Unverified Commit 1de67d8b authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Refactor trace server sort to SortMode enum (execution order / value / name) (#92873)

### What?

Replaces the boolean `sort` flag in the trace server with a `SortMode`
enum supporting three modes:
- **`ExecutionOrder`** — no sorting, spans appear in natural/execution
order (previous `false`)
- **`Value`** — sort by corrected duration descending (previous `true`)
- **`Name`** — sort alphabetically by span name (title), then by
category

### Why?

The boolean `sort` only allowed toggling duration-based sorting on/off.
Adding alphabetical sorting by name makes it easier to find duplicate
spans and locate a specific span by name in the trace viewer. The enum
is extensible for future sort modes without breaking changes.

### How?

**Rust (`turbopack-trace-server`):**
- Added `SortMode { ExecutionOrder, Value, Name }` enum to both `lib.rs`
(for the query API) and `viewer.rs` (for the WebSocket viewer).
- `ViewMode` variants changed from `sorted: bool` to `sort_mode:
SortMode`.
- `sort_children()` now returns `SortMode` instead of `bool`; all 10
sorting branches in `viewer.rs` converted from `if/else` to a 3-arm
`match`.
- `Name` sort uses `nice_name()` — sorts by title first, then category,
both ascending.
- `SpanEventRef::SelfTime` and `SpanGraphEventRef::SelfTime` (which have
no name) sort as `("", "")` under `Name` mode.

**WebSocket protocol (backward compatible):**
- `-sorted` suffix → `SortMode::Value` (existing clients unaffected)
- `-sorted-by-value` suffix → `SortMode::Value`
- `-sorted-by-name` suffix → `SortMode::Name`
- no suffix → `SortMode::ExecutionOrder`

**napi bindings (`next-napi-bindings`):**
- `TraceQueryOptions.sort` changed from `Option<bool>` to
`Option<String>` (`"value"` | `"name"` | omit).

**TypeScript:**
- `generated-native.d.ts`: `sort?: 'value' | 'name'`
- MCP tool schema: `z.enum(['value', 'name']).optional()`
- CLI: `--sort <mode>` with `.choices(['value', 'name'])` replacing the
boolean `--sort` flag
- Tests updated; added new test cases for `sort: 'name'` and `--sort
name`

<!-- NEXT_JS_LLM_PR -->
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 68bac2a7
......@@ -2,7 +2,8 @@ use std::{path::PathBuf, sync::Arc};
use napi_derive::napi;
use turbopack_trace_server::{
QueryOptions, query_spans, start_turbopack_trace_server, store_container::StoreContainer,
QueryOptions, SortMode, query_spans, start_turbopack_trace_server,
store_container::StoreContainer,
};
/// An opaque handle to a running trace server instance.
......@@ -21,8 +22,9 @@ pub struct TraceQueryOptions {
pub parent: Option<String>,
/// When `true` (default), aggregate child spans with the same name.
pub aggregated: Option<bool>,
/// When `true`, sort results by corrected duration descending. Default `false`.
pub sort: Option<bool>,
/// Sort mode: `"value"` for duration descending, `"name"` for alphabetical.
/// Omit for execution order (no sorting).
pub sort: Option<String>,
/// Optional substring search query applied to span name/category.
pub search: Option<String>,
/// 1-based page number. Default `1`.
......@@ -94,7 +96,11 @@ pub fn query_trace_spans(
QueryOptions {
parent: options.parent,
aggregated: options.aggregated.unwrap_or(true),
sort: options.sort.unwrap_or(false),
sort: match options.sort.as_deref() {
Some("value") => SortMode::Value,
Some("name") => SortMode::Name,
_ => SortMode::ExecutionOrder,
},
search: options.search,
page: options.page.unwrap_or(1) as usize,
},
......
......@@ -643,9 +643,9 @@ internal
)
.addOption(
new Option(
'--sort',
'Sort results by corrected duration descending (default: false).'
)
'--sort <mode>',
'Sort mode: "value" for corrected duration descending, "name" for alphabetical.'
).choices(['value', 'name'])
)
.addOption(
new Option('--search <search>', 'Substring filter on span name/category.')
......
......@@ -616,8 +616,8 @@ export interface TraceQueryOptions {
parent?: string
/** When `true` (default), aggregate child spans with the same name. */
aggregated?: boolean
/** When `true`, sort results by corrected duration descending. Default `false`. */
sort?: boolean
/** Sort mode: `"value"` for duration descending, `"name"` for alphabetical. Omit for execution order. */
sort?: 'value' | 'name'
/** Optional substring search query applied to span name/category. */
search?: string
/** 1-based page number. Default `1`. */
......
......@@ -12,7 +12,7 @@ interface QueryTraceOptions {
port: number | undefined
parent: string | undefined
aggregated: boolean | undefined
sort: boolean | undefined
sort: string | undefined
search: string | undefined
page: number | undefined
json: boolean | undefined
......
......@@ -136,10 +136,10 @@ 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
.boolean()
.enum(['value', 'name'])
.optional()
.describe(
'When true, sort results by corrected duration descending. Default false.'
'Sort mode: "value" for corrected duration descending, "name" for alphabetical. Omit for execution order.'
),
search: z
.string()
......@@ -160,7 +160,7 @@ export async function startTurboTraceServerCli(
const result = bindings.turbo.queryTraceSpans(handle, {
parent: args.parent,
aggregated: args.aggregated ?? true,
sort: args.sort ?? false,
sort: args.sort,
search: args.search,
page: args.page ?? 1,
})
......
......@@ -256,7 +256,7 @@ describe('turbopack-trace-server', () => {
})
it('should drill into children of a span using its ID', async () => {
const { spans } = await querySpansJson(mcpPort, { sort: true })
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
const spanId = spans[0].id
const childMd = await callMcpTool(mcpPort, 'query_spans', {
......@@ -275,7 +275,7 @@ describe('turbopack-trace-server', () => {
it('should return results when searching for a real span name', async () => {
// Get a real span name from the root level via JSON output.
const { spans } = await querySpansJson(mcpPort, { sort: true })
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
const searchTerm = spans[0].name.slice(0, 20)
const md = await callMcpTool(mcpPort, 'query_spans', {
......@@ -286,8 +286,14 @@ describe('turbopack-trace-server', () => {
expect(md).toMatch(/###/)
})
it('should support sort by duration', async () => {
const md = await callMcpTool(mcpPort, 'query_spans', { sort: true })
it('should support sort by value', async () => {
const md = await callMcpTool(mcpPort, 'query_spans', { sort: 'value' })
expect(md).toContain('## Spans at root level')
expect(md).toMatch(/###/)
})
it('should support sort by name', async () => {
const md = await callMcpTool(mcpPort, 'query_spans', { sort: 'name' })
expect(md).toContain('## Spans at root level')
expect(md).toMatch(/###/)
})
......@@ -321,11 +327,24 @@ describe('turbopack-trace-server', () => {
expect(stdout).toMatch(/CPU Duration|Corrected Duration/)
})
it('CLI: should support --sort flag', async () => {
it('CLI: should support --sort value flag', async () => {
const { stdout, exitCode } = await runQueryTraceCli([
'--port',
String(mcpPort),
'--sort',
'value',
])
expect(exitCode).toBe(0)
expect(stdout).toContain('## Spans at root level')
expect(stdout).toMatch(/###/)
})
it('CLI: should support --sort name flag', async () => {
const { stdout, exitCode } = await runQueryTraceCli([
'--port',
String(mcpPort),
'--sort',
'name',
])
expect(exitCode).toBe(0)
expect(stdout).toContain('## Spans at root level')
......@@ -334,7 +353,7 @@ describe('turbopack-trace-server', () => {
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: true })
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
const searchTerm = spans[0].name.slice(0, 20)
const { stdout, exitCode } = await runQueryTraceCli([
......@@ -372,7 +391,7 @@ describe('turbopack-trace-server', () => {
})
it('CLI: should support --parent to drill into children', async () => {
const { spans } = await querySpansJson(mcpPort, { sort: true })
const { spans } = await querySpansJson(mcpPort, { sort: 'value' })
const spanId = spans[0].id
const { stdout, exitCode } = await runQueryTraceCli([
......
......@@ -57,6 +57,18 @@ pub fn start_turbopack_trace_server(path: PathBuf, port: Option<u16>) -> Arc<Sto
const PAGE_SIZE: usize = 20;
/// How spans should be sorted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortMode {
/// No sorting — spans appear in execution/natural order.
#[default]
ExecutionOrder,
/// Sort by value (corrected duration descending).
Value,
/// Sort alphabetically by name, then by category.
Name,
}
/// Options for querying spans from the trace store.
pub struct QueryOptions {
/// Optional parent span ID (as produced by `SpanInfo::id`).
......@@ -64,8 +76,8 @@ pub struct QueryOptions {
pub parent: Option<String>,
/// When true, aggregate child spans with the same name.
pub aggregated: bool,
/// When true, sort results by corrected duration descending.
pub sort: bool,
/// How to sort the results.
pub sort: SortMode,
/// Optional substring search query.
pub search: Option<String>,
/// 1-based page number.
......@@ -224,12 +236,22 @@ pub fn query_spans(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryR
};
// Sort if requested.
if options.sort {
filtered.sort_by(|a, b| {
b.corrected_total_time()
.cmp(&a.corrected_total_time())
.then_with(|| b.total_time().cmp(&a.total_time()))
});
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 (page_items, page, total_pages, total_count) = paginate(filtered, options.page);
......@@ -307,12 +329,22 @@ pub fn query_spans(store: &Arc<StoreContainer>, options: QueryOptions) -> QueryR
};
// Sort if requested.
if options.sort {
filtered.sort_by(|a, b| {
b.corrected_total_time()
.cmp(&a.corrected_total_time())
.then_with(|| b.total_time().cmp(&a.total_time()))
});
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 (page_items, page, total_pages, total_count) = paginate(filtered, options.page);
......
......@@ -13,7 +13,7 @@ use crate::{
store_container::StoreContainer,
timestamp::Timestamp,
u64_string,
viewer::{Update, ViewLineUpdate, ViewMode, Viewer},
viewer::{SortMode, Update, ViewLineUpdate, ViewMode, Viewer},
};
#[derive(Serialize, Debug)]
......@@ -211,34 +211,39 @@ fn handle_connection(
)?;
}
ClientToServerMessage::ViewMode { id, mode, inherit } => {
let (mode, sorted) = if let Some(mode) = mode.strip_suffix("-sorted") {
(mode, true)
} else {
(mode.as_str(), false)
};
let (mode, sort_mode) =
if let Some(mode) = mode.strip_suffix("-sorted-by-name") {
(mode, SortMode::Name)
} else if let Some(mode) = mode.strip_suffix("-sorted-by-value") {
(mode, SortMode::Value)
} else if let Some(mode) = mode.strip_suffix("-sorted") {
(mode, SortMode::Value)
} else {
(mode.as_str(), SortMode::ExecutionOrder)
};
match mode {
"raw-spans" => {
state.viewer.set_view_mode(
id,
Some((ViewMode::RawSpans { sorted }, inherit)),
Some((ViewMode::RawSpans { sort_mode }, inherit)),
);
}
"aggregated" => {
state.viewer.set_view_mode(
id,
Some((ViewMode::Aggregated { sorted }, inherit)),
Some((ViewMode::Aggregated { sort_mode }, inherit)),
);
}
"bottom-up" => {
state.viewer.set_view_mode(
id,
Some((ViewMode::BottomUp { sorted }, inherit)),
Some((ViewMode::BottomUp { sort_mode }, inherit)),
);
}
"aggregated-bottom-up" => {
state.viewer.set_view_mode(
id,
Some((ViewMode::AggregatedBottomUp { sorted }, inherit)),
Some((ViewMode::AggregatedBottomUp { sort_mode }, inherit)),
);
}
_ => {
......
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