Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(trace): dynamic span names + share WtTraceLog across Cmd modes (#2555)
Maximilian Roos72176e593de3
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex f2ccecc9f..91a4d0ad3 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -431,7 +431,7 @@ fn referenced_vars_for_entry(entry: &AliasEntry) -> anyhow::Result<BTreeSet<Stri/// rather than silently turning into an "unrecognized subcommand" once we/// fall through to PATH lookup.pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Result<Option<()>> {- let _span = Span::new("try_alias");+ let _span = Span::new(format!("try_alias:{}", name));let Ok(repo) = Repository::current() else {return Ok(None);};@@ -549,7 +549,7 @@ fn run_alias(entry: &AliasEntry,global_yes: bool,) -> anyhow::Result<()> {- let _span = Span::new("run_alias");+ let _span = Span::new(format!("run_alias:{}", opts.name));for warning in &warnings {eprintln!("{}", warning_message(warning));}@@ -611,7 +611,7 @@ fn run_alias(let alias_name = opts.name.clone();let foreground_steps = {- let _span = Span::new("prepare_steps");+ let _span = Span::new(format!("prepare_steps:{}", alias_name));let mut sourced_steps = Vec::new();for (source, cfg) in entry.iter() {for step in cfg.steps() {diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 7591210d6..50d498413 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -437,12 +437,13 @@ fn run_concurrent_group(announce_command(cmd, &fg_step.announce);}- let expanded: Vec<String> = {- let _span = Span::new("template_render");- cmds.iter()- .map(|cmd| resolve_command_str(cmd, repo))- .collect::<Result<_>>()?- };+ let expanded: Vec<String> = cmds+ .iter()+ .map(|cmd| {+ let _span = Span::new(format!("template_render:{}", cmd.label));+ resolve_command_str(cmd, repo)+ })+ .collect::<Result<_>>()?;// Both alias tables and hook tables produce named commands (TOML keys// become `name`), so `cmd.name` is always `Some` here.@@ -500,7 +501,7 @@ fn run_one_command(announce_command(cmd, &fg_step.announce);let command_str = {- let _span = Span::new("template_render");+ let _span = Span::new(format!("template_render:{}", cmd.label));resolve_command_str(cmd, repo)?};diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 26cd26a73..f65742b60 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -470,33 +470,6 @@ fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {out}-/// Emit a `[wt-trace]` line plus stdout/stderr for a finished command.-fn log_command_result(- context: Option<&str>,- cmd_str: &str,- ts: u64,- tid: u64,- dur_us: u64,- result: &std::io::Result<std::process::Output>,-) {- match result {- Ok(output) => {- crate::trace::emit::command_completed(- context,- cmd_str,- ts,- tid,- dur_us,- output.status.success(),- );- log_output(output);- }- Err(e) => {- crate::trace::emit::command_errored(context, cmd_str, ts, tid, dur_us, e);- }- }-}-/// Implementation of timeout-based command execution.////// Spawns reader threads to drain stdout/stderr concurrently (preventing deadlock when@@ -653,14 +626,14 @@ impl ExternalCommandLog {}}-/// Per-subprocess `[wt-trace]` recorder used by `Cmd::stream`.+/// Per-subprocess `[wt-trace]` recorder used by `Cmd::run`, `Cmd::pipe_into`,+/// and `Cmd::stream`.///-/// Mirrors `ExternalCommandLog`'s shape but emits to the `[wt-trace]` grammar-/// (`crate::trace::emit`) rather than the per-command external log. Captures-/// `ts`/`tid`/`started_at` at construction; callers invoke `completed` /-/// `errored` at each exit point. `Cmd::run` and `Cmd::pipe_into` have a single-/// emit site each so they call `command_completed`/`command_errored`-/// directly — `stream` has six exit points and benefits from this helper.+/// Captures `ts`/`tid`/`started_at` at construction; callers invoke+/// `completed` / `errored` at each exit point. `record_result` is a+/// convenience wrapper used by `run`/`pipe_into` (which have a single+/// `Result<Output>` exit each, plus captured stdout/stderr to surface).+/// `stream` has multiple exit points and uses the lower-level methods.struct WtTraceLog<'a> {context: Option<&'a str>,cmd_str: &'a str,@@ -708,6 +681,20 @@ impl<'a> WtTraceLog<'a> {err,);}++ /// Emit a trace record for a finished `run`/`pipe_into` invocation and+ /// surface the captured stdout/stderr to the debug log. `stream` doesn't+ /// capture output (it inherits stdio), so it uses `completed`/`errored`+ /// directly.+ fn record_result(&self, result: &std::io::Result<std::process::Output>) {+ match result {+ Ok(output) => {+ self.completed(output.status.success());+ log_output(output);+ }+ Err(e) => self.errored(e),+ }+ }}impl Cmd {@@ -1011,12 +998,7 @@ impl Cmd {// Acquire semaphore to limit concurrent commandslet _guard = semaphore().acquire();- // Capture timing for tracing- let t0 = Instant::now();- let ts = t0- .duration_since(crate::trace::emit::trace_epoch())- .as_micros() as u64;- let tid = crate::trace::emit::thread_id();+ let trace_log = WtTraceLog::new(self.context.as_deref(), &cmd_str);let mut cmd = self.direct_command();self.apply_common_settings(&mut cmd);@@ -1051,9 +1033,7 @@ impl Cmd {cmd.output()};- // Log trace- let dur_us = t0.elapsed().as_micros() as u64;- log_command_result(self.context.as_deref(), &cmd_str, ts, tid, dur_us, &result);+ trace_log.record_result(&result);let exit_code = result.as_ref().ok().and_then(|output| output.status.code());external_log.record(exit_code);@@ -1121,11 +1101,8 @@ impl Cmd {let _guard = semaphore().acquire();- let t0 = Instant::now();- let ts = t0- .duration_since(crate::trace::emit::trace_epoch())- .as_micros() as u64;- let tid = crate::trace::emit::thread_id();+ let first_log = WtTraceLog::new(self.context.as_deref(), &first_cmd_str);+ let second_log = WtTraceLog::new(next.context.as_deref(), &second_cmd_str);let mut first = self.direct_command();self.apply_common_settings(&mut first);@@ -1168,7 +1145,7 @@ impl Cmd {.take().expect("stderr was configured as piped");- let (first_result, second_result, first_dur_us, second_dur_us) = std::thread::scope(|s| {+ let (first_result, second_result) = std::thread::scope(|s| {let stderr_thread = s.spawn(move || {let mut buf = Vec::new();first_stderr_pipe.read_to_end(&mut buf).map(|_| buf)@@ -1177,13 +1154,12 @@ impl Cmd {// Drain `next` first (its `wait_with_output` reads its own// stdout/stderr), so `first`'s writes can complete.let second_result = second_child.wait_with_output();- let second_dur_us = t0.elapsed().as_micros() as u64;+ second_log.record_result(&second_result);// Reap `first`. Its stderr is already being drained; combine// the captured stderr with the exit status into an Output.let first_status = first_child.wait();let first_stderr = stderr_thread.join().unwrap();- let first_dur_us = t0.elapsed().as_micros() as u64;let first_result = first_status.and_then(|status| {first_stderr.map(|stderr| std::process::Output {@@ -1192,27 +1168,11 @@ impl Cmd {stderr,})});+ first_log.record_result(&first_result);- (first_result, second_result, first_dur_us, second_dur_us)+ (first_result, second_result)});- log_command_result(- self.context.as_deref(),- &first_cmd_str,- ts,- tid,- first_dur_us,- &first_result,- );- log_command_result(- next.context.as_deref(),- &second_cmd_str,- ts,- tid,- second_dur_us,- &second_result,- );-Ok((first_result?, second_result?))}diff --git a/src/trace/emit.rs b/src/trace/emit.rsindex 549d24820..d3d5f9025 100644--- a/src/trace/emit.rs+++ b/src/trace/emit.rs@@ -27,6 +27,7 @@//! separate log targets: the full output goes to `output.log`, and a bounded//! preview goes to stderr + `trace.log` — so raw bodies don't spam `-vv`.+use std::borrow::Cow;use std::fmt::Display;use std::sync::OnceLock;use std::time::Instant;@@ -151,8 +152,10 @@ pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {/// Construct at the top of a block — `let _span = Span::new("config_load");` —/// and the span fires when `_span` goes out of scope.///-/// `name` is `&'static str` to keep construction allocation-free; for dynamic-/// names, call [`span_completed`] directly.+/// `name` accepts anything that converts into `Cow<'static, str>`: string+/// literals stay borrowed (allocation-free), and `String` becomes owned —+/// useful when the span name carries dynamic context, e.g.+/// `Span::new(format!("prepare_steps:{}", alias))`.////// The `log_enabled!` check happens on drop, not construction. A span/// constructed before `init_logging` (e.g. wrapping the logger init itself)@@ -160,15 +163,15 @@ pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {/// goes out of scope. Construction always pays two `Instant::now()` calls;/// they're vDSO-fast and the overhead is below noise.pub struct Span {- name: &'static str,+ name: Cow<'static, str>,start_ts_us: u64,start: Instant,}impl Span {- pub fn new(name: &'static str) -> Self {+ pub fn new(name: impl Into<Cow<'static, str>>) -> Self {Self {- name,+ name: name.into(),start_ts_us: now_us(),start: Instant::now(),}@@ -181,6 +184,6 @@ impl Drop for Span {return;}let dur_us = self.start.elapsed().as_micros() as u64;- span_completed(self.name, self.start_ts_us, thread_id(), dur_us);+ span_completed(&self.name, self.start_ts_us, thread_id(), dur_us);}}