Unverified Commit 202bba59 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Trace active Tokio worker threads with memory samples (#99233)

## What?

Record the number of non-idle Tokio scheduler worker threads alongside
Turbopack's existing process-memory samples. The span-query API and MCP
output expose it as the fourth value in each memory sample. The
WebSocket query result adds a parallel worker series for visualization
in
[vercel/turbo-trace-viewer#33](https://github.com/vercel/turbo-trace-viewer/pull/33),
retaining the original memory-only series.

## Why?

Memory samples alone do not show whether Tokio's workers were busy or
parked at a given point in a trace. The aligned worker count makes it
easier to correlate memory changes and traced work with scheduler
activity.

## How?

Each traced runtime builder initializes one global atomic counter with
its worker capacity, then Tokio's worker-only park/unpark callbacks
adjust it. This avoids counting blocking-pool threads and assumes one
traced Tokio runtime per process; shutdown bookkeeping is unnecessary
for this metric. The counter is read at the existing memory-sampling
cadence rather than emitting trace rows on each worker transition. Trace
ingestion, span-query downsampling, and the WebSocket worker series
preserve the count from the same sample as the selected memory value.

## Verification

- `cargo test --locked -p turbopack-trace-utils -p
turbopack-trace-server`
- `cargo check --locked -p turbopack-cli -p turbopack-nft -p
next-build-test -p next-napi-bindings`
- `cargo fmt --all -- --check`; `git diff --check`
- Not run: Next.js TypeScript/prettier/full build (checkout has no
`node_modules`).

<!-- NEXT_JS_LLM -->


<!-- fleet 0c297c2c-8e55-4012-be8a-752ff8175d1b -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent fa8dcf34
......@@ -17,7 +17,8 @@ use turbo_tasks::TurboTasks;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_malloc::TurboMalloc;
use turbopack_trace_utils::{
exit::ExitGuard, filter_layer::FilterLayer, raw_trace::RawTraceLayer, trace_writer::TraceWriter,
exit::ExitGuard, filter_layer::FilterLayer, raw_trace::RawTraceLayer, tokio_workers,
trace_writer::TraceWriter,
};
#[global_allocator]
......@@ -79,6 +80,7 @@ fn main() {
thread_local! {
static LAST_SWC_ATOM_GC_TIME: RefCell<Option<Instant>> = const { RefCell::new(None) };
}
tokio_workers::set_worker_threads(tokio_workers::default_worker_threads());
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.on_thread_stop(|| {
......@@ -86,6 +88,7 @@ fn main() {
tracing::debug!("threads stopped");
})
.on_thread_park(|| {
tokio_workers::park();
LAST_SWC_ATOM_GC_TIME.with_borrow_mut(|cell| {
if cell.is_none_or(|t| t.elapsed() > Duration::from_secs(2)) {
swc_core::ecma::atoms::hstr::global_atom_store_gc();
......@@ -94,6 +97,7 @@ fn main() {
});
TurboMalloc::thread_park();
})
.on_thread_unpark(tokio_workers::unpark)
.build()
.unwrap()
.block_on(async {
......
......@@ -80,6 +80,7 @@ fn init() {
use tokio::runtime::Builder;
use turbo_tasks::{panic_hooks::handle_panic, parallel::available_parallelism};
use turbo_tasks_malloc::TurboMalloc;
use turbopack_trace_utils::tokio_workers;
let prev_hook = take_hook();
set_hook(Box::new(move |info| {
......@@ -88,6 +89,7 @@ fn init() {
}));
let worker_threads = available_parallelism().map(|n| n.get()).unwrap_or(1);
tokio_workers::set_worker_threads(worker_threads);
let rt = Builder::new_multi_thread()
.enable_all()
......@@ -95,6 +97,7 @@ fn init() {
TurboMalloc::thread_stop();
})
.on_thread_park(|| {
tokio_workers::park();
LAST_SWC_ATOM_GC_TIME.with_borrow_mut(|cell| {
if cell.is_none_or(|t| t.elapsed() > Duration::from_secs(2)) {
swc_core::ecma::atoms::hstr::global_atom_store_gc();
......@@ -103,6 +106,7 @@ fn init() {
});
TurboMalloc::thread_park();
})
.on_thread_unpark(tokio_workers::unpark)
.worker_threads(worker_threads)
// Avoid a limit on threads to avoid deadlocks due to usage of block_in_place
.max_blocking_threads(usize::MAX - worker_threads)
......
......@@ -126,18 +126,19 @@ pub struct TraceSpanInfo {
/// Number of allocation operations by this span itself, excluding children.
/// Group total for aggregated spans.
pub self_allocation_count: i64,
/// TurboMalloc memory-usage samples recorded while this span
/// (or its example span, for aggregated groups) was live.
/// Process samples recorded while this span (or its example span, for
/// aggregated groups) was live.
///
/// **Process-wide, not per-span.** One global series is sliced by the
/// span's time range, so spans that overlap in time report identical values
/// no matter what each allocated. Rank concurrent work by the allocation
/// fields instead.
///
/// Each entry is `[ts_offset_from_span_start_in_ticks, bytes, pressure]`,
/// where `pressure` is the memory-pressure byte (0 = no pressure, higher
/// = more pressure). `100 ticks = 1 µs`. The offset is always `>= 0` and
/// `<= span_duration`. Capped and downsampled by the store.
/// Each entry is `[ts_offset_from_span_start_in_ticks, bytes, pressure,
/// active_worker_threads]`: `bytes` is TurboMalloc memory usage,
/// `pressure` is the memory-pressure byte (0 = no pressure, higher = more
/// pressure), and `active_worker_threads` counts non-parked Tokio scheduler
/// workers. `100 ticks = 1 µs`. Capped and downsampled by the store.
pub memory_samples: Vec<Vec<i64>>,
/// Summary of `memorySamples`; absent when the span's range holds none.
/// Unlike the allocation counters these are absolute live-heap readings, so
......@@ -214,7 +215,9 @@ fn convert_span(s: turbopack_trace_server::SpanInfo) -> TraceSpanInfo {
memory_samples: s
.memory_samples
.into_iter()
.map(|(ts, mem, pressure)| vec![ts, mem as i64, pressure as i64])
.map(|(ts, mem, pressure, workers)| {
vec![ts, mem as i64, pressure as i64, workers as i64]
})
.collect(),
memory_summary: s.memory_summary.map(|m| TraceMemorySummary {
count: m.count as u32,
......
......@@ -945,18 +945,19 @@ export interface TraceSpanInfo {
*/
selfAllocationCount: number
/**
* TurboMalloc memory-usage samples recorded while this span
* (or its example span, for aggregated groups) was live.
* Process samples recorded while this span (or its example span, for
* aggregated groups) was live.
*
* **Process-wide, not per-span.** One global series is sliced by the
* span's time range, so spans that overlap in time report identical values
* no matter what each allocated. Rank concurrent work by the allocation
* fields instead.
*
* Each entry is `[ts_offset_from_span_start_in_ticks, bytes, pressure]`,
* where `pressure` is the memory-pressure byte (0 = no pressure, higher
* = more pressure). `100 ticks = 1 µs`. The offset is always `>= 0` and
* `<= span_duration`. Capped and downsampled by the store.
* Each entry is `[ts_offset_from_span_start_in_ticks, bytes, pressure,
* active_worker_threads]`: `bytes` is TurboMalloc memory usage,
* `pressure` is the memory-pressure byte (0 = no pressure, higher = more
* pressure), and `active_worker_threads` counts non-parked Tokio scheduler
* workers. `100 ticks = 1 µs`. Capped and downsampled by the store.
*/
memorySamples: Array<Array<number>>
/**
......
......@@ -86,10 +86,12 @@ function summarizeMemorySamples(span: TraceSpanInfo): string | null {
if (!summary) return null
const delta = summary.end - summary.start
const deltaSign = delta >= 0 ? '+' : '-'
const workers = span.memorySamples.map((s) => s[3])
return (
`samples=${summary.count}, peak=${formatBytes(summary.peak)}, min=${formatBytes(summary.min)}, ` +
`start=${formatBytes(summary.start)}, end=${formatBytes(summary.end)}, ` +
`Δ=${deltaSign}${formatBytes(Math.abs(delta))}, maxPressure=${summary.maxPressure}`
`Δ=${deltaSign}${formatBytes(Math.abs(delta))}, maxPressure=${summary.maxPressure}, ` +
`activeWorkerThreads=${Math.min(...workers)}–${Math.max(...workers)}`
)
}
......@@ -149,7 +151,7 @@ function renderSpanMarkdown(
const memSummary = summarizeMemorySamples(span)
if (memSummary) {
md += `\n**Memory (TurboMalloc live bytes):** ${memSummary}\n`
md += `\n**Process samples (TurboMalloc live bytes, memory pressure, active Tokio workers):** ${memSummary}\n`
}
if (span.children.length > 0) {
......@@ -224,7 +226,7 @@ export async function startTurboTraceServerCli(
'',
'For aggregated groups every allocation field is a group total, while `cpuDuration`, `correctedDuration` and `memorySamples` describe the example span only. `firstSpanId` is first in execution order; use `heaviestSpanId` to reach the member holding the most bytes.',
'',
'Set `outputType: "json"` for full precision and the raw `memorySamples` triples `[tsOffsetTicks, bytes, pressure]`; markdown is a human summary.',
'Set `outputType: "json"` for full precision and the raw `memorySamples` entries `[tsOffsetTicks, bytes, pressure, active_worker_threads]` (active_worker_threads excludes parked and blocking-pool threads); markdown is a human summary.',
].join('\n'),
inputSchema: {
parent: z
......
......@@ -10,6 +10,7 @@ use turbopack_trace_utils::{
exit::ExitHandler,
filter_layer::FilterLayer,
raw_trace::RawTraceLayer,
tokio_workers,
trace_writer::TraceWriter,
tracing_presets::{
TRACING_OVERVIEW_TARGETS, TRACING_TURBO_TASKS_TARGETS, TRACING_TURBOPACK_TARGETS,
......@@ -25,21 +26,9 @@ fn main() {
}
let mut rt = tokio::runtime::Builder::new_multi_thread();
rt.enable_all()
.on_thread_stop(|| {
TurboMalloc::thread_stop();
})
.on_thread_park(|| {
LAST_SWC_ATOM_GC_TIME.with_borrow_mut(|cell| {
use std::time::Duration;
if cell.is_none_or(|t| t.elapsed() > Duration::from_secs(2)) {
swc_core::ecma::atoms::hstr::global_atom_store_gc();
*cell = Some(Instant::now());
}
});
TurboMalloc::thread_park();
});
rt.enable_all().on_thread_stop(|| {
TurboMalloc::thread_stop();
});
let args = Arguments::parse();
......@@ -54,6 +43,20 @@ fn main() {
})
.unwrap_or_else(|| available_parallelism().map(|n| n.get()).unwrap_or(1));
tokio_workers::set_worker_threads(worker_threads);
rt.on_thread_park(|| {
tokio_workers::park();
LAST_SWC_ATOM_GC_TIME.with_borrow_mut(|cell| {
use std::time::Duration;
if cell.is_none_or(|t| t.elapsed() > Duration::from_secs(2)) {
swc_core::ecma::atoms::hstr::global_atom_store_gc();
*cell = Some(Instant::now());
}
});
TurboMalloc::thread_park();
})
.on_thread_unpark(tokio_workers::unpark);
rt.worker_threads(worker_threads);
rt.max_blocking_threads(usize::MAX - worker_threads);
......
......@@ -14,6 +14,7 @@ use turbopack_trace_utils::{
exit::ExitHandler,
filter_layer::FilterLayer,
raw_trace::RawTraceLayer,
tokio_workers,
trace_writer::TraceWriter,
tracing_presets::{
TRACING_OVERVIEW_TARGETS, TRACING_TURBO_TASKS_TARGETS, TRACING_TURBOPACK_TARGETS,
......@@ -40,8 +41,12 @@ pub struct Arguments {
static ALLOC: TurboMalloc = TurboMalloc;
fn main() {
tokio_workers::set_worker_threads(tokio_workers::default_worker_threads());
let mut rt = tokio::runtime::Builder::new_multi_thread();
rt.enable_all().disable_lifo_slot();
rt.enable_all()
.disable_lifo_slot()
.on_thread_park(tokio_workers::park)
.on_thread_unpark(tokio_workers::unpark);
let args = Arguments::parse();
rt.build().unwrap().block_on(main_inner(args)).unwrap();
......
......@@ -25,6 +25,8 @@ use self::{
mod bottom_up;
mod chunked_vec;
mod lazy_sorted_vec;
#[cfg(test)]
mod query_tests;
mod reader;
mod self_time_tree;
mod server;
......@@ -213,8 +215,8 @@ pub struct SpanInfo {
/// Number of allocation operations by this span itself, excluding children.
/// Group total for aggregated spans.
pub self_allocation_count: u64,
/// TurboMalloc memory-usage samples recorded while this span (or its
/// example span, for aggregated groups) was live.
/// Process samples recorded while this span (or its example span, for
/// aggregated groups) was live.
///
/// **Process-wide, not per-span.** There is one global sample series, and a
/// span's samples are just the slice covering its time range, so spans that
......@@ -222,16 +224,16 @@ pub struct SpanInfo {
/// Rank concurrent work by the allocation fields; use these for absolute
/// memory over a span that dominates its window.
///
/// Each tuple is `(ts_offset_from_span_start_in_ticks, bytes, pressure)`,
/// where `pressure` is the memory-pressure byte recorded with the sample
/// (0 = no pressure, higher = more pressure). `100 ticks = 1 µs`. The
/// offset is always `>= 0` and `<= span_duration`.
/// Each tuple is `(ts_offset_from_span_start_in_ticks, bytes, pressure,
/// active_worker_threads)`. `bytes` is TurboMalloc memory usage;
/// `pressure` is the memory-pressure byte (0 = no pressure, higher =
/// more pressure), and `active_worker_threads` counts non-parked Tokio
/// scheduler workers. `100 ticks = 1 µs`. The offset is within the span.
///
/// The store caps the series at `MAX_MEMORY_SAMPLES`; when more samples
/// exist in the range, consecutive groups are merged by picking the
/// group's max-memory sample (timestamp, value, and pressure kept
/// together).
pub memory_samples: Vec<(i64, u64, u8)>,
/// exist, groups are merged by picking the group's max-memory sample,
/// retaining its timestamp, pressure and worker count.
pub memory_samples: Vec<(i64, u64, u8, u64)>,
/// Summary of `memory_samples`. `None` when the span's range holds none.
pub memory_summary: Option<MemorySummary>,
/// Descendants of this span, populated only when `QueryOptions::depth` is
......@@ -261,8 +263,8 @@ pub struct MemorySummary {
impl MemorySummary {
/// Summarize a sample series, or `None` if it is empty.
fn from_samples(samples: &[(i64, u64, u8)]) -> Option<Self> {
let (_, first_bytes, first_pressure) = *samples.first()?;
fn from_samples(samples: &[(i64, u64, u8, u64)]) -> Option<Self> {
let (_, first_bytes, first_pressure, _) = *samples.first()?;
let mut summary = MemorySummary {
count: samples.len(),
start: first_bytes,
......@@ -271,7 +273,7 @@ impl MemorySummary {
peak: first_bytes,
max_pressure: first_pressure,
};
for &(_, bytes, pressure) in &samples[1..] {
for &(_, bytes, pressure, _) in &samples[1..] {
summary.min = summary.min.min(bytes);
summary.peak = summary.peak.max(bytes);
summary.max_pressure = summary.max_pressure.max(pressure);
......@@ -495,12 +497,12 @@ fn sort_spans(items: &mut [Located<SpanRef<'_>>], sort: SortMode) {
}
/// Memory samples recorded while `span` was live, offset from its start.
fn memory_samples_for(store: &store::Store, span: &SpanRef<'_>) -> Vec<(i64, u64, u8)> {
fn memory_samples_for(store: &store::Store, span: &SpanRef<'_>) -> Vec<(i64, u64, u8, u64)> {
let span_start = *span.start() as i64;
store
.memory_samples_for_range_with_ts(span.start(), span.end())
.into_iter()
.map(|(ts, mem, pressure)| ((*ts as i64) - span_start, mem, pressure))
.map(|(ts, mem, pressure, workers)| ((*ts as i64) - span_start, mem, pressure, workers))
.collect()
}
......@@ -1256,7 +1258,7 @@ mod tests {
#[test]
fn memory_summary_reports_peak_not_last() {
let samples = [(0i64, 100u64, 0u8), (1, 900, 3), (2, 200, 1)];
let samples = [(0i64, 100u64, 0u8, 2u64), (1, 900, 3, 1), (2, 200, 1, 3)];
let summary = MemorySummary::from_samples(&samples).expect("samples present");
assert_eq!(summary.count, 3);
assert_eq!(summary.start, 100);
......
use std::sync::Arc;
use turbopack_trace_utils::tracing::TraceRow;
use crate::{
QueryOptions, SortMode, query_spans,
reader::{TraceFormat, turbopack::TurbopackFormat},
store_container::StoreContainer,
timestamp::Timestamp,
};
#[test]
fn reads_active_workers_and_exposes_them_in_span_queries() {
let store = Arc::new(StoreContainer::new());
let mut format = TurbopackFormat::new(store.clone());
let rows = [
TraceRow::Start {
ts: 10,
id: 1,
parent: None,
name: "test".into(),
target: "test".into(),
values: vec![],
},
TraceRow::Enter {
ts: 10,
id: 1,
thread_id: 1,
},
TraceRow::MemorySample {
ts: 20,
memory: 1234,
memory_pressure: 7,
active_worker_threads: 2,
},
TraceRow::Exit {
ts: 30,
id: 1,
thread_id: 1,
},
TraceRow::End { ts: 30, id: 1 },
];
let mut bytes = Vec::new();
for row in rows {
bytes.extend(postcard::to_stdvec(&row).unwrap());
}
assert_eq!(
format
.read(&bytes, &mut TurbopackFormat::create_reused())
.unwrap(),
bytes.len()
);
let samples = store
.read()
.memory_samples_for_range_with_ts(Timestamp::from_micros(10), Timestamp::from_micros(30));
assert_eq!(samples[0].1, 1234);
assert_eq!(samples[0].2, 7);
assert_eq!(samples[0].3, 2);
for aggregated in [false, true] {
let result = query_spans(
&store,
QueryOptions {
parent: None,
aggregated,
sort: SortMode::ExecutionOrder,
search: None,
max_depth: u32::MAX,
depth: 1,
page: 1,
page_size: None,
},
);
assert_eq!(result.spans.len(), 1);
assert_eq!(result.spans[0].memory_samples, vec![(1000, 1234, 7, 2)]);
}
}
mod heaptrack;
mod nextjs;
mod turbopack;
pub(crate) mod turbopack;
use std::{
any::Any,
......@@ -23,7 +23,7 @@ use crate::{
const MIN_INITIAL_REPORT_SIZE: u64 = 100 * 1024 * 1024;
trait TraceFormat {
pub(crate) trait TraceFormat {
type Reused: Default;
/// Create the initial reused buffer. Override to pre-allocate capacity.
fn create_reused() -> Self::Reused {
......
......@@ -287,9 +287,10 @@ impl TurbopackFormat {
ts,
memory,
memory_pressure,
active_worker_threads,
} => {
let ts = Timestamp::from_micros(ts);
store.add_memory_sample(ts, memory, memory_pressure);
store.add_memory_sample(ts, memory, memory_pressure, active_worker_threads);
}
TraceRow::AllocationCounters {
ts: _,
......
......@@ -45,6 +45,7 @@ pub enum ServerToClientMessage {
path: Vec<String>,
memory_samples: Vec<u64>,
memory_pressure_samples: Vec<u8>,
active_worker_threads_samples: Vec<u64>,
},
}
......@@ -297,6 +298,11 @@ fn handle_connection(
store.memory_samples_for_range(span.start(), span.end());
let memory_pressure_samples = store
.memory_pressure_samples_for_range(span.start(), span.end());
let active_worker_threads_samples = store
.active_worker_threads_samples_for_range(
span.start(),
span.end(),
);
ServerToClientMessage::QueryResult {
id,
is_graph,
......@@ -312,6 +318,7 @@ fn handle_connection(
path,
memory_samples,
memory_pressure_samples,
active_worker_threads_samples,
}
} else {
ServerToClientMessage::QueryResult {
......@@ -329,6 +336,7 @@ fn handle_connection(
path: Vec::new(),
memory_samples: Vec::new(),
memory_pressure_samples: Vec::new(),
active_worker_threads_samples: Vec::new(),
}
}
};
......@@ -374,3 +382,33 @@ fn handle_connection(
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn query_result_serializes_worker_samples_in_camel_case() {
let message = ServerToClientMessage::QueryResult {
id: SpanId::new(1).unwrap(),
is_graph: false,
start: Timestamp::ZERO,
end: Timestamp::ZERO,
duration: Timestamp::ZERO,
cpu: Timestamp::ZERO,
allocations: 0,
deallocations: 0,
allocation_count: 0,
persistent_allocations: 0,
args: Vec::new(),
path: Vec::new(),
memory_samples: vec![1024],
memory_pressure_samples: vec![2],
active_worker_threads_samples: vec![3],
};
let json = serde_json::to_value(message).unwrap();
assert_eq!(json["type"], "query-result");
assert_eq!(json["memorySamples"], serde_json::json!([1024]));
assert_eq!(json["activeWorkerThreadsSamples"], serde_json::json!([3]));
}
}
......@@ -24,11 +24,10 @@ pub type SpanId = NonZeroUsize;
/// at the cut-off depth (Flattening).
const CUT_OFF_DEPTH: u32 = 80;
/// A single memory usage sample: (timestamp, memory_bytes, memory_pressure).
/// Sorted by timestamp. `memory_pressure` is an OS-reported pressure value in
/// the range `0..=100`; `0` is used when the reporter platform did not expose
/// a pressure signal.
type MemorySample = (Timestamp, u64, u8);
/// A single process sample: (timestamp, memory_bytes, memory_pressure,
/// active_worker_threads). Sorted by timestamp. `memory_pressure` is an
/// OS-reported value in `0..=100`; `0` is used if unavailable.
type MemorySample = (Timestamp, u64, u8, u64);
/// Maximum number of memory samples returned in a query result.
const MAX_MEMORY_SAMPLES: usize = 200;
......@@ -37,7 +36,7 @@ pub struct Store {
pub(crate) spans: ChunkedVec<Span>,
pub(crate) self_time_tree: Option<SelfTimeTree<SpanIndex>>,
max_self_time_lookup_time: AtomicU64,
/// Global sorted list of memory samples (timestamp, memory_bytes).
/// Global sorted list of process memory and worker samples.
memory_samples: Vec<MemorySample>,
}
......@@ -341,11 +340,18 @@ impl Store {
span.self_deallocation_count += count;
}
pub fn add_memory_sample(&mut self, ts: Timestamp, memory: u64, memory_pressure: u8) {
pub fn add_memory_sample(
&mut self,
ts: Timestamp,
memory: u64,
memory_pressure: u8,
active_worker_threads: u64,
) {
// Samples arrive nearly sorted (roughly chronological from the trace
// writer), so an insertion-sort step is efficient: push to the end
// then swap backward until the timestamp ordering is restored.
self.memory_samples.push((ts, memory, memory_pressure));
self.memory_samples
.push((ts, memory, memory_pressure, active_worker_threads));
let mut i = self.memory_samples.len() - 1;
while i > 0 && self.memory_samples[i - 1].0 > ts {
self.memory_samples.swap(i, i - 1);
......@@ -359,16 +365,16 @@ impl Store {
pub fn memory_samples_for_range(&self, start: Timestamp, end: Timestamp) -> Vec<u64> {
self.memory_samples_for_range_with_ts(start, end)
.into_iter()
.map(|(_, mem, _)| mem)
.map(|(_, mem, _, _)| mem)
.collect()
}
/// Like `memory_samples_for_range` but keeps the timestamps and the
/// memory-pressure byte. Timestamps are absolute store timestamps (same
/// reference frame as span start/end). When the raw slice exceeds
/// `MAX_MEMORY_SAMPLES`, each merged group is represented by the sample
/// whose memory value was the group's max (its timestamp and pressure
/// byte are kept alongside it).
/// memory-pressure byte and active worker count. Timestamps are absolute
/// store timestamps (same reference frame as span start/end). When the raw
/// slice exceeds `MAX_MEMORY_SAMPLES`, each merged group is represented by
/// the sample whose memory value was the group's max (its timestamp,
/// pressure, and worker count are kept alongside it).
pub fn memory_samples_for_range_with_ts(
&self,
start: Timestamp,
......@@ -389,7 +395,20 @@ impl Store {
let n = count.div_ceil(MAX_MEMORY_SAMPLES);
slice
.chunks(n)
.map(|chunk| *chunk.iter().max_by_key(|(_, mem, _)| *mem).unwrap())
.map(|chunk| *chunk.iter().max_by_key(|(_, mem, _, _)| *mem).unwrap())
.collect()
}
/// Returns worker counts from the same max-memory samples selected by
/// [`Self::memory_samples_for_range`], in the same order.
pub fn active_worker_threads_samples_for_range(
&self,
start: Timestamp,
end: Timestamp,
) -> Vec<u64> {
self.memory_samples_for_range_with_ts(start, end)
.into_iter()
.map(|(_, _, _, workers)| workers)
.collect()
}
......@@ -406,13 +425,13 @@ impl Store {
}
if count <= MAX_MEMORY_SAMPLES {
return slice.iter().map(|(_, _, p)| *p).collect();
return slice.iter().map(|(_, _, p, _)| *p).collect();
}
let n = count.div_ceil(MAX_MEMORY_SAMPLES);
slice
.chunks(n)
.map(|chunk| chunk.iter().map(|(_, _, p)| *p).max().unwrap())
.map(|chunk| chunk.iter().map(|(_, _, p, _)| *p).max().unwrap())
.collect()
}
......@@ -420,9 +439,11 @@ impl Store {
// Binary search for the first sample >= start
let lo = self
.memory_samples
.partition_point(|(ts, _, _)| *ts < start);
.partition_point(|(ts, _, _, _)| *ts < start);
// Binary search for the first sample > end
let hi = self.memory_samples.partition_point(|(ts, _, _)| *ts <= end);
let hi = self
.memory_samples
.partition_point(|(ts, _, _, _)| *ts <= end);
&self.memory_samples[lo..hi]
}
......@@ -498,3 +519,47 @@ impl Store {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn downsampling_keeps_worker_count_from_max_memory_sample() {
let mut store = Store::new();
for i in 0..=MAX_MEMORY_SAMPLES {
store.add_memory_sample(Timestamp::from_micros(i as u64), i as u64, 3, 1);
}
store.add_memory_sample(Timestamp::from_micros(201), 5000, 9, 4);
let samples = store.memory_samples_for_range_with_ts(
Timestamp::from_micros(0),
Timestamp::from_micros(201),
);
assert!(samples.len() <= MAX_MEMORY_SAMPLES);
assert!(samples.iter().any(|(_, mem, pressure, workers)| {
*mem == 5000 && *pressure == 9 && *workers == 4
}));
let start = Timestamp::from_micros(0);
let end = Timestamp::from_micros(201);
let memory = store.memory_samples_for_range(start, end);
let workers = store.active_worker_threads_samples_for_range(start, end);
assert_eq!(workers.len(), memory.len());
assert_eq!(
workers,
samples.iter().map(|sample| sample.3).collect::<Vec<_>>()
);
assert_eq!(
memory
.iter()
.position(|&value| value == 5000)
.map(|i| workers[i]),
Some(4)
);
assert!(
store
.active_worker_threads_samples_for_range(Timestamp::from_micros(202), end)
.is_empty()
);
}
}
......@@ -19,7 +19,7 @@ parking_lot = { workspace = true }
postcard = { workspace = true, features = ["alloc", "use-std"] }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
tokio = { workspace = true, features = ["macros", "signal", "sync", "rt"] }
tokio = { workspace = true, features = ["macros", "signal", "sync", "rt-multi-thread"] }
thread_local = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
......
......@@ -7,6 +7,7 @@ pub mod exit;
pub mod filter_layer;
mod flavor;
pub mod raw_trace;
pub mod tokio_workers;
pub mod trace_writer;
pub mod tracing;
pub mod tracing_presets;
......@@ -18,6 +18,7 @@ use turbo_tasks_malloc::TurboMalloc;
use crate::{
flavor::WriteGuardFlavor,
tokio_workers::active_worker_threads,
trace_writer::TraceWriter,
tracing::{TraceRow, TraceValue},
};
......@@ -107,6 +108,7 @@ impl<S: Subscriber + for<'a> LookupSpan<'a>> RawTraceLayer<S> {
ts,
memory,
memory_pressure,
active_worker_threads: active_worker_threads() as u64,
});
}
Err(actual) => {
......
use std::sync::atomic::{AtomicUsize, Ordering};
static ACTIVE_WORKER_THREADS: AtomicUsize = AtomicUsize::new(0);
/// Initialize the count of non-parked scheduler workers before building the
/// process's Tokio runtime. Tokio's thread start/stop hooks also include the
/// blocking pool, while park/unpark hooks apply only to scheduler workers.
///
/// This assumes a single traced Tokio runtime per process. We do not adjust
/// the count when the runtime shuts down.
pub fn set_worker_threads(worker_threads: usize) {
ACTIVE_WORKER_THREADS.store(worker_threads, Ordering::Relaxed);
}
pub fn park() {
ACTIVE_WORKER_THREADS.fetch_sub(1, Ordering::Relaxed);
}
pub fn unpark() {
ACTIVE_WORKER_THREADS.fetch_add(1, Ordering::Relaxed);
}
pub fn active_worker_threads() -> usize {
ACTIVE_WORKER_THREADS.load(Ordering::Relaxed)
}
/// Match Tokio's default worker count when a runtime does not set it explicitly.
pub fn default_worker_threads() -> usize {
match std::env::var("TOKIO_WORKER_THREADS") {
Ok(value) => {
let count: usize = value.parse().expect("TOKIO_WORKER_THREADS must be usize");
assert!(count > 0, "TOKIO_WORKER_THREADS cannot be set to 0");
count
}
Err(std::env::VarError::NotPresent) => {
std::thread::available_parallelism().map_or(1, |n| n.get())
}
Err(error) => panic!("TOKIO_WORKER_THREADS must be valid unicode: {error}"),
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{Arc, Barrier, mpsc},
time::Duration,
};
use super::*;
#[test]
fn counts_scheduler_workers_but_not_blocking_threads() {
set_worker_threads(2);
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder
.worker_threads(2)
.on_thread_park(park)
.on_thread_unpark(unpark);
let rt = builder.build().unwrap();
assert_eq!(active_worker_threads(), 2);
let (tx, rx) = mpsc::channel();
rt.spawn_blocking(move || tx.send(()).unwrap());
rx.recv_timeout(Duration::from_secs(5)).unwrap();
// All workers should park after the runtime has become idle.
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while active_worker_threads() != 0 {
assert!(std::time::Instant::now() < deadline, "workers did not park");
std::thread::yield_now();
}
let barrier = Arc::new(Barrier::new(2));
let worker_barrier = barrier.clone();
let (started_tx, started_rx) = mpsc::channel();
rt.spawn(async move {
started_tx.send(()).unwrap();
worker_barrier.wait();
});
started_rx.recv_timeout(Duration::from_secs(5)).unwrap();
assert!(active_worker_threads() > 0);
barrier.wait();
}
}
......@@ -100,7 +100,7 @@ pub enum TraceRow<'a> {
/// Deallocation count
deallocation_count: u64,
},
/// A snapshot of the process memory usage at a point in time.
/// A snapshot of process memory and non-idle Tokio scheduler workers.
MemorySample {
/// Timestamp
ts: u64,
......@@ -110,6 +110,8 @@ pub enum TraceRow<'a> {
/// `TurboMalloc::memory_pressure()`). `0` is used when the current
/// platform does not report a pressure value.
memory_pressure: u8,
/// Number of non-parked Tokio scheduler worker threads in this process.
active_worker_threads: u64,
},
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment