From e261e507614c19ca222722cb1da2ccd716527cf9 Mon Sep 17 00:00:00 2001 From: Worktrunk Bot Date: Mon, 4 May 2026 13:19:32 -0700 Subject: [PATCH] fix(wt-perf): move timeline tests to lib + exclude bin from test compile (#2604) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem The `collect affected coverage` job has been failing on every push to main since #2558 merged, with the same error shape: ``` FAIL [ 0.009s] (3487/3491) wt-perf::bin/wt-perf tests::cmd_failure_annotates_name cargo-affected runner-shim: failed to resolve binary_id for /home/runner/work/worktrunk/worktrunk/target/affected/build/debug/deps/wt_perf-01f04725fd165542: binary not found in map (path: /home/runner/work/worktrunk/worktrunk/target/affected/build/debug/deps/wt_perf-01f04725fd165542); target-name basename fallback ambiguous — 2 candidates share target name "wt_perf" ([wt-perf, wt-perf::bin/wt-perf]) and the marker probe matched 0 of them (none; candidates without markers: wt-perf::bin/wt-perf, wt-perf); re-run `cargo affected collect` ``` Root cause: the `[lib] name = "wt_perf"` and `[[bin]] name = "wt-perf"` artifacts both normalize to the same `wt_perf` basename. cargo-affected's runner shim disambiguates same-basename test binaries via a marker probe, but markers only fire for `kind = "test" | "bench" | "example"` — `lib` and `bin` get none. Once #2558 added inline tests under `bin/wt-perf`, both candidates appeared in cargo-affected's binary map without markers, so any hash drift between list and run aborted the shim with `basename fallback ambiguous`. Issue #2571 previously diagnosed this as transient, but it has continued to fail every run since (25295115776, 25301191157, 25303363793, 25309058661, [25336005330](https://github.com/max-sixty/worktrunk/actions/runs/25336005330)) with the same error shape — it is durable, not transient. ## Solution Two changes together fix it: - Move `render_timeline` (and its `describe`/`duration_of` helpers) plus the inline tests from `src/main.rs` into `src/lib.rs`. The bin no longer carries any `#[cfg(test)]` items. - Set `test = false` on the `[[bin]]` in `Cargo.toml` so cargo doesn't emit a test binary for it. This removes the bin from cargo-affected's binary map entirely, so even with hash drift the basename fallback finds a single candidate (the lib). The bin still gets compiled at `target/debug/wt-perf` because `tests/builds.rs` triggers it. ## Testing - `cargo build -p wt-perf` — produces the binary at `target/debug/wt-perf` and `wt-perf --help` works as before. - `cargo test -p wt-perf` — both timeline tests (`renders_sorted_timeline_with_summary`, `cmd_failure_annotates_name`) pass under the lib target; the bin target no longer ships a test binary. - `cargo clippy -p wt-perf --tests` — clean. This commit is identical to f168bdef on the orphaned `fix/ci-25289365418` branch (cherry-picked here onto a current main). --- Automated fix for [failed run](https://github.com/max-sixty/worktrunk/actions/runs/25336005330) Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> Co-authored-by: Claude --- tests/helpers/wt-perf/Cargo.toml | 9 ++ tests/helpers/wt-perf/src/lib.rs | 206 ++++++++++++++++++++++++++++++ tests/helpers/wt-perf/src/main.rs | 202 +---------------------------- 3 files changed, 218 insertions(+), 199 deletions(-) diff --git a/tests/helpers/wt-perf/Cargo.toml b/tests/helpers/wt-perf/Cargo.toml index 0dc2c6528..d00d569c6 100644 --- a/tests/helpers/wt-perf/Cargo.toml +++ b/tests/helpers/wt-perf/Cargo.toml @@ -41,3 +41,12 @@ path = "src/lib.rs" [[bin]] name = "wt-perf" path = "src/main.rs" +# The `[lib]` and `[[bin]]` artifact basenames both normalize to `wt_perf` +# (cargo turns `wt-perf` → `wt_perf`). cargo-affected's runner shim can't +# disambiguate same-basename test binaries when neither carries a marker +# (markers only fire for `kind = "test" | "bench" | "example"`), so when +# both candidates appear in its binary map and cargo's hash suffix drifts +# between list and run, the shim aborts with "basename fallback ambiguous". +# Excluding the bin from test compilation removes it from the map; the +# binary still gets compiled because `tests/builds.rs` depends on it. +test = false diff --git a/tests/helpers/wt-perf/src/lib.rs b/tests/helpers/wt-perf/src/lib.rs index fd4b46c66..cfae9b989 100644 --- a/tests/helpers/wt-perf/src/lib.rs +++ b/tests/helpers/wt-perf/src/lib.rs @@ -24,11 +24,14 @@ //! //! See `wt-perf --help` for CLI usage. +use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::OnceLock; +use std::time::Duration; use tempfile::TempDir; use worktrunk::testing::{NULL_DEVICE, configure_git_cmd}; +use worktrunk::trace::{TraceEntry, TraceEntryKind, TraceResult}; /// Lazy-initialized rust repo path. static RUST_REPO: OnceLock = OnceLock::new(); @@ -526,3 +529,206 @@ pub fn parse_config(s: &str) -> Option { _ => None, } } + +/// 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. +// +// Lives in the lib (rather than next to the `Timeline` subcommand in +// `main.rs`) so the inline tests below don't compile under the `bin/wt-perf` +// target. The package's `[lib]` and `[[bin]]` targets normalize to the same +// `wt_perf` artifact basename, and cargo-affected's runner shim can't +// disambiguate which target a test binary belongs to when both ship tests +// (the marker probe only fires for `kind = "test" | "bench" | "example"`). +// Keeping unit tests in the lib avoids the collision. +pub 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::::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 +} + +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()), + } +} + +fn duration_of(e: &TraceEntry) -> Duration { + match &e.kind { + TraceEntryKind::Command { duration, .. } | TraceEntryKind::Span { duration, .. } => { + *duration + } + TraceEntryKind::Instant { .. } => Duration::ZERO, + } +} + +#[cfg(test)] +mod timeline_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) + " + ); + } +} diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rs index 56297094c..ea6228c2d 100644 --- a/tests/helpers/wt-perf/src/main.rs +++ b/tests/helpers/wt-perf/src/main.rs @@ -8,8 +8,9 @@ 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}; +use wt_perf::{ + canonicalize, create_repo_at, invalidate_caches_auto, parse_config, render_timeline, +}; #[derive(Parser)] #[command(name = "wt-perf")] @@ -309,120 +310,6 @@ fn run_timeline(cold: bool, repo: Option, chrome: bool, wt_args: &[Stri } } -/// 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::::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, - } -} - /// Read trace input from file or stdin, parse entries, and exit if empty. fn read_trace_entries(file: Option<&std::path::Path>) -> Vec { let input = match file { @@ -562,86 +449,3 @@ 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) - " - ); - } -}