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