Unverified Commit 2d5a45a5 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Add allocation and memory data to the trace-server MCP protocol (#98546)

### What?

Makes the trace-server MCP tool usable for memory investigations and
improve usability/performance based on agent feedback ♾️

* Spans now report allocation data (`allocations` / `deallocations` /
`persistentAllocations` / `allocationCount`, each with a `self*`
counterpart excluding children), plus `memorySummary` and
`heaviestSpanId`.

* `search` became recursive, and `depth` / `pageSize` were added so a
caller can pull a subtree or a wide page in one call instead of one
round-trip per level.

---------
Co-authored-by: 's avatarClaude Opus 5 (1M context) <noreply@anthropic.com>
parent 86d92b94
......@@ -22,13 +22,29 @@ pub struct TraceQueryOptions {
pub parent: Option<String>,
/// When `true` (default), aggregate child spans with the same name.
pub aggregated: Option<bool>,
/// Sort mode: `"value"` for duration descending, `"name"` for alphabetical.
/// Sort mode: `"value"` for duration descending, `"name"` for alphabetical,
/// `"allocations"` for total allocated bytes descending,
/// `"persistent-allocations"` for `persistentAllocations` descending.
/// Omit for execution order (no sorting).
pub sort: Option<String>,
/// Optional substring search query applied to span name/category.
///
/// Matches anywhere in the parent's subtree. Each result's `id` is the full
/// path from `parent` to the match, so it can be passed back as `parent`.
///
/// Cost scales with subtree size, so a root search on a large trace walks
/// everything. Setting `parent`, or lowering `maxDepth`, bounds it.
pub search: Option<String>,
/// Maximum depth to descend below `parent` for `search` and `depth`.
/// Default `32`, which is also the cap.
pub max_depth: Option<u32>,
/// When greater than `1`, each returned span carries this many levels of
/// descendants inline in `children`. Default `1` (no nesting).
pub depth: Option<u32>,
/// 1-based page number. Default `1`.
pub page: Option<u32>,
/// Spans per page. Default `20`, capped at `500`.
pub page_size: Option<u32>,
}
/// Information about a single span or aggregated span group.
......@@ -60,16 +76,92 @@ pub struct TraceSpanInfo {
pub total_corrected_duration: Option<i64>,
/// Average corrected duration across spans in the group.
pub avg_corrected_duration: Option<i64>,
/// Raw span ID for aggregated groups (the index of the first span).
/// Raw span ID of the group's example span, whose `cpuDuration`,
/// `correctedDuration` and `memorySamples` are the ones reported here.
/// First in execution order — *not* the largest, so it can badly understate
/// a group's allocations. Use `heaviestSpanId` for those.
pub first_span_id: Option<String>,
/// Raw span ID of the group member with the largest persistent
/// allocations.
pub heaviest_span_id: Option<String>,
/// Total bytes allocated by this span and all its children.
///
/// For aggregated groups this is the group total, unlike `cpuDuration`,
/// `correctedDuration` and `memorySamples`, which describe the example span
/// only. Every allocation field below follows this field, not those.
pub allocations: i64,
/// Total bytes deallocated by this span and all its children.
/// Group total for aggregated spans.
pub deallocations: i64,
/// Sum over each span of `max(0, selfAllocations - selfDeallocations)`,
/// for this span and its children. Group total for aggregated spans.
///
/// **A ranking signal, not retained memory.** TurboMalloc's per-span
/// counters never observe turbo-tasks cell and cache drops, so a
/// whole-trace total far above real peak RSS is expected, not a leak. Use
/// `memorySummary.peak` for absolute memory.
///
/// The per-span floor at zero is also why this is not
/// `allocations - deallocations`.
pub persistent_allocations: i64,
/// Number of allocation operations by this span and all its children.
/// Group total for aggregated spans.
pub allocation_count: i64,
/// Bytes allocated by this span itself, excluding children.
/// Group total for aggregated spans.
pub self_allocations: i64,
/// Bytes deallocated by this span itself, excluding children.
/// Group total for aggregated spans.
///
/// Frees are charged to whichever span was on top of the thread's stack at
/// free time, which is often not the span that allocated. So small
/// `selfAllocations` with large `selfDeallocations` means this span is
/// where a child's arena gets dropped — that arena is bounded, not leaking.
/// The shape to suspect is a large `selfPersistentAllocations` with no such
/// counterpart above it.
pub self_deallocations: i64,
/// `max(0, selfAllocations - selfDeallocations)` for this span alone.
/// Group total for aggregated spans.
pub self_persistent_allocations: i64,
/// 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-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.
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
/// `peak` is the figure to quote for memory actually in use.
pub memory_summary: Option<TraceMemorySummary>,
/// Descendants of this span, populated only when `depth > 1`.
pub children: Vec<TraceSpanInfo>,
}
/// Aggregate view of a span's TurboMalloc memory samples.
#[napi(object)]
pub struct TraceMemorySummary {
/// Number of samples in the span's range, after downsampling.
pub count: u32,
/// Live bytes at the first sample in the range.
pub start: i64,
/// Live bytes at the last sample in the range.
pub end: i64,
/// Smallest live-bytes reading in the range.
pub min: i64,
/// Largest live-bytes reading in the range — the span's peak memory.
pub peak: i64,
/// Highest memory-pressure byte in the range (0 = no pressure).
pub max_pressure: u8,
}
/// The result of a `query_trace_spans` call.
......@@ -93,6 +185,49 @@ pub fn start_turbopack_trace_server_handle(path: String, port: Option<u16>) -> T
TraceServerHandle { store }
}
/// Convert a core `SpanInfo` and its nested children into the napi shape.
fn convert_span(s: turbopack_trace_server::SpanInfo) -> TraceSpanInfo {
TraceSpanInfo {
id: s.id,
name: s.name,
cpu_duration: s.cpu_duration as i64,
corrected_duration: s.corrected_duration as i64,
start_relative_to_parent: s.start_relative_to_parent,
end_relative_to_parent: s.end_relative_to_parent,
args: s.args.into_iter().map(|(k, v)| vec![k, v]).collect(),
is_aggregated: s.is_aggregated,
count: s.count.map(|c| c as i64),
total_cpu_duration: s.total_cpu_duration.map(|v| v as i64),
avg_cpu_duration: s.avg_cpu_duration.map(|v| v as i64),
total_corrected_duration: s.total_corrected_duration.map(|v| v as i64),
avg_corrected_duration: s.avg_corrected_duration.map(|v| v as i64),
first_span_id: s.first_span_id,
heaviest_span_id: s.heaviest_span_id,
allocations: s.allocations as i64,
deallocations: s.deallocations as i64,
persistent_allocations: s.persistent_allocations as i64,
allocation_count: s.allocation_count as i64,
self_allocations: s.self_allocations as i64,
self_deallocations: s.self_deallocations as i64,
self_persistent_allocations: s.self_persistent_allocations as i64,
self_allocation_count: s.self_allocation_count as i64,
memory_samples: s
.memory_samples
.into_iter()
.map(|(ts, mem, pressure)| vec![ts, mem as i64, pressure as i64])
.collect(),
memory_summary: s.memory_summary.map(|m| TraceMemorySummary {
count: m.count as u32,
start: m.start as i64,
end: m.end as i64,
min: m.min as i64,
peak: m.peak as i64,
max_pressure: m.max_pressure,
}),
children: s.children.into_iter().map(convert_span).collect(),
}
}
/// Query spans from the trace store held by a `TraceServerHandle`.
#[napi]
pub fn query_trace_spans(
......@@ -107,39 +242,20 @@ pub fn query_trace_spans(
sort: match options.sort.as_deref() {
Some("value") => SortMode::Value,
Some("name") => SortMode::Name,
Some("allocations") => SortMode::Allocations,
Some("persistent-allocations") => SortMode::PersistentAllocations,
_ => SortMode::ExecutionOrder,
},
search: options.search,
max_depth: options.max_depth.unwrap_or(u32::MAX),
depth: options.depth.unwrap_or(1),
page: options.page.unwrap_or(1) as usize,
page_size: options.page_size.map(|n| n as usize),
},
);
TraceQueryResult {
spans: result
.spans
.into_iter()
.map(|s| TraceSpanInfo {
id: s.id,
name: s.name,
cpu_duration: s.cpu_duration as i64,
corrected_duration: s.corrected_duration as i64,
start_relative_to_parent: s.start_relative_to_parent,
end_relative_to_parent: s.end_relative_to_parent,
args: s.args.into_iter().map(|(k, v)| vec![k, v]).collect(),
is_aggregated: s.is_aggregated,
count: s.count.map(|c| c as i64),
total_cpu_duration: s.total_cpu_duration.map(|v| v as i64),
avg_cpu_duration: s.avg_cpu_duration.map(|v| v as i64),
total_corrected_duration: s.total_corrected_duration.map(|v| v as i64),
avg_corrected_duration: s.avg_corrected_duration.map(|v| v as i64),
first_span_id: s.first_span_id,
memory_samples: s
.memory_samples
.into_iter()
.map(|(ts, mem, pressure)| vec![ts, mem as i64, pressure as i64])
.collect(),
})
.collect(),
spans: result.spans.into_iter().map(convert_span).collect(),
page: result.page as u32,
total_pages: result.total_pages as u32,
total_count: result.total_count as u32,
......
......@@ -732,11 +732,26 @@ internal
.addOption(
new Option(
'--sort <mode>',
'Sort mode: "value" for corrected duration descending, "name" for alphabetical.'
).choices(['value', 'name'])
'Sort mode: "value" for corrected duration descending, "name" for alphabetical, "allocations" for total allocated bytes descending, "persistent-allocations" for persistentAllocations descending.'
).choices(['value', 'name', 'allocations', 'persistent-allocations'])
)
.addOption(
new Option('--search <search>', 'Substring filter on span name/category.')
new Option(
'--search <search>',
'Substring filter on span name/category. Searches the whole subtree below --parent.'
)
)
.addOption(
new Option(
'--max-depth <depth>',
'Levels to descend for --search and --depth (default 32, also the cap).'
).argParser(parseValidPositiveInteger)
)
.addOption(
new Option(
'--depth <depth>',
'Levels of descendants to nest inline under each span (default 1).'
).argParser(parseValidPositiveInteger)
)
.addOption(new Option('--json', 'Output as JSON instead of markdown.'))
.addOption(
......@@ -744,6 +759,12 @@ internal
parseValidPositiveInteger
)
)
.addOption(
new Option(
'--page-size <size>',
'Spans per page (default 20, max 500).'
).argParser(parseValidPositiveInteger)
)
.addHelpText('after', ({ command }) => {
const port = (command.opts() as { port?: number }).port ?? 5748
return `\nExample:\n next internal query-trace --port ${port} --parent <id>`
......
......@@ -777,6 +777,22 @@ export declare function teardownTraceSubscriber(
guardExternal: ExternalObject<RefCell<FlushGuard | undefined | null>>
): void
/** Aggregate view of a span's TurboMalloc memory samples. */
export interface TraceMemorySummary {
/** Number of samples in the span's range, after downsampling. */
count: number
/** Live bytes at the first sample in the range. */
start: number
/** Live bytes at the last sample in the range. */
end: number
/** Smallest live-bytes reading in the range. */
min: number
/** Largest live-bytes reading in the range — the span's peak memory. */
peak: number
/** Highest memory-pressure byte in the range (0 = no pressure). */
maxPressure: number
}
/** Options for `query_trace_spans`. */
export interface TraceQueryOptions {
/**
......@@ -787,14 +803,36 @@ export interface TraceQueryOptions {
/** When `true` (default), aggregate child spans with the same name. */
aggregated?: boolean
/**
* Sort mode: `"value"` for duration descending, `"name"` for alphabetical.
* Sort mode: `"value"` for duration descending, `"name"` for alphabetical,
* `"allocations"` for total allocated bytes descending,
* `"persistent-allocations"` for `persistentAllocations` descending.
* Omit for execution order (no sorting).
*/
sort?: string
/** Optional substring search query applied to span name/category. */
/**
* Optional substring search query applied to span name/category.
*
* Matches anywhere in the parent's subtree. Each result's `id` is the full
* path from `parent` to the match, so it can be passed back as `parent`.
*
* Cost scales with subtree size, so a root search on a large trace walks
* everything. Setting `parent`, or lowering `maxDepth`, bounds it.
*/
search?: string
/**
* Maximum depth to descend below `parent` for `search` and `depth`.
* Default `32`, which is also the cap.
*/
maxDepth?: number
/**
* When greater than `1`, each returned span carries this many levels of
* descendants inline in `children`. Default `1` (no nesting).
*/
depth?: number
/** 1-based page number. Default `1`. */
page?: number
/** Spans per page. Default `20`, capped at `500`. */
pageSize?: number
}
/** The result of a `query_trace_spans` call. */
......@@ -836,18 +874,99 @@ export interface TraceSpanInfo {
totalCorrectedDuration?: number
/** Average corrected duration across spans in the group. */
avgCorrectedDuration?: number
/** Raw span ID for aggregated groups (the index of the first span). */
/**
* Raw span ID of the group's example span, whose `cpuDuration`,
* `correctedDuration` and `memorySamples` are the ones reported here.
* First in execution order — *not* the largest, so it can badly understate
* a group's allocations. Use `heaviestSpanId` for those.
*/
firstSpanId?: string
/**
* Raw span ID of the group member with the largest persistent
* allocations.
*/
heaviestSpanId?: string
/**
* Total bytes allocated by this span and all its children.
*
* For aggregated groups this is the group total, unlike `cpuDuration`,
* `correctedDuration` and `memorySamples`, which describe the example span
* only. Every allocation field below follows this field, not those.
*/
allocations: number
/**
* Total bytes deallocated by this span and all its children.
* Group total for aggregated spans.
*/
deallocations: number
/**
* Sum over each span of `max(0, selfAllocations - selfDeallocations)`,
* for this span and its children. Group total for aggregated spans.
*
* **A ranking signal, not retained memory.** TurboMalloc's per-span
* counters never observe turbo-tasks cell and cache drops, so a
* whole-trace total far above real peak RSS is expected, not a leak. Use
* `memorySummary.peak` for absolute memory.
*
* The per-span floor at zero is also why this is not
* `allocations - deallocations`.
*/
persistentAllocations: number
/**
* Number of allocation operations by this span and all its children.
* Group total for aggregated spans.
*/
allocationCount: number
/**
* Bytes allocated by this span itself, excluding children.
* Group total for aggregated spans.
*/
selfAllocations: number
/**
* Bytes deallocated by this span itself, excluding children.
* Group total for aggregated spans.
*
* Frees are charged to whichever span was on top of the thread's stack at
* free time, which is often not the span that allocated. So small
* `selfAllocations` with large `selfDeallocations` means this span is
* where a child's arena gets dropped — that arena is bounded, not leaking.
* The shape to suspect is a large `selfPersistentAllocations` with no such
* counterpart above it.
*/
selfDeallocations: number
/**
* `max(0, selfAllocations - selfDeallocations)` for this span alone.
* Group total for aggregated spans.
*/
selfPersistentAllocations: number
/**
* Number of allocation operations by this span itself, excluding children.
* Group total for aggregated spans.
*/
selfAllocationCount: number
/**
* TurboMalloc memory-usage 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.
*/
memorySamples: Array<Array<number>>
/**
* Summary of `memorySamples`; absent when the span's range holds none.
* Unlike the allocation counters these are absolute live-heap readings, so
* `peak` is the figure to quote for memory actually in use.
*/
memorySummary?: TraceMemorySummary
/** Descendants of this span, populated only when `depth > 1`. */
children: Array<TraceSpanInfo>
}
export declare function transform(
......
......@@ -14,7 +14,10 @@ interface QueryTraceOptions {
aggregated: boolean | undefined
sort: string | undefined
search: string | undefined
maxDepth: number | undefined
depth: number | undefined
page: number | undefined
pageSize: number | undefined
json: boolean | undefined
}
......@@ -27,7 +30,10 @@ export async function queryTraceCli(options: QueryTraceOptions): Promise<void> {
if (options.aggregated !== undefined) args.aggregated = options.aggregated
if (options.sort !== undefined) args.sort = options.sort
if (options.search !== undefined) args.search = options.search
if (options.maxDepth !== undefined) args.maxDepth = options.maxDepth
if (options.depth !== undefined) args.depth = options.depth
if (options.page !== undefined) args.page = options.page
if (options.pageSize !== undefined) args.pageSize = options.pageSize
if (options.json) args.outputType = 'json'
const requestBody = JSON.stringify({
......
......@@ -44,29 +44,67 @@ function formatBytes(bytes: number): string {
return `${bytes} B`
}
function summarizeMemorySamples(samples: number[][]): string | null {
if (!samples || samples.length === 0) return null
const bytes = samples.map((s) => s[1])
const pressures = samples.map((s) => s[2] ?? 0)
const min = Math.min(...bytes)
const max = Math.max(...bytes)
const first = bytes[0]
const last = bytes[bytes.length - 1]
const delta = last - first
function formatCount(n: number): string {
return n.toLocaleString('en-US')
}
/**
* Does any span in this result carry allocation data?
*
* Only the turbopack trace format records allocations, so this is a property of
* the whole trace. Checking per result rather than per span keeps a real zero
* distinguishable from a trace that never tracked allocations at all.
*/
function hasAllocationData(spans: TraceSpanInfo[]): boolean {
return spans.some(
(span) =>
span.allocations > 0 ||
span.deallocations > 0 ||
span.allocationCount > 0 ||
hasAllocationData(span.children)
)
}
/**
* Render the allocation metrics for a span.
*
* `total*` values cover the span and all its children; `self*` values exclude
* children. For aggregated groups both are group totals across every span in
* the group.
*/
function renderAllocationsMarkdown(span: TraceSpanInfo): string {
let md = `\n**Allocations:**\n`
md += `- **Allocated:** ${formatBytes(span.allocations)} (self ${formatBytes(span.selfAllocations)})\n`
md += `- **Deallocated:** ${formatBytes(span.deallocations)} (self ${formatBytes(span.selfDeallocations)})\n`
md += `- **Persistent (ranking signal, not retained):** ${formatBytes(span.persistentAllocations)} (self ${formatBytes(span.selfPersistentAllocations)})\n`
md += `- **Allocation Count:** ${formatCount(span.allocationCount)} (self ${formatCount(span.selfAllocationCount)})\n`
return md
}
function summarizeMemorySamples(span: TraceSpanInfo): string | null {
const summary = span.memorySummary
if (!summary) return null
const delta = summary.end - summary.start
const deltaSign = delta >= 0 ? '+' : '-'
const maxPressure = Math.max(...pressures)
return (
`samples=${samples.length}, min=${formatBytes(min)}, max=${formatBytes(max)}, ` +
`start=${formatBytes(first)}, end=${formatBytes(last)}, ` +
`Δ=${deltaSign}${formatBytes(Math.abs(delta))}, maxPressure=${maxPressure}`
`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}`
)
}
/**
* Render a single span (or aggregated span group) as a markdown section.
*
* `level` deepens the heading so a `depth > 1` result reads as a tree.
*/
function renderSpanMarkdown(span: TraceSpanInfo): string {
let md = `### \`${span.name}\` (ID: \`${span.id}\`)\n`
function renderSpanMarkdown(
span: TraceSpanInfo,
showAllocations: boolean,
level = 0
): string {
const heading = '#'.repeat(Math.min(3 + level, 6))
let md = `${heading} \`${span.name}\` (ID: \`${span.id}\`)\n`
if (span.isAggregated && span.count !== undefined && span.count > 1) {
md += `- **Count:** ${span.count} spans\n`
......@@ -84,6 +122,9 @@ function renderSpanMarkdown(span: TraceSpanInfo): string {
}
md += `- **Start (relative to parent):** ${formatRelative(span.startRelativeToParent)}\n`
md += `- **End (relative to parent):** ${formatRelative(span.endRelativeToParent)}\n`
if (span.heaviestSpanId !== undefined) {
md += `- **Heaviest member (most persistent bytes):** ID \`${span.heaviestSpanId}\`\n`
}
const exampleId = span.firstSpanId ?? span.id
md += `\n#### First span as example (ID: \`${exampleId}\`)\n`
md += `- **CPU Duration:** ${formatDuration(span.cpuDuration)}\n`
......@@ -102,12 +143,24 @@ function renderSpanMarkdown(span: TraceSpanInfo): string {
}
}
const memSummary = summarizeMemorySamples(span.memorySamples)
if (showAllocations) {
md += renderAllocationsMarkdown(span)
}
const memSummary = summarizeMemorySamples(span)
if (memSummary) {
md += `\n**Memory (TurboMalloc live bytes):** ${memSummary}\n`
}
md += '\n---\n\n'
if (span.children.length > 0) {
md += '\n'
for (const child of span.children) {
md += renderSpanMarkdown(child, showAllocations, level + 1)
}
} else {
md += '\n---\n\n'
}
return md
}
......@@ -154,8 +207,25 @@ export async function startTurboTraceServerCli(
mcpServer.registerTool(
'query_spans',
{
description:
'Query spans from a turbopack trace file. Returns spans with timing, CPU usage, attribute details, and TurboMalloc live-memory samples recorded while each span was active. Set `outputType` to "json" for machine-readable output (including the raw `memorySamples` array of `[ts_offset_ticks, bytes, pressure]` triples per span — pressure is 0 = none, higher = more memory pressure) or "markdown" (default) for a human-readable summary. Use the `parent` parameter (with an ID from a previous result) to drill into children. Results are paginated to 20 spans per page.',
description: [
'Query spans from a turbopack trace file: timing, CPU, attributes, allocation counters, and TurboMalloc live-memory samples.',
'',
'Navigation: pass a result `id` as `parent` to drill in. `search` is recursive over the whole subtree and returns full path IDs, so you can find a span without knowing where it lives. `depth` > 1 returns that many levels nested inline; `pageSize` (default 20, max 500) widens a page.',
'',
'Every response is paged: `totalCount` is how many matched in all, `totalPages` how many pages that is. Getting exactly `pageSize` results does not mean there are no more — check `totalCount`. Search cost scales with subtree size, so prefer scoping `parent` (or lowering `maxDepth`) over repeated root searches on a large trace.',
'',
'Allocations: `allocations` / `deallocations` / `allocationCount` and `persistentAllocations`, each with a `self*` counterpart excluding children. Comparing a total to its `self` shows whether a span allocates directly or only through descendants.',
'',
'`persistentAllocations` ranks allocators; it is NOT retained memory. It is allocated-minus-freed per TurboMalloc counters, which never see turbo-tasks cell or cache drops, so a total far above real peak RSS is expected rather than a leak. For absolute memory use `memorySummary` (count/start/end/min/peak/maxPressure, precomputed from `memorySamples`).',
'',
"But live heap is process-wide: a span's samples are just the global series sliced to its time range, so concurrent spans report identical memory however much each allocated. Rank concurrent work by the allocation fields, never by memory.",
'',
"Frees are charged to whichever span was on the stack at free time, not the one that allocated. A child with large `selfAllocations` under a parent with large `selfDeallocations` means the parent drops the child's arena — bounded, not leaking. Large `selfPersistentAllocations` with no such counterpart above it is the shape worth suspecting.",
'',
'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.',
].join('\n'),
inputSchema: {
parent: z
.string()
......@@ -170,18 +240,34 @@ export async function startTurboTraceServerCli(
'When true (default), aggregate spans with the same name into a single entry. Set to false to see individual raw spans.'
),
sort: z
.enum(['value', 'name'])
.enum(['value', 'name', 'allocations', 'persistent-allocations'])
.optional()
.describe(
'Sort mode: "value" for corrected duration descending, "name" for alphabetical. Omit for execution order.'
'Sort mode: "value" for corrected duration descending, "name" for alphabetical, "allocations" for total allocated bytes descending, "persistent-allocations" for `persistentAllocations` descending. Omit for execution order.'
),
search: z
.string()
.optional()
.describe(
'Substring search query applied to span name and category.'
"Substring search over span name and category, applied to the whole subtree below `parent`. Each match's `id` is the full path from `parent`, so it can be passed straight back as `parent`. Comma-separated terms are ANDed."
),
maxDepth: z
.number()
.optional()
.describe(
'Levels to descend below `parent` for `search` and `depth`. Default 32, which is also the cap.'
),
depth: z
.number()
.optional()
.describe(
"Levels of descendants to include inline in each span's `children`. Default 1 (no nesting)."
),
page: z.number().optional().describe('1-based page number. Default 1.'),
pageSize: z
.number()
.optional()
.describe('Spans per page. Default 20, capped at 500.'),
outputType: z
.enum(['markdown', 'json'])
.optional()
......@@ -196,7 +282,10 @@ export async function startTurboTraceServerCli(
aggregated: args.aggregated ?? true,
sort: args.sort,
search: args.search,
maxDepth: args.maxDepth,
depth: args.depth,
page: args.page ?? 1,
pageSize: args.pageSize,
})
const { spans, page, totalPages, totalCount } = result
......@@ -221,8 +310,9 @@ export async function startTurboTraceServerCli(
md += '_No spans found._\n'
}
const showAllocations = hasAllocationData(spans)
for (const span of spans) {
md += renderSpanMarkdown(span)
md += renderSpanMarkdown(span, showAllocations)
}
if (page < totalPages) {
......
......@@ -313,6 +313,268 @@ describe('turbopack-trace-server', () => {
expect(span).toHaveProperty('isAggregated')
})
// ─── allocation metadata ─────────────────────────────────────────────────
it('should include allocation metadata on every span in JSON output', async () => {
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
expect(spans.length).toBeGreaterThan(0)
for (const span of spans) {
for (const field of [
'allocations',
'deallocations',
'persistentAllocations',
'allocationCount',
'selfAllocations',
'selfDeallocations',
'selfPersistentAllocations',
'selfAllocationCount',
]) {
expect(span).toHaveProperty(field)
expect(typeof span[field]).toBe('number')
expect(span[field]).toBeGreaterThanOrEqual(0)
}
}
})
it('should sort by allocations descending', async () => {
const { spans } = await querySpansJson(mcpPort, { sort: 'allocations' })
const values = spans.map((s) => s.allocations as number)
expect(values).toEqual([...values].sort((a, b) => b - a))
})
it('should sort by persistent-allocations descending', async () => {
const { spans } = await querySpansJson(mcpPort, {
sort: 'persistent-allocations',
})
const values = spans.map((s) => s.persistentAllocations as number)
expect(values).toEqual([...values].sort((a, b) => b - a))
})
it('should include allocation metadata for raw (non-aggregated) spans', async () => {
const { spans } = await querySpansJson(mcpPort, { aggregated: false })
expect(spans.length).toBeGreaterThan(0)
for (const span of spans) {
expect(typeof span.allocations).toBe('number')
expect(typeof span.persistentAllocations).toBe('number')
}
})
it('should render an allocations section in markdown', async () => {
const md = await callMcpTool(mcpPort, 'query_spans', {
sort: 'allocations',
})
expect(md).toContain('**Allocations:**')
expect(md).toMatch(/- \*\*Allocated:\*\* .+ \(self .+\)/)
expect(md).toMatch(
/- \*\*Persistent \(ranking signal, not retained\):\*\* .+ \(self .+\)/
)
expect(md).toMatch(/- \*\*Allocation Count:\*\* .+ \(self .+\)/)
})
it('should expose a precomputed memory summary matching the raw samples', async () => {
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
const withSamples = spans.find(
(s) => (s.memorySamples as number[][] | undefined)?.length
)
if (!withSamples) {
// Traces from very short builds can contain no memory samples at all.
return
}
const samples = withSamples.memorySamples as number[][]
const summary = withSamples.memorySummary as {
count: number
start: number
end: number
min: number
peak: number
maxPressure: number
}
expect(summary).toBeDefined()
expect(summary.count).toBe(samples.length)
expect(summary.start).toBe(samples[0][1])
expect(summary.end).toBe(samples[samples.length - 1][1])
expect(summary.peak).toBe(Math.max(...samples.map((x) => x[1])))
expect(summary.min).toBe(Math.min(...samples.map((x) => x[1])))
})
// ─── recursive search ────────────────────────────────────────────────────
it('should find spans nested below the queried level', async () => {
// Walk two levels down to find a name that is not a direct child of root.
const { spans: roots } = await querySpansJson(mcpPort, { sort: 'value' })
const { spans: level2 } = await querySpansJson(mcpPort, {
parent: roots[0].id,
sort: 'value',
})
if (level2.length === 0) return
const { spans: level3 } = await querySpansJson(mcpPort, {
parent: level2[0].id,
sort: 'value',
})
if (level3.length === 0) return
const deepName = level3[0].name
const rootNames = new Set(roots.map((s) => s.name))
if (rootNames.has(deepName)) {
// This name also exists at the root, so it wouldn't prove recursion.
return
}
// Searching from the root must still reach it.
const { spans: found } = await querySpansJson(mcpPort, {
search: deepName,
})
expect(found.length).toBeGreaterThan(0)
expect(found.some((s) => s.name.includes(deepName))).toBe(true)
})
it('should return search results with navigable full-path IDs', async () => {
const { spans: roots } = await querySpansJson(mcpPort, { sort: 'value' })
const { spans: level2 } = await querySpansJson(mcpPort, {
parent: roots[0].id,
sort: 'value',
})
if (level2.length === 0) return
const { spans: found } = await querySpansJson(mcpPort, {
search: level2[0].name,
})
expect(found.length).toBeGreaterThan(0)
// Every returned ID must be usable as a `parent` in a follow-up call.
const nested = found.find((s) => s.id.includes('-'))
if (nested) {
const result = await querySpansJson(mcpPort, { parent: nested.id })
expect(result).toHaveProperty('totalCount')
expect(result.totalCount).toBeGreaterThanOrEqual(0)
}
})
it('should not change result membership based on sort mode', async () => {
// Sorting reorders; it must never filter.
const byValue = await querySpansJson(mcpPort, { sort: 'value' })
const byName = await querySpansJson(mcpPort, { sort: 'name' })
const byAllocations = await querySpansJson(mcpPort, { sort: 'allocations' })
expect(byName.totalCount).toBe(byValue.totalCount)
expect(byAllocations.totalCount).toBe(byValue.totalCount)
})
// ─── subtree depth ───────────────────────────────────────────────────────
it('should return nested children inline when depth > 1', async () => {
const flat = await querySpansJson(mcpPort, { sort: 'value' })
expect(flat.spans[0].children).toEqual([])
const nested = await querySpansJson(mcpPort, { sort: 'value', depth: 3 })
const top = nested.spans[0]
const children = top.children as SpanData[]
// The same top-level span, now carrying its subtree.
expect(top.id).toBe(flat.spans[0].id)
if (children.length === 0) return
// Nested IDs extend the parent's path, so they stay navigable.
expect(children[0].id.startsWith(top.id)).toBe(true)
// Nested children must match what a direct drill-down returns.
const drilled = await querySpansJson(mcpPort, {
parent: top.id,
sort: 'value',
})
expect(children.map((c) => c.id)).toEqual(
drilled.spans.slice(0, children.length).map((c) => c.id)
)
})
// ─── page size ───────────────────────────────────────────────────────────
it('should honor pageSize and cap it', async () => {
const wide = await querySpansJson(mcpPort, {
aggregated: false,
pageSize: 100,
})
expect(wide.spans.length).toBeLessThanOrEqual(100)
const narrow = await querySpansJson(mcpPort, {
aggregated: false,
pageSize: 1,
})
expect(narrow.spans.length).toBe(1)
expect(narrow.totalCount).toBe(wide.totalCount)
// A smaller page over the same set means more pages.
expect(narrow.totalPages).toBeGreaterThanOrEqual(wide.totalPages)
})
// ─── heaviest span ───────────────────────────────────────────────────────
it('should point heaviestSpanId at the group member holding the most bytes', async () => {
// A group's members are the raw spans under the group's *parent* that
// share its name — not the children of the group id, which belong to the
// example span alone. So the walk has to keep the parent it descended
// from.
const isGroup = (s: SpanData) =>
s.isAggregated && (s.count as number) > 1 && s.heaviestSpanId
// Multi-member groups do not always exist at the root; descend until one
// turns up, remembering which parent each candidate came from.
let frontier: Array<{ parent: string | undefined; span: SpanData }> = (
await querySpansJson(mcpPort, { sort: 'value' })
).spans.map((span) => ({ parent: undefined, span }))
let found: { parent: string | undefined; span: SpanData } | undefined
for (let level = 0; level < 4 && !found && frontier.length > 0; level++) {
found = frontier.find((entry) => isGroup(entry.span))
if (found) break
const next: typeof frontier = []
for (const entry of frontier.slice(0, 5)) {
const { spans } = await querySpansJson(mcpPort, {
parent: entry.span.id,
sort: 'value',
})
next.push(...spans.map((span) => ({ parent: entry.span.id, span })))
}
frontier = next
}
if (!found) return
const group = found.span
const heaviestId = group.heaviestSpanId as string
const firstId = group.firstSpanId as string
// Raw siblings under the group's parent, filtered to the group's name.
const { spans: siblings } = await querySpansJson(mcpPort, {
parent: found.parent,
aggregated: false,
pageSize: 500,
})
const members = siblings.filter((s) => s.name.startsWith(group.name))
// A group can collect spans from different parents, so the siblings here
// are not always the whole group. Only assert when we have recovered every
// member — otherwise `max` is taken over a subset and holds trivially.
if (members.length !== group.count) return
const byIndex = new Map(
members.map((m) => [m.id.split('-').pop() as string, m])
)
const heaviest = byIndex.get(heaviestId)
const first = byIndex.get(firstId)
expect(heaviest).toBeDefined()
expect(first).toBeDefined()
if (!heaviest || !first) return
const max = Math.max(
...members.map((m) => m.persistentAllocations as number)
)
expect(heaviest.persistentAllocations as number).toBe(max)
expect(heaviest.persistentAllocations as number).toBeGreaterThanOrEqual(
first.persistentAllocations as number
)
})
// ─── CLI tests ───────────────────────────────────────────────────────────
it('CLI: should return root-level spans', async () => {
......@@ -350,6 +612,18 @@ describe('turbopack-trace-server', () => {
expect(stdout).toMatch(/###/)
})
it('CLI: should support --sort allocations flag', async () => {
const { stdout, exitCode } = await runQueryTraceCli([
'--port',
String(mcpPort),
'--sort',
'allocations',
])
expect(exitCode).toBe(0)
expect(stdout).toContain('## Spans at root level')
expect(stdout).toMatch(/###/)
})
it('CLI: should support --search flag with a real match', async () => {
// Get a real span name to search for via JSON output.
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
......
......@@ -2,6 +2,8 @@
#![feature(bufreader_peek)]
use std::{
cmp::Reverse,
collections::VecDeque,
hash::BuildHasherDefault,
path::PathBuf,
sync::Arc,
......@@ -12,8 +14,12 @@ use std::{
use rustc_hash::FxHasher;
use self::{
reader::TraceReader, server::serve, span_graph_ref::SpanGraphEventRef, span_ref::SpanRef,
reader::TraceReader,
server::serve,
span_graph_ref::{SpanGraphEventRef, SpanGraphRef},
span_ref::SpanRef,
store_container::StoreContainer,
timestamp::Timestamp,
};
mod bottom_up;
......@@ -57,7 +63,15 @@ pub fn start_turbopack_trace_server(path: PathBuf, port: Option<u16>) -> Arc<Sto
store
}
const PAGE_SIZE: usize = 20;
/// Page size used when the caller doesn't ask for one.
const DEFAULT_PAGE_SIZE: usize = 20;
/// Upper bound on a caller-supplied page size, so one response stays bounded.
const MAX_PAGE_SIZE: usize = 500;
/// Default and cap for `QueryOptions::max_depth`. Also bounds the subtree
/// walks, which is why they need no cycle detection.
const DEFAULT_SEARCH_MAX_DEPTH: u32 = 32;
/// How spans should be sorted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
......@@ -69,6 +83,10 @@ pub enum SortMode {
Value,
/// Sort alphabetically by name, then by category.
Name,
/// Sort by total allocated bytes, descending.
Allocations,
/// Sort by `SpanInfo::persistent_allocations`, descending.
PersistentAllocations,
}
/// Options for querying spans from the trace store.
......@@ -81,9 +99,26 @@ pub struct QueryOptions {
/// How to sort the results.
pub sort: SortMode,
/// Optional substring search query.
///
/// Matches the parent's entire subtree, not just its direct children. Each
/// result's `id` is the full path from `parent` down to the match, so it
/// can be passed straight back as `parent`.
///
/// Cost scales with the size of that subtree, so a root search on a large
/// trace walks everything. Setting `parent`, or lowering `max_depth`,
/// bounds it.
pub search: Option<String>,
/// Maximum depth to descend below `parent` when `search` is set, or when
/// `depth` requests a nested subtree. Clamped to `DEFAULT_SEARCH_MAX_DEPTH`.
pub max_depth: u32,
/// When greater than 1, each returned span carries this many levels of
/// descendants inline in `children`.
pub depth: u32,
/// 1-based page number.
pub page: usize,
/// Number of spans per page. Clamped to `MAX_PAGE_SIZE`; `None` uses
/// `DEFAULT_PAGE_SIZE`.
pub page_size: Option<usize>,
}
/// Information about a single span (or aggregated group of spans).
......@@ -127,11 +162,66 @@ pub struct SpanInfo {
pub total_corrected_duration: Option<u64>,
/// Average corrected_duration across all spans in the group.
pub avg_corrected_duration: Option<u64>,
/// Raw span ID for aggregated groups (the index of the first span).
/// Raw span ID of the group's example span, whose `cpu_duration`,
/// `corrected_duration` and `memory_samples` are the ones reported above.
/// First in execution order — *not* the largest, so it can badly understate
/// a group's allocations. Use `heaviest_span_id` for those.
pub first_span_id: Option<String>,
/// Raw span ID of the group member with the largest
/// `total_persistent_allocations`.
pub heaviest_span_id: Option<String>,
/// Total bytes allocated by this span and all its children.
///
/// For aggregated groups this is the group total, unlike `cpu_duration`,
/// `corrected_duration` and `memory_samples`, which describe the example
/// span only. Every allocation field below follows this field, not those.
pub allocations: u64,
/// Total bytes deallocated by this span and all its children.
/// Group total for aggregated spans.
pub deallocations: u64,
/// Sum over each span of `max(0, self_allocations - self_deallocations)`,
/// for this span and its children. Group total for aggregated spans.
///
/// **A ranking signal, not retained memory.** TurboMalloc's per-span
/// counters never see memory released outside the allocating span's window
/// — turbo-tasks cell and cache drops in particular — so a whole-trace
/// total far above real peak RSS is expected, not a leak. Use
/// `memory_summary` for absolute memory.
///
/// The per-span floor at zero is also why this is not
/// `allocations - deallocations`.
pub persistent_allocations: u64,
/// Number of allocation operations by this span and all its children.
/// Group total for aggregated spans.
pub allocation_count: u64,
/// Bytes allocated by this span itself, excluding children.
/// Group total for aggregated spans.
pub self_allocations: u64,
/// Bytes deallocated by this span itself, excluding children.
/// Group total for aggregated spans.
///
/// Frees are charged to whichever span was on top of the thread's stack at
/// free time, which is often not the span that allocated. So small
/// `self_allocations` with large `self_deallocations` means this span is
/// where a child's arena gets dropped — that arena is bounded, not leaking.
/// The shape to suspect is a large `self_persistent_allocations` with no
/// such counterpart above it.
pub self_deallocations: u64,
/// `max(0, self_allocations - self_deallocations)` for this span alone.
/// Group total for aggregated spans.
pub self_persistent_allocations: u64,
/// 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-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
/// overlap in time report identical values no matter what each allocated.
/// 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
......@@ -142,6 +232,52 @@ pub struct SpanInfo {
/// group's max-memory sample (timestamp, value, and pressure kept
/// together).
pub memory_samples: Vec<(i64, u64, u8)>,
/// 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
/// greater than 1. Sorted and aggregated the same way as this level.
pub children: Vec<SpanInfo>,
}
/// Aggregate view of a span's TurboMalloc memory samples.
///
/// Unlike the allocation counters these are absolute live-heap readings, so
/// `peak` is the figure to quote for memory actually in use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemorySummary {
/// Number of samples in the span's range (after the store's downsampling).
pub count: usize,
/// Live bytes at the first sample in the range.
pub start: u64,
/// Live bytes at the last sample in the range.
pub end: u64,
/// Smallest live-bytes reading in the range.
pub min: u64,
/// Largest live-bytes reading in the range — the span's peak memory.
pub peak: u64,
/// Highest memory-pressure byte seen in the range (0 = no pressure).
pub max_pressure: u8,
}
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()?;
let mut summary = MemorySummary {
count: samples.len(),
start: first_bytes,
end: samples.last().expect("non-empty").1,
min: first_bytes,
peak: first_bytes,
max_pressure: first_pressure,
};
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);
}
Some(summary)
}
}
/// Result of a `query_spans` call.
......@@ -151,14 +287,14 @@ pub struct QueryResult {
pub total_pages: usize,
pub total_count: usize,
}
/// Paginate a vec of items. Returns `(page_items, clamped_page, total_pages, total_count)`.
fn paginate<T>(items: Vec<T>, page: usize) -> (Vec<T>, usize, usize, usize) {
fn paginate<T>(items: Vec<T>, page: usize, page_size: usize) -> (Vec<T>, usize, usize, usize) {
let page_size = page_size.clamp(1, MAX_PAGE_SIZE);
let total_count = items.len();
let total_pages = total_count.div_ceil(PAGE_SIZE).max(1);
let total_pages = total_count.div_ceil(page_size).max(1);
let page = page.clamp(1, total_pages);
let start = (page - 1) * PAGE_SIZE;
let page_items = items.into_iter().skip(start).take(PAGE_SIZE).collect();
let start = (page - 1) * page_size;
let page_items = items.into_iter().skip(start).take(page_size).collect();
(page_items, page, total_pages, total_count)
}
......@@ -178,6 +314,337 @@ fn build_span_id(parent: Option<&str>, leaf: &str) -> String {
}
}
/// A span found while walking, paired with the ID path that leads to it.
struct Located<T> {
item: T,
/// Full path ID, e.g. `"a5-a34-a91"`, usable as a `parent`.
id: String,
}
/// Does this name match the search query?
///
/// Comma-separated terms are ANDed. Each term is a plain substring match
/// against the span's display name, `"category title"` — the `name` a result
/// reports — which is why a term copied out of a response finds its span
/// again.
fn name_matches(cat: &str, title: &str, query: &str) -> bool {
query
.split(',')
.map(str::trim)
.filter(|term| !term.is_empty())
.all(|term| contains_in_joined(cat, title, term))
}
/// Is `term` a substring of `"{cat} {title}"`, without building that string?
///
/// This runs for every span in the searched subtree, so the concatenation is
/// worth avoiding: it was the dominant cost of a search.
///
/// A substring of the joined name either lies within one field or straddles
/// the single space between them, so the straddling case splits the term at a
/// space and checks that `cat` ends with the head and `title` starts with the
/// tail. Every space in the term is tried, since both sides may contain their
/// own.
fn contains_in_joined(cat: &str, title: &str, term: &str) -> bool {
if cat.contains(term) || title.contains(term) {
return true;
}
// `format_span_name` drops the separator only for an empty category, so
// that is the one case with no joining space to straddle. An empty title
// still leaves a trailing space, which a term may legitimately end on, so
// it must not short-circuit here.
if cat.is_empty() {
return false;
}
term.match_indices(' ')
.any(|(i, _)| cat.ends_with(&term[..i]) && title.starts_with(&term[i + 1..]))
}
/// Collect the aggregated children of a graph node.
fn graph_children<'a>(graph: &SpanGraphRef<'a>) -> Vec<SpanGraphRef<'a>> {
graph
.events()
.filter_map(|event| match event {
SpanGraphEventRef::Child { graph } => Some(graph),
SpanGraphEventRef::SelfTime { .. } => None,
})
.collect()
}
/// Collect the aggregated children of a raw span.
fn span_graph_children<'a>(span: &SpanRef<'a>) -> Vec<SpanGraphRef<'a>> {
span.graph()
.filter_map(|event| match event {
SpanGraphEventRef::Child { graph } => Some(graph),
SpanGraphEventRef::SelfTime { .. } => None,
})
.collect()
}
/// Walk the aggregated graph below `roots`, returning every node whose name
/// matches `query`, each tagged with its full path ID.
///
/// Raw spans get recursion from the store's search index, but graph nodes are
/// built on demand and have no index, so this walks them directly.
///
/// A match does not stop the descent — nested spans often share a name with an
/// ancestor.
fn search_graph_recursive<'a>(
roots: Vec<Located<SpanGraphRef<'a>>>,
query: &str,
max_depth: u32,
) -> Vec<Located<SpanGraphRef<'a>>> {
let mut matches = Vec::new();
let mut queue: VecDeque<(Located<SpanGraphRef<'a>>, u32)> =
roots.into_iter().map(|located| (located, 1)).collect();
while let Some((located, depth)) = queue.pop_front() {
let (cat, title) = located.item.nice_name();
let is_match = name_matches(cat, title, query);
if depth < max_depth {
for child in graph_children(&located.item) {
let leaf = format!("a{}", child.first_span().index);
let id = build_span_id(Some(&located.id), &leaf);
queue.push_back((Located { item: child, id }, depth + 1));
}
}
if is_match {
matches.push(located);
}
}
matches
}
/// Walk raw spans below `roots`, returning every span whose name matches
/// `query`.
///
/// Used for multi-word terms, which the store's index cannot answer; see the
/// call site.
fn search_spans_recursive<'a>(
roots: Vec<SpanRef<'a>>,
query: &str,
max_depth: u32,
) -> Vec<SpanRef<'a>> {
let mut matches = Vec::new();
let mut queue: VecDeque<(SpanRef<'a>, u32)> = roots.into_iter().map(|span| (span, 1)).collect();
while let Some((span, depth)) = queue.pop_front() {
let (cat, title) = span.nice_name();
if name_matches(cat, title, query) {
matches.push(span);
}
if depth < max_depth {
for child in span.children() {
queue.push_back((child, depth + 1));
}
}
}
matches
}
/// Sort located aggregated nodes in place.
fn sort_graph(items: &mut [Located<SpanGraphRef<'_>>], sort: SortMode) {
match sort {
SortMode::Value => items.sort_by(|a, b| {
b.item
.corrected_total_time()
.cmp(&a.item.corrected_total_time())
.then_with(|| b.item.total_time().cmp(&a.item.total_time()))
}),
SortMode::Name => items.sort_by(|a, b| {
let (a_cat, a_title) = a.item.nice_name();
let (b_cat, b_title) = b.item.nice_name();
a_title.cmp(b_title).then_with(|| a_cat.cmp(b_cat))
}),
SortMode::Allocations => {
items.sort_by_key(|s| Reverse(s.item.total_allocations()));
}
SortMode::PersistentAllocations => {
items.sort_by_key(|s| Reverse(s.item.total_persistent_allocations()));
}
SortMode::ExecutionOrder => {}
}
}
/// Sort located raw spans in place.
fn sort_spans(items: &mut [Located<SpanRef<'_>>], sort: SortMode) {
match sort {
SortMode::Value => items.sort_by(|a, b| {
b.item
.corrected_total_time()
.cmp(&a.item.corrected_total_time())
.then_with(|| b.item.total_time().cmp(&a.item.total_time()))
}),
SortMode::Name => items.sort_by(|a, b| {
let (a_cat, a_title) = a.item.nice_name();
let (b_cat, b_title) = b.item.nice_name();
a_title.cmp(b_title).then_with(|| a_cat.cmp(b_cat))
}),
SortMode::Allocations => {
items.sort_by_key(|s| Reverse(s.item.total_allocations()));
}
SortMode::PersistentAllocations => {
items.sort_by_key(|s| Reverse(s.item.total_persistent_allocations()));
}
SortMode::ExecutionOrder => {}
}
}
/// Memory samples recorded while `span` was live, offset from its start.
fn memory_samples_for(store: &store::Store, span: &SpanRef<'_>) -> Vec<(i64, u64, u8)> {
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))
.collect()
}
/// Build a `SpanInfo` for an aggregated graph node, recursing into children
/// while `depth > 1`.
fn build_graph_span_info(
store: &store::Store,
located: Located<SpanGraphRef<'_>>,
parent_start: Timestamp,
sort: SortMode,
depth: u32,
) -> SpanInfo {
let Located { item: graph, id } = located;
let first = graph.first_span();
let (cat, title) = graph.nice_name();
let count = graph.count() as u64;
let total_cpu = *graph.total_time();
let total_corrected = *graph.corrected_total_time();
let heaviest = graph
.root_spans()
.max_by_key(|span| span.total_persistent_allocations())
.map(|span| span.index.to_string());
let memory_samples = memory_samples_for(store, &first);
let memory_summary = MemorySummary::from_samples(&memory_samples);
let children = if depth > 1 {
let mut located_children: Vec<_> = graph_children(&graph)
.into_iter()
.map(|child| {
let leaf = format!("a{}", child.first_span().index);
Located {
id: build_span_id(Some(&id), &leaf),
item: child,
}
})
.collect();
sort_graph(&mut located_children, sort);
located_children
.into_iter()
.map(|child| build_graph_span_info(store, child, first.start(), sort, depth - 1))
.collect()
} else {
Vec::new()
};
SpanInfo {
id,
name: format_span_name(cat, title),
cpu_duration: *first.total_time(),
corrected_duration: *first.corrected_total_time(),
start_relative_to_parent: (*first.start() as i64) - (*parent_start as i64),
end_relative_to_parent: (*first.end() as i64) - (*parent_start as i64),
args: first
.args()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
is_aggregated: count > 1,
count: Some(count),
total_cpu_duration: Some(total_cpu),
avg_cpu_duration: Some(total_cpu.checked_div(count).unwrap_or(0)),
total_corrected_duration: Some(total_corrected),
avg_corrected_duration: Some(total_corrected.checked_div(count).unwrap_or(0)),
first_span_id: Some(first.index.to_string()),
heaviest_span_id: heaviest,
allocations: graph.total_allocations(),
deallocations: graph.total_deallocations(),
persistent_allocations: graph.total_persistent_allocations(),
allocation_count: graph.total_allocation_count(),
self_allocations: graph.self_allocations(),
self_deallocations: graph.self_deallocations(),
self_persistent_allocations: graph.self_persistent_allocations(),
self_allocation_count: graph.self_allocation_count(),
memory_samples,
memory_summary,
children,
}
}
/// Build a `SpanInfo` for a raw span, recursing into children while `depth > 1`.
fn build_raw_span_info(
store: &store::Store,
located: Located<SpanRef<'_>>,
parent_start: Timestamp,
sort: SortMode,
depth: u32,
) -> SpanInfo {
let Located { item: span, id } = located;
let (cat, title) = span.nice_name();
let memory_samples = memory_samples_for(store, &span);
let memory_summary = MemorySummary::from_samples(&memory_samples);
let children = if depth > 1 {
let mut located_children: Vec<_> = span
.children()
.map(|child| Located {
id: build_span_id(Some(&id), &child.index.to_string()),
item: child,
})
.collect();
sort_spans(&mut located_children, sort);
located_children
.into_iter()
.map(|child| build_raw_span_info(store, child, span.start(), sort, depth - 1))
.collect()
} else {
Vec::new()
};
SpanInfo {
id,
name: format_span_name(cat, title),
cpu_duration: *span.total_time(),
corrected_duration: *span.corrected_total_time(),
start_relative_to_parent: (*span.start() as i64) - (*parent_start as i64),
end_relative_to_parent: (*span.end() as i64) - (*parent_start as i64),
args: span
.args()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
is_aggregated: false,
count: None,
total_cpu_duration: None,
avg_cpu_duration: None,
total_corrected_duration: None,
avg_corrected_duration: None,
first_span_id: None,
heaviest_span_id: None,
allocations: span.total_allocations(),
deallocations: span.total_deallocations(),
persistent_allocations: span.total_persistent_allocations(),
allocation_count: span.total_allocation_count(),
self_allocations: span.self_allocations(),
self_deallocations: span.self_deallocations(),
self_persistent_allocations: span.self_persistent_allocations(),
self_allocation_count: span.self_allocation_count(),
memory_samples,
memory_summary,
children,
}
}
/// Query spans from the store.
///
/// Waits up to 10 seconds for at least some data to be loaded before
......@@ -202,129 +669,50 @@ pub fn query_spans(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryR
let store_guard = store.read();
let store_ref = &*store_guard;
// Resolve the parent span.
let parent_span: Option<SpanRef<'_>> = if let Some(ref parent_id) = options.parent {
resolve_span_by_id(store_ref, parent_id)
} else {
None
};
let parent_start = parent_span.as_ref().map(|s| *s.start()).unwrap_or_default();
let parent_start = parent_span.as_ref().map(|s| s.start()).unwrap_or_default();
let max_depth = options.max_depth.clamp(1, DEFAULT_SEARCH_MAX_DEPTH);
let depth = options.depth.clamp(1, DEFAULT_SEARCH_MAX_DEPTH);
let page_size = options
.page_size
.unwrap_or(DEFAULT_PAGE_SIZE)
.clamp(1, MAX_PAGE_SIZE);
if options.aggregated {
// Collect aggregated children (SpanGraphRef) from either the resolved
// parent span or the root.
let graph_children: Vec<_> = if let Some(ref parent) = parent_span {
// The parent might be an aggregated node: look up which graph node
// the parent ID refers to, then iterate its children's graph events.
// For simplicity, resolve via the parent span's graph().
parent
.graph()
.filter_map(|event| match event {
SpanGraphEventRef::Child { graph } => Some(graph),
SpanGraphEventRef::SelfTime { .. } => None,
})
.collect()
} else {
// Root level: use root span's graph.
store_ref
.root_span()
.graph()
.filter_map(|event| match event {
SpanGraphEventRef::Child { graph } => Some(graph),
SpanGraphEventRef::SelfTime { .. } => None,
})
.collect()
};
let direct: Vec<Located<SpanGraphRef<'_>>> = match parent_span {
Some(ref parent) => span_graph_children(parent),
None => span_graph_children(&store_ref.root_span()),
}
.into_iter()
.map(|graph| {
let leaf = format!("a{}", graph.first_span().index);
Located {
id: build_span_id(options.parent.as_deref(), &leaf),
item: graph,
}
})
.collect();
// Apply search filter.
let mut filtered: Vec<_> = if let Some(ref query) = options.search {
graph_children
.into_iter()
.filter(|g| {
let (cat, title) = g.nice_name();
cat.contains(query.as_str()) || title.contains(query.as_str())
})
.collect()
} else {
graph_children
// A search descends the subtree; without one we stay at this level.
let mut filtered = match options.search {
Some(ref query) => search_graph_recursive(direct, query, max_depth),
None => direct,
};
// Sort if requested.
match options.sort {
SortMode::Value => {
filtered.sort_by(|a, b| {
b.corrected_total_time()
.cmp(&a.corrected_total_time())
.then_with(|| b.total_time().cmp(&a.total_time()))
});
}
SortMode::Name => {
filtered.sort_by(|a, b| {
let (a_cat, a_title) = a.nice_name();
let (b_cat, b_title) = b.nice_name();
a_title.cmp(b_title).then_with(|| a_cat.cmp(b_cat))
});
}
SortMode::ExecutionOrder => {}
}
sort_graph(&mut filtered, options.sort);
let (page_items, page, total_pages, total_count) = paginate(filtered, options.page);
let (page_items, page, total_pages, total_count) =
paginate(filtered, options.page, page_size);
let spans = page_items
.into_iter()
.map(|graph| {
let first = graph.first_span();
let (cat, title) = graph.nice_name();
let name = format_span_name(cat, title);
let count = graph.count() as u64;
let total_cpu = *graph.total_time();
let total_corrected = *graph.corrected_total_time();
let avg_cpu = total_cpu.checked_div(count).unwrap_or(0);
let avg_corrected = total_corrected.checked_div(count).unwrap_or(0);
// Build the full path ID for this aggregated span.
// The leaf segment is "a{first_span_index}"; prepend the parent
// path (if any) with a dash so callers can pass the full string
// back as `parent` to drill into children.
let first_index = first.index;
let graph_id = build_span_id(options.parent.as_deref(), &format!("a{first_index}"));
// start/end of the first/example span relative to parent.
let span_start = *first.start();
let span_end = *first.end();
let rel_start = (span_start as i64) - (parent_start as i64);
let rel_end = (span_end as i64) - (parent_start as i64);
let first_start_ticks = *first.start();
let memory_samples: Vec<(i64, u64, u8)> = store_ref
.memory_samples_for_range_with_ts(first.start(), first.end())
.into_iter()
.map(|(ts, mem, pressure)| {
((*ts as i64) - (first_start_ticks as i64), mem, pressure)
})
.collect();
SpanInfo {
id: graph_id,
name,
cpu_duration: *first.total_time(),
corrected_duration: *first.corrected_total_time(),
start_relative_to_parent: rel_start,
end_relative_to_parent: rel_end,
args: first
.args()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
is_aggregated: count > 1,
count: Some(count),
total_cpu_duration: Some(total_cpu),
avg_cpu_duration: Some(avg_cpu),
total_corrected_duration: Some(total_corrected),
avg_corrected_duration: Some(avg_corrected),
first_span_id: Some(first_index.to_string()),
memory_samples,
}
.map(|located| {
build_graph_span_info(store_ref, located, parent_start, options.sort, depth)
})
.collect();
......@@ -335,84 +723,57 @@ pub fn query_spans(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryR
total_count,
}
} else {
// Raw spans mode.
let raw_children: Vec<SpanRef<'_>> = if let Some(ref parent) = parent_span {
parent.children().collect()
} else {
store_ref.root_spans().collect()
};
// Apply search filter using the span's search index.
let mut filtered: Vec<_> = if let Some(ref query) = options.search {
if let Some(ref parent) = parent_span {
parent.search(query).collect()
// The store's index keys category and title separately, so a term
// spanning both (a `name` copied from a result) matches no key. It is
// shared with the WebSocket viewer, so rather than change its keys,
// walk the subtree ourselves whenever any term contains a space.
// Single-word queries still take the index, which is much faster.
let filtered: Vec<Located<SpanRef<'_>>> = if let Some(ref query) = options.search {
let needs_scan = query.split(',').any(|term| term.trim().contains(' '));
let matches: Vec<SpanRef<'_>> = if needs_scan {
let roots: Vec<SpanRef<'_>> = match parent_span {
Some(ref parent) => parent.children().collect(),
None => store_ref.root_spans().collect(),
};
search_spans_recursive(roots, query, max_depth)
} else {
store_ref.root_span().search(query).collect()
}
match parent_span {
Some(ref parent) => parent.search(query).collect(),
None => store_ref.root_span().search(query).collect(),
}
};
matches
.into_iter()
.filter_map(|span| {
raw_span_path(&span, parent_span.as_ref(), max_depth).map(|id| Located {
item: span,
id: build_span_id(options.parent.as_deref(), &id),
})
})
.collect()
} else {
raw_children
match parent_span {
Some(ref parent) => parent.children().collect::<Vec<_>>(),
None => store_ref.root_spans().collect::<Vec<_>>(),
}
.into_iter()
.map(|span| Located {
id: build_span_id(options.parent.as_deref(), &span.index.to_string()),
item: span,
})
.collect()
};
// Sort if requested.
match options.sort {
SortMode::Value => {
filtered.sort_by(|a, b| {
b.corrected_total_time()
.cmp(&a.corrected_total_time())
.then_with(|| b.total_time().cmp(&a.total_time()))
});
}
SortMode::Name => {
filtered.sort_by(|a, b| {
let (a_cat, a_title) = a.nice_name();
let (b_cat, b_title) = b.nice_name();
a_title.cmp(b_title).then_with(|| a_cat.cmp(b_cat))
});
}
SortMode::ExecutionOrder => {}
}
let mut filtered = filtered;
sort_spans(&mut filtered, options.sort);
let (page_items, page, total_pages, total_count) = paginate(filtered, options.page);
let (page_items, page, total_pages, total_count) =
paginate(filtered, options.page, page_size);
let spans = page_items
.into_iter()
.map(|span| {
let (cat, title) = span.nice_name();
let name = format_span_name(cat, title);
let span_start = *span.start();
let span_end = *span.end();
let rel_start = (span_start as i64) - (parent_start as i64);
let rel_end = (span_end as i64) - (parent_start as i64);
let raw_span_start = span_start;
let memory_samples: Vec<(i64, u64, u8)> = store_ref
.memory_samples_for_range_with_ts(span.start(), span.end())
.into_iter()
.map(|(ts, mem, pressure)| {
((*ts as i64) - (raw_span_start as i64), mem, pressure)
})
.collect();
SpanInfo {
id: build_span_id(options.parent.as_deref(), &span.index.to_string()),
name,
cpu_duration: *span.total_time(),
corrected_duration: *span.corrected_total_time(),
start_relative_to_parent: rel_start,
end_relative_to_parent: rel_end,
args: span
.args()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
is_aggregated: false,
count: None,
total_cpu_duration: None,
avg_cpu_duration: None,
total_corrected_duration: None,
avg_corrected_duration: None,
first_span_id: None,
memory_samples,
}
.map(|located| {
build_raw_span_info(store_ref, located, parent_start, options.sort, depth)
})
.collect();
......@@ -425,6 +786,45 @@ pub fn query_spans(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryR
}
}
/// Build the dash-separated index path from `ancestor` (exclusive) down to
/// `span` (inclusive), e.g. `"12-48-91"`.
///
/// `None` when `span` is not a descendant of `ancestor`, or when the chain is
/// longer than `max_depth`. Passing `None` for `ancestor` walks up to the
/// trace root.
fn raw_span_path(
span: &SpanRef<'_>,
ancestor: Option<&SpanRef<'_>>,
max_depth: u32,
) -> Option<String> {
let stop_at = ancestor.map(|a| a.index);
let mut segments = Vec::new();
let mut current = *span;
loop {
if Some(current.index) == stop_at {
break;
}
if segments.len() as u32 >= max_depth {
return None;
}
segments.push(current.index.to_string());
match current.parent() {
Some(parent) => current = parent,
// Reached the root without finding `ancestor`.
None => {
if stop_at.is_some() {
return None;
}
break;
}
}
}
segments.reverse();
Some(segments.join("-"))
}
/// Resolve a span by its MCP ID string.
///
/// IDs use the format `[a]<index>[-[a]<index>...]`:
......@@ -446,3 +846,517 @@ fn resolve_span_by_id<'a>(store: &'a store::Store, id: &str) -> Option<SpanRef<'
index,
})
}
#[cfg(test)]
mod tests {
use rustc_hash::FxHashSet;
use turbo_rcstr::RcStr;
use super::*;
use crate::{
span::{SpanArgs, SpanIndex},
timestamp::Timestamp,
};
/// Build a store shaped like:
///
/// ```text
/// root
/// └─ outer (index 1)
/// ├─ middle (index 2)
/// │ └─ cat needle (index 3) ← only reachable 3 levels down
/// └─ other (index 4)
/// ```
fn nested_store() -> (Arc<StoreContainer>, Vec<SpanIndex>) {
let container = Arc::new(StoreContainer::new());
let mut indices = Vec::new();
{
let mut store = container.write();
let mut outdated = FxHashSet::default();
let outer = store.add_span(
None,
Timestamp::from_micros(0),
RcStr::default(),
RcStr::from("outer"),
SpanArgs::new(),
&mut outdated,
);
let middle = store.add_span(
Some(outer),
Timestamp::from_micros(1),
RcStr::default(),
RcStr::from("middle"),
SpanArgs::new(),
&mut outdated,
);
// `needle` gets a category so its display name ("cat needle")
// spans both fields, which the display-name search test needs.
let needle = store.add_span(
Some(middle),
Timestamp::from_micros(2),
RcStr::from("cat"),
RcStr::from("needle"),
SpanArgs::new(),
&mut outdated,
);
let other = store.add_span(
Some(outer),
Timestamp::from_micros(3),
RcStr::default(),
RcStr::from("other"),
SpanArgs::new(),
&mut outdated,
);
// Most bytes in `other`, so allocation order differs from
// execution order.
store.add_allocation(needle, 1_000, 10, &mut outdated);
store.add_allocation(other, 50_000, 100, &mut outdated);
for span in [outer, middle, needle, other] {
store.complete_span(span);
}
store.invalidate_outdated_spans(&outdated);
indices.extend([outer, middle, needle, other]);
}
(container, indices)
}
fn query(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryResult {
query_spans(store, options)
}
fn options() -> QueryOptions {
QueryOptions {
parent: None,
aggregated: true,
sort: SortMode::ExecutionOrder,
search: None,
max_depth: DEFAULT_SEARCH_MAX_DEPTH,
depth: 1,
page: 1,
page_size: None,
}
}
#[test]
fn aggregated_search_finds_deep_descendants() {
let (store, _) = nested_store();
// `needle` is three levels below the root.
let result = query(
&store,
QueryOptions {
search: Some("needle".to_string()),
..options()
},
);
assert_eq!(result.total_count, 1, "expected to find the nested span");
assert_eq!(result.spans[0].name, "cat needle");
}
#[test]
fn aggregated_search_returns_full_navigable_path() {
let (store, _) = nested_store();
let result = query(
&store,
QueryOptions {
search: Some("needle".to_string()),
..options()
},
);
let id = &result.spans[0].id;
assert_eq!(
id.split('-').count(),
3,
"expected a 3-segment path, got {id}"
);
// The path must resolve back to `needle`.
let children = query(
&store,
QueryOptions {
parent: Some(id.clone()),
..options()
},
);
assert_eq!(children.total_count, 0, "needle has no children");
}
#[test]
fn raw_search_finds_deep_descendants_with_paths() {
let (store, _) = nested_store();
let result = query(
&store,
QueryOptions {
aggregated: false,
search: Some("needle".to_string()),
..options()
},
);
assert_eq!(result.total_count, 1);
assert_eq!(result.spans[0].name, "cat needle");
// outer-middle-needle
assert_eq!(result.spans[0].id.split('-').count(), 3);
}
#[test]
fn raw_search_matches_the_display_name() {
let (store, _) = nested_store();
// "cat needle" is the `name` a result reports, but the store's index
// keys "cat" and "needle" separately, so only the fallback scan
// resolves it.
let result = query(
&store,
QueryOptions {
aggregated: false,
search: Some("cat needle".to_string()),
..options()
},
);
assert_eq!(result.total_count, 1);
assert_eq!(result.spans[0].name, "cat needle");
}
#[test]
fn raw_search_handles_multi_word_terms_that_the_index_matches_partially() {
let (store, _) = nested_store();
// "cat" alone matches via the store's index. Adding a second word must
// narrow the result, not be silently dropped: the index answers whole
// terms only, so trusting it here returned every "cat" span.
let both = query(
&store,
QueryOptions {
aggregated: false,
search: Some("cat needle".to_string()),
..options()
},
);
assert_eq!(both.total_count, 1);
assert_eq!(both.spans[0].name, "cat needle");
// A second word that matches nothing must yield nothing, even though
// the first word matches.
let neither = query(
&store,
QueryOptions {
aggregated: false,
search: Some("cat nomatch".to_string()),
..options()
},
);
assert_eq!(neither.total_count, 0);
}
#[test]
fn search_respects_max_depth() {
let (store, _) = nested_store();
let shallow = query(
&store,
QueryOptions {
search: Some("needle".to_string()),
max_depth: 2,
..options()
},
);
assert_eq!(
shallow.total_count, 0,
"needle sits at depth 3 and must be excluded at max_depth 2"
);
}
#[test]
fn depth_returns_nested_children_in_one_call() {
let (store, _) = nested_store();
let result = query(
&store,
QueryOptions {
depth: 3,
..options()
},
);
let outer = &result.spans[0];
assert_eq!(outer.name, "outer");
assert_eq!(outer.children.len(), 2, "middle and other");
let middle = outer
.children
.iter()
.find(|c| c.name == "middle")
.expect("middle present");
assert_eq!(middle.children.len(), 1);
assert_eq!(middle.children[0].name, "cat needle");
// Nested IDs stay navigable.
assert!(middle.children[0].id.starts_with(&outer.id));
}
#[test]
fn depth_one_leaves_children_empty() {
let (store, _) = nested_store();
let result = query(&store, options());
assert!(result.spans[0].children.is_empty());
}
#[test]
fn raw_allocation_sorts_are_descending() {
let (store, _) = nested_store();
// Regression: these sorted ascending, so the "biggest allocator" query
// returned the smallest ones.
for sort in [SortMode::Allocations, SortMode::PersistentAllocations] {
let result = query(
&store,
QueryOptions {
aggregated: false,
// Search the whole tree so more than one span is ranked.
search: Some("e".to_string()),
sort,
..options()
},
);
let values: Vec<u64> = result
.spans
.iter()
.map(|s| match sort {
SortMode::PersistentAllocations => s.persistent_allocations,
_ => s.allocations,
})
.collect();
let mut sorted = values.clone();
sorted.sort_by(|a, b| b.cmp(a));
assert_eq!(values, sorted, "{sort:?} must be descending");
}
}
#[test]
fn page_size_is_honored_and_capped() {
let (store, _) = nested_store();
let paged = query(
&store,
QueryOptions {
parent: Some("1".to_string()),
aggregated: false,
page_size: Some(1),
..options()
},
);
assert_eq!(paged.spans.len(), 1);
assert_eq!(paged.total_count, 2, "outer has two children");
assert_eq!(paged.total_pages, 2);
// An absurd request is clamped rather than rejected.
let huge = query(
&store,
QueryOptions {
page_size: Some(usize::MAX),
..options()
},
);
assert_eq!(huge.page, 1);
}
#[test]
fn heaviest_span_id_points_at_the_biggest_member() {
let (store, indices) = nested_store();
let result = query(
&store,
QueryOptions {
parent: Some("1".to_string()),
..options()
},
);
let other = result
.spans
.iter()
.find(|s| s.name == "other")
.expect("other present");
// Single-member group: heaviest is that member.
assert_eq!(
other.heaviest_span_id.as_deref(),
Some(indices[3].get().to_string().as_str())
);
}
#[test]
fn heaviest_span_id_differs_from_first_in_a_multi_member_group() {
// A single-member group cannot tell the two apart, so build a group of
// three same-named siblings where the heaviest is neither first nor
// last. This is the case that matters: on a real trace `first_span_id`
// reached a 75MB member of a 370MB group whose heaviest held 209MB.
let container = Arc::new(StoreContainer::new());
let mut members = Vec::new();
{
let mut store = container.write();
let mut outdated = FxHashSet::default();
let parent = store.add_span(
None,
Timestamp::from_micros(0),
RcStr::default(),
RcStr::from("parent"),
SpanArgs::new(),
&mut outdated,
);
// Same name so they aggregate; allocations ordered small, large,
// medium so the winner is not simply the first or the last.
for (i, bytes) in [1_000u64, 90_000, 40_000].into_iter().enumerate() {
let child = store.add_span(
Some(parent),
Timestamp::from_micros(i as u64 + 1),
RcStr::default(),
RcStr::from("member"),
SpanArgs::new(),
&mut outdated,
);
store.add_allocation(child, bytes, 10, &mut outdated);
store.complete_span(child);
members.push(child);
}
store.complete_span(parent);
store.invalidate_outdated_spans(&outdated);
}
let result = query(
&container,
QueryOptions {
parent: Some("1".to_string()),
..options()
},
);
let group = result
.spans
.iter()
.find(|s| s.name == "member")
.expect("group present");
assert_eq!(group.count, Some(3), "the three spans must aggregate");
let first = members[0].get().to_string();
let heaviest = members[1].get().to_string();
assert_eq!(group.first_span_id.as_deref(), Some(first.as_str()));
assert_eq!(group.heaviest_span_id.as_deref(), Some(heaviest.as_str()));
assert_ne!(
group.first_span_id, group.heaviest_span_id,
"otherwise this test cannot tell the two apart"
);
}
#[test]
fn memory_summary_is_absent_without_samples() {
let (store, _) = nested_store();
let result = query(&store, options());
assert!(result.spans[0].memory_summary.is_none());
}
#[test]
fn memory_summary_reports_peak_not_last() {
let samples = [(0i64, 100u64, 0u8), (1, 900, 3), (2, 200, 1)];
let summary = MemorySummary::from_samples(&samples).expect("samples present");
assert_eq!(summary.count, 3);
assert_eq!(summary.start, 100);
assert_eq!(summary.end, 200);
assert_eq!(summary.min, 100);
assert_eq!(summary.peak, 900);
assert_eq!(summary.max_pressure, 3);
assert!(MemorySummary::from_samples(&[]).is_none());
}
#[test]
fn search_terms_are_anded() {
assert!(name_matches("cat", "needle in haystack", "needle,haystack"));
assert!(!name_matches("cat", "needle only", "needle,haystack"));
// Category counts as a match target too.
assert!(name_matches("turbopack", "build", "turbopack"));
}
#[test]
fn search_matches_the_display_name_callers_see() {
// A result's `name` is "cat title"; searching for that exact string has
// to find the span again, even though it spans both fields.
assert!(name_matches("turbopack", "build", "turbopack build"));
// Every word still has to land somewhere.
assert!(!name_matches("turbopack", "build", "turbopack missing"));
assert!(!name_matches("turbopack", "build", "nope"));
}
#[test]
fn search_term_is_a_substring_of_the_display_name() {
// Contiguous, in order — exactly what a term copied from a `name` is.
assert!(name_matches("turbopack", "build", "turbopack build"));
assert!(!name_matches("turbopack", "build", "build turbopack"));
// Words with something between them are not a substring.
assert!(name_matches(
"a",
"analyze ecmascript module",
"analyze ecmascript"
));
assert!(!name_matches(
"a",
"analyze ecmascript module",
"analyze module"
));
// A term may straddle the space joining the two fields.
assert!(name_matches(
"turbopack_ecmascript",
"analyze module",
"ecmascript analyze"
));
assert!(!name_matches(
"turbopack_ecmascript",
"analyze module",
"analyze ecmascript"
));
// Straddling requires the exact boundary, not just both halves present.
assert!(!name_matches(
"turbopack_ecmascript",
"analyze module",
"turbopack module"
));
}
#[test]
fn joined_match_is_equivalent_to_the_formatted_name() {
// `contains_in_joined` must agree with formatting the name and calling
// `contains`, including when a field is empty. `format_span_name` drops
// the separator only for an empty category, so an empty title still
// leaves a trailing space — guarding on `title.is_empty()` would lose
// the terms that end on it.
for (cat, title) in [("foo", ""), ("", "bar"), ("foo", "bar"), ("", "")] {
for term in ["foo", "bar", "foo ", " bar", "foo bar", "o b", "", " "] {
let expected = format_span_name(cat, title).contains(term);
assert_eq!(
contains_in_joined(cat, title, term),
expected,
"cat={cat:?} title={title:?} term={term:?}"
);
}
}
}
#[test]
fn search_handles_non_ascii_without_panicking() {
// The cursor slices `cat`/`title` by byte offset, so every offset has
// to land on a char boundary.
assert!(name_matches("café", "über naïve", "café über"));
assert!(name_matches("café", "über naïve", "é ü"));
assert!(name_matches("café", "über naïve", "über naïve"));
assert!(!name_matches("café", "über naïve", "naïve café"));
assert!(!name_matches("日本語", "テスト", "テスト 日本語"));
assert!(name_matches("日本語", "テスト", "日本語 テスト"));
}
#[test]
fn search_ignores_empty_terms_and_padding() {
// Trimming and the empty-word filter must not turn separators into a
// vacuous match-everything.
assert!(name_matches("turbopack", "build", " build "));
assert!(name_matches("turbopack", "build", "build,,"));
assert!(!name_matches("turbopack", "build", "build, nope"));
}
}
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