Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Add wt-perf timeline subcommand for trace capture & rendering (#2558)

Maximilian Roosdb1beb61b88b
diff --git a/CLAUDE.md b/CLAUDE.md
index ce0ac4d1b..5929c7739 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -304,14 +304,28 @@ For each uncovered function/method, either write a test or document why it's int
## Benchmarks
-Benchmarks measure `wt list` performance across worktree counts and repository sizes.
+Benchmarks measure `wt list` performance across worktree counts and repository sizes. Criterion takes a positional `FILTER` (substring inclusion) — there's no `--skip`. Pick a filter that *includes* what you want.
```bash
-cargo bench --bench list -- --skip cold --skip real # fast synthetic benchmarks
-cargo bench --bench list bench_list_by_worktree_count # specific benchmark
+cargo bench --bench list skeleton # fast synthetic group only
+cargo bench --bench list scaling/warm # one variant
+cargo bench --bench alias # alias-dispatch overhead
```
-Real repo benchmarks clone rust-lang/rust (~2-5 min first run, cached thereafter). Skip with `--skip real`. See `benches/CLAUDE.md` for methodology and adding new benchmarks.
+Real-repo benchmarks (`real_repo`, `real_repo_many_branches`) clone rust-lang/rust on first run (~2–5 min, cached at `target/bench-repos/rust/`). To skip them, name a synthetic group instead. See `benches/CLAUDE.md` for the full filter map, expected numbers, and adding new benchmarks.
+
+## Traces
+
+To trace a single `wt` invocation, use `wt-perf timeline` (text timeline by default; `--chrome` emits Chrome Trace Format JSON for Perfetto/chrome://tracing):
+
+```bash
+cargo run -p wt-perf -- timeline -- list --progressive
+cargo run -p wt-perf -- timeline --cold --repo /tmp/wt-perf-typical-8 -- \
+ -C /tmp/wt-perf-typical-8 list --progressive
+cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
+```
+
+The summary distinguishes `traced` (first → last `[wt-trace]` record) from `wall` (externally-measured spawn → wait); the gap between them is prelude/epilogue not visible to the trace. See `benches/CLAUDE.md` → "Generating traces" for the SQL-query path via `trace_processor`.
### Don't wait for CI `benchmarks` before merging
diff --git a/Cargo.lock b/Cargo.lock
index 12b384cf4..a43fbc65f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2354,6 +2354,15 @@ dependencies = [
"unicode-width 0.2.2",
]
+[[package]]
+name = "tabwriter"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fce91f2f0ec87dff7e6bcbbeb267439aa1188703003c6055193c821487400432"
+dependencies = [
+ "unicode-width 0.2.2",
+]
+
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -3216,7 +3225,9 @@ version = "0.1.0"
dependencies = [
"clap",
"dunce",
+ "insta",
"serde_json",
+ "tabwriter",
"tempfile",
"worktrunk",
]
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index b07427749..b3d90675c 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -136,16 +136,43 @@ cargo run -p wt-perf -- invalidate /tmp/wt-perf-typical-8/main
### Generating traces
+`wt-perf timeline` runs a `wt` invocation, captures `[wt-trace]` records,
+and renders. Default mode is a sorted text timeline; `--chrome` emits
+Chrome Trace Format JSON for Perfetto/chrome://tracing. `--cold`
+invalidates caches first.
+
```bash
-# Generate trace.json for Perfetto/Chrome. `--progressive` forces TTY-gated
-# events (Skeleton rendered, First result received) to fire even when stdout
-# is piped.
-RUST_LOG=debug wt list --progressive --branches 2>&1 \
- | cargo run -p wt-perf -- trace > trace.json
+# Text timeline of one wt invocation
+cargo run -p wt-perf -- timeline -- list --progressive
+
+# Cold-cache run
+cargo run -p wt-perf -- timeline --cold --repo /tmp/wt-perf-typical-8 -- \
+ -C /tmp/wt-perf-typical-8 list --progressive
+# Chrome Trace Format JSON for Perfetto
+cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
# Open in https://ui.perfetto.dev or chrome://tracing
```
+`--progressive` is still required: `wt-perf timeline` runs wt with stdout
+piped to /dev/null, so TTY-gated events (`Skeleton rendered`, `First
+result received`) won't fire without it.
+
+For Chrome JSON from a log already captured to disk (e.g. a CI artifact),
+pipe through `wt-perf trace` instead:
+
+```bash
+RUST_LOG=debug wt list --progressive --branches 2> captured.log
+cargo run -p wt-perf -- trace < captured.log > trace.json
+```
+
+The text-timeline summary reports `traced` (first → last `[wt-trace]`
+record, what the spans actually cover) and `wall` (externally-measured
+spawn → wait, the true process duration). The gap between them is
+prelude/epilogue not visible to the trace — process spawn, dyld, code
+that runs before `init_logging` registers the trace epoch, and the exit
+path after the last span drops.
+
### Querying with trace_processor
Install [trace_processor](https://perfetto.dev/docs/analysis/trace-processor) for SQL analysis:
diff --git a/benches/list.rs b/benches/list.rs
index 70e77b67d..c0ff623fb 100644
--- a/benches/list.rs
+++ b/benches/list.rs
@@ -12,13 +12,13 @@
// - warm_worktrees_only: no branch enumeration (~600ms)
// - timeout_effect: Compare with/without 500ms command timeout on rust repo / GH #461 fix
//
-// Run examples:
+// Run examples (Criterion takes a positional substring FILTER; no --skip):
// cargo bench --bench list # All benchmarks
// cargo bench --bench list skeleton # Progressive rendering
// cargo bench --bench list real_repo_many_branches # GH #461 scenario (large repo + many branches)
// cargo bench --bench list timeout_effect # Test timeout fix for GH #461
-// cargo bench --bench list -- --skip cold # Skip cold cache variants
-// cargo bench --bench list -- --skip real # Skip rust repo clone
+// cargo bench --bench list warm # Warm-cache variants (every group's warm rows)
+// cargo bench --bench list skeleton/warm # Skeleton group, warm only
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use std::path::{Path, PathBuf};
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index a24b0fc7f..4149685ae 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -12,11 +12,16 @@
//! # Usage
//!
//! ```bash
-//! # Generate Chrome Trace Format (--progressive forces TTY-gated events
-//! # like `Skeleton rendered` to fire even when stdout is piped)
-//! RUST_LOG=debug wt list --progressive 2>&1 | cargo run -p wt-perf -- trace > trace.json
+//! # Text timeline of one wt invocation
+//! cargo run -p wt-perf -- timeline -- list --progressive
//!
-//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev
+//! # Chrome Trace Format JSON for Perfetto/chrome://tracing
+//! # (--progressive forces TTY-gated events like `Skeleton rendered` to
+//! # fire even though wt-perf pipes wt's stdout to /dev/null)
+//! cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
+//!
+//! # From a log already captured to disk
+//! cargo run -p wt-perf -- trace < captured.log > trace.json
//!
//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)
//! trace_processor trace.json -Q 'SELECT name, COUNT(*), SUM(dur)/1e6 as ms FROM slice GROUP BY name'
diff --git a/tests/helpers/wt-perf/Cargo.toml b/tests/helpers/wt-perf/Cargo.toml
index b1d441620..0dc2c6528 100644
--- a/tests/helpers/wt-perf/Cargo.toml
+++ b/tests/helpers/wt-perf/Cargo.toml
@@ -21,6 +21,9 @@ clap = { version = "4", features = ["derive"] }
# For JSON output
serde_json = "1"
+# For column-aligned timeline tables (elastic tabstops)
+tabwriter = "1"
+
# For trace parsing (reuse worktrunk's trace module).
# `default-features = false` avoids leaking the `cli` feature into the
# workspace-unified resolution of worktrunk; without it, `cargo check
@@ -28,6 +31,9 @@ serde_json = "1"
# masking gating bugs in lib code that uses `cli`-gated dependencies.
worktrunk = { path = "../../..", default-features = false }
+[dev-dependencies]
+insta = "1.47"
+
[lib]
name = "wt_perf"
path = "src/lib.rs"
diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rs
index c375e8766..56297094c 100644
--- a/tests/helpers/wt-perf/src/main.rs
+++ b/tests/helpers/wt-perf/src/main.rs
@@ -4,8 +4,11 @@
use std::io::{IsTerminal, Read, Write};
use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
use clap::{Parser, Subcommand};
+use worktrunk::trace::{TraceEntry, TraceEntryKind, TraceResult};
use wt_perf::{canonicalize, create_repo_at, invalidate_caches_auto, parse_config};
#[derive(Parser)]
@@ -72,6 +75,45 @@ enum Commands {
/// Path to trace log file (reads from stdin if omitted)
file: Option<PathBuf>,
},
+
+ /// Run a `wt` command with tracing on and render a timeline.
+ ///
+ /// Sets `RUST_LOG=debug` on the child so `[wt-trace]` records emit on
+ /// stderr alongside the rest of debug output, parses out the trace
+ /// records, sorts them by start time, and prints a column-aligned
+ /// timeline to stdout. With `--chrome`, emits Chrome Trace Format JSON
+ /// instead — pipe to a file and open in chrome://tracing or
+ /// https://ui.perfetto.dev.
+ #[command(after_long_help = r#"EXAMPLES:
+ # Text timeline of `wt list` in the current repo
+ wt-perf timeline -- list
+
+ # Cold-cache run (invalidates ./ then runs)
+ wt-perf timeline --cold -- list
+
+ # Cold run against a specific repo
+ wt-perf timeline --cold --repo /tmp/wt-perf-typical-1 -- -C /tmp/wt-perf-typical-1 list
+
+ # Chrome Trace Format JSON for Perfetto
+ wt-perf timeline --chrome -- list > trace.json
+"#)]
+ Timeline {
+ /// Invalidate caches before running (cold measurement).
+ #[arg(long)]
+ cold: bool,
+
+ /// Repo to invalidate (only used with --cold). Defaults to cwd.
+ #[arg(long, value_name = "PATH")]
+ repo: Option<PathBuf>,
+
+ /// Output Chrome Trace Format JSON to stdout instead of a text timeline.
+ #[arg(long)]
+ chrome: bool,
+
+ /// Args passed to `wt`. Use `--` to separate them from timeline flags.
+ #[arg(trailing_var_arg = true, allow_hyphen_values = true, required = true)]
+ wt_args: Vec<String>,
+ },
}
fn main() {
@@ -122,7 +164,11 @@ fn main() {
eprintln!("Created: {}", parts.join(", "));
eprintln!();
eprintln!(
- " RUST_LOG=debug wt -C {} list --progressive 2>&1 | wt-perf trace > trace.json",
+ " wt-perf timeline -- -C {} list --progressive",
+ base_path.display()
+ );
+ eprintln!(
+ " wt-perf timeline --chrome -- -C {} list --progressive > trace.json",
base_path.display()
);
eprintln!(" wt-perf invalidate {}", base_path.display());
@@ -166,6 +212,214 @@ fn main() {
let entries = read_trace_entries(file.as_deref());
cache_check(&entries);
}
+
+ Commands::Timeline {
+ cold,
+ repo,
+ chrome,
+ wt_args,
+ } => run_timeline(cold, repo, chrome, &wt_args),
+ }
+}
+
+/// Resolve the `wt` binary as a sibling of the current executable
+/// (`target/{debug,release}/wt-perf` → `target/{debug,release}/wt`).
+/// `EXE_SUFFIX` keeps this correct on Windows, where Cargo builds
+/// `wt-perf.exe` next to `wt.exe`.
+fn resolve_wt_binary() -> PathBuf {
+ let me = std::env::current_exe().unwrap_or_else(|e| {
+ eprintln!("Failed to resolve current executable: {e}");
+ std::process::exit(1);
+ });
+ let exe = format!("wt{}", std::env::consts::EXE_SUFFIX);
+ let candidate = me.parent().map(|p| p.join(&exe)).unwrap_or_default();
+ if !candidate.is_file() {
+ eprintln!(
+ "wt binary not found at {} — run `cargo build --release --bin wt` (or `cargo build --bin wt`) first.",
+ candidate.display()
+ );
+ std::process::exit(1);
+ }
+ candidate
+}
+
+/// Run a `wt` command with `RUST_LOG=debug`, capture stderr, and render.
+fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[String]) {
+ let wt = resolve_wt_binary();
+
+ if cold {
+ let path = repo
+ .clone()
+ .unwrap_or_else(|| std::env::current_dir().unwrap());
+ let path = canonicalize(&path).unwrap_or_else(|e| {
+ eprintln!("Invalid repo path {}: {}", path.display(), e);
+ std::process::exit(1);
+ });
+ if !path.join(".git").exists() {
+ eprintln!("--cold target is not a git repository: {}", path.display());
+ std::process::exit(1);
+ }
+ invalidate_caches_auto(&path);
+ }
+
+ // Measure spawn → wait wall externally. The trace can't see the
+ // process prelude (argv parsing, dyld, the time before `init_logging`
+ // registers the logger and the trace_epoch is set) or the epilogue
+ // (drop, exit), so the externally-measured duration is the only honest
+ // answer to "how long did the whole thing take". Quantize to
+ // microseconds — same precision as in-trace records, so the output
+ // doesn't mix `4.5ms` and `19.161583ms`.
+ let started = Instant::now();
+ let output = Command::new(&wt)
+ .args(wt_args)
+ .env("RUST_LOG", "debug")
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .output()
+ .unwrap_or_else(|e| {
+ eprintln!("Failed to spawn {}: {e}", wt.display());
+ std::process::exit(1);
+ });
+ let wall = Duration::from_micros(started.elapsed().as_micros() as u64);
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let entries = worktrunk::trace::parse_lines(&stderr);
+
+ if entries.is_empty() {
+ eprintln!(
+ "No [wt-trace] entries captured. wt exited with {}; check that the command runs past `init_logging` (e.g. avoid `--version`/`--help`).",
+ output.status,
+ );
+ if !output.stderr.is_empty() {
+ eprintln!("--- wt stderr ---\n{stderr}");
+ }
+ std::process::exit(1);
+ }
+
+ if chrome {
+ println!("{}", worktrunk::trace::to_chrome_trace(&entries));
+ } else {
+ print!("{}", render_timeline(&entries, wall));
+ }
+
+ if !output.status.success() {
+ eprintln!("note: wt exited with {}", output.status);
+ std::process::exit(1);
+ }
+}
+
+/// Render parsed entries as a column-aligned, start-time-sorted timeline.
+///
+/// `wall` is the externally-measured spawn → wait duration. The trace
+/// can't see the prelude (argv parsing, dyld, time before `init_logging`
+/// sets the trace epoch) or the exit path, so reporting `wall` lets
+/// readers see how much of the process the trace actually accounts for —
+/// the gap between `traced` and `wall` is the unobserved overhead.
+///
+/// Column alignment uses `tabwriter`'s elastic tabstops (write `\t`-separated
+/// rows, padding is computed at flush). Durations are rendered via
+/// `Duration`'s `Debug` impl, which produces compact units (`999µs`, `4.5ms`,
+/// `1.5s`) — matches what we want without a dedicated humanization crate.
+fn render_timeline(entries: &[TraceEntry], wall: Duration) -> String {
+ let mut sorted: Vec<&TraceEntry> = entries.iter().collect();
+ sorted.sort_by_key(|e| e.start_time_us.unwrap_or(0));
+
+ let mut tw = tabwriter::TabWriter::new(Vec::<u8>::new())
+ .minwidth(2)
+ .padding(2);
+ writeln!(tw, "ts(ms)\tdur\ttid\tkind\tname").unwrap();
+ for e in &sorted {
+ let (kind, dur, name) = describe(e);
+ let ts_ms = e.start_time_us.unwrap_or(0) as f64 / 1_000.0;
+ let tid = e
+ .thread_id
+ .map(|t| t.to_string())
+ .unwrap_or_else(|| "-".into());
+ writeln!(tw, "{ts_ms:.3}\t{dur:?}\t{tid}\t{kind}\t{name}").unwrap();
+ }
+ tw.flush().unwrap();
+ let mut out = String::from_utf8(tw.into_inner().unwrap()).unwrap();
+
+ // Summary: subprocess totals + traced span + true process wall.
+ let cmds: Vec<(Duration, String)> = sorted
+ .iter()
+ .filter_map(|e| match &e.kind {
+ TraceEntryKind::Command { duration, .. } => {
+ let (_, _, name) = describe(e);
+ Some((*duration, name))
+ }
+ _ => None,
+ })
+ .collect();
+ let cmd_total: Duration = cmds.iter().map(|(d, _)| *d).sum();
+ let slowest = cmds.iter().max_by_key(|(d, _)| *d);
+ let traced = Duration::from_micros(
+ sorted
+ .iter()
+ .map(|e| e.start_time_us.unwrap_or(0) + duration_of(e).as_micros() as u64)
+ .max()
+ .unwrap_or(0)
+ .saturating_sub(
+ sorted
+ .iter()
+ .map(|e| e.start_time_us.unwrap_or(0))
+ .min()
+ .unwrap_or(0),
+ ),
+ );
+ let untraced = wall.saturating_sub(traced);
+
+ out.push('\n');
+ if let Some((dur, name)) = slowest {
+ let plural = if cmds.len() == 1 { "" } else { "es" };
+ out.push_str(&format!(
+ "{} subprocess{plural} totaling {cmd_total:?} (slowest: {dur:?} {name})\n",
+ cmds.len(),
+ ));
+ } else {
+ out.push_str("0 subprocesses\n");
+ }
+ out.push_str(&format!(
+ "traced: {traced:?} (first → last [wt-trace] record)\n"
+ ));
+ out.push_str(&format!(
+ "wall: {wall:?} (spawn → wait; +{untraced:?} untraced prelude/epilogue)\n"
+ ));
+ out
+}
+
+/// Extract the (kind, duration, display-name) tuple for a trace entry.
+fn describe(e: &TraceEntry) -> (&'static str, Duration, String) {
+ match &e.kind {
+ TraceEntryKind::Command {
+ command,
+ duration,
+ result,
+ } => {
+ let mut label = match e.context.as_deref() {
+ Some(c) => format!("{command} [{c}]"),
+ None => command.clone(),
+ };
+ match result {
+ TraceResult::Completed { success: false } => label.push_str(" (ok=false)"),
+ TraceResult::Error { message } => label.push_str(&format!(" (err: {message})")),
+ TraceResult::Completed { success: true } => {}
+ }
+ ("cmd", *duration, label)
+ }
+ TraceEntryKind::Span { name, duration } => ("span", *duration, name.clone()),
+ TraceEntryKind::Instant { name } => ("event", Duration::ZERO, name.clone()),
+ }
+}
+
+/// Duration of an entry (zero for instant events).
+fn duration_of(e: &TraceEntry) -> Duration {
+ match &e.kind {
+ TraceEntryKind::Command { duration, .. } | TraceEntryKind::Span { duration, .. } => {
+ *duration
+ }
+ TraceEntryKind::Instant { .. } => Duration::ZERO,
}
}
@@ -308,3 +562,86 @@ fn cache_check(entries: &[worktrunk::trace::TraceEntry]) {
});
println!("{}", serde_json::to_string_pretty(&output).unwrap());
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn span(name: &str, ts_us: u64, dur_us: u64, tid: u64) -> TraceEntry {
+ TraceEntry {
+ context: None,
+ kind: TraceEntryKind::Span {
+ name: name.to_string(),
+ duration: Duration::from_micros(dur_us),
+ },
+ start_time_us: Some(ts_us),
+ thread_id: Some(tid),
+ }
+ }
+
+ fn cmd(
+ cmd: &str,
+ ctx: Option<&str>,
+ ts_us: u64,
+ dur_us: u64,
+ tid: u64,
+ ok: bool,
+ ) -> TraceEntry {
+ TraceEntry {
+ context: ctx.map(|s| s.to_string()),
+ kind: TraceEntryKind::Command {
+ command: cmd.to_string(),
+ duration: Duration::from_micros(dur_us),
+ result: TraceResult::Completed { success: ok },
+ },
+ start_time_us: Some(ts_us),
+ thread_id: Some(tid),
+ }
+ }
+
+ #[test]
+ fn renders_sorted_timeline_with_summary() {
+ // Emit order swaps span and child cmd (parent finishes after child),
+ // so this exercises the sort-by-start-time guarantee. Durations are
+ // chosen so std `Duration` Debug renders compact (no trailing
+ // sub-millisecond precision): 4ms, 4.1ms, 280µs, 8µs.
+ let entries = vec![
+ cmd("git rev-parse HEAD", Some("repo"), 50, 4_000, 1, true),
+ span("prewarm", 30, 4_100, 1),
+ span("init_logging", 0, 8, 1),
+ span("user_config_load", 4_200, 280, 38),
+ ];
+ // Wall = 6ms; traced = 4.48ms (4.2ms start → 4.48ms end);
+ // untraced prelude/epilogue = 6 - 4.48 = ~1.52ms.
+ insta::assert_snapshot!(
+ render_timeline(&entries, Duration::from_micros(6_000)),
+ @r"
+ ts(ms) dur tid kind name
+ 0.000 8µs 1 span init_logging
+ 0.030 4.1ms 1 span prewarm
+ 0.050 4ms 1 cmd git rev-parse HEAD [repo]
+ 4.200 280µs 38 span user_config_load
+
+ 1 subprocess totaling 4ms (slowest: 4ms git rev-parse HEAD [repo])
+ traced: 4.48ms (first → last [wt-trace] record)
+ wall: 6ms (spawn → wait; +1.52ms untraced prelude/epilogue)
+ "
+ );
+ }
+
+ #[test]
+ fn cmd_failure_annotates_name() {
+ let entries = vec![cmd("git foo", None, 0, 1_000, 1, false)];
+ insta::assert_snapshot!(
+ render_timeline(&entries, Duration::from_millis(2)),
+ @r"
+ ts(ms) dur tid kind name
+ 0.000 1ms 1 cmd git foo (ok=false)
+
+ 1 subprocess totaling 1ms (slowest: 1ms git foo (ok=false))
+ traced: 1ms (first → last [wt-trace] record)
+ wall: 2ms (spawn → wait; +1ms untraced prelude/epilogue)
+ "
+ );
+ }
+}