Skip to content

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

refactor(trace): unify in-process trace-trigger surface (#2554)

Maximilian Roos0b3cf7bdf043
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index f2a6bcd70..7591210d6 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -512,21 +512,14 @@ fn run_one_command(
} else {
None
};
- // `execute_shell_command` ultimately calls `Cmd::stream()`, which does not
- // emit a per-subprocess `[wt-trace]` record (unlike `Cmd::run()`). Wrap it
- // in a span so foreground hook/alias step time is attributable in the
- // trace output.
- let result = {
- let _span = Span::new("execute_shell_command");
- execute_shell_command(
- wt_path,
- &command_str,
- stdin_json,
- cmd.log_label.as_deref(),
- directives.clone(),
- fg_step.redirect_stdout_to_stderr,
- )
- };
+ let result = execute_shell_command(
+ wt_path,
+ &command_str,
+ stdin_json,
+ cmd.log_label.as_deref(),
+ directives.clone(),
+ fg_step.redirect_stdout_to_stderr,
+ );
match result {
Ok(()) => Ok(()),
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index f4578f143..91ec7bcb9 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -469,7 +469,7 @@ pub fn collect(
) -> anyhow::Result<Option<super::model::ListData>> {
let show_progress = matches!(render_target, RenderTarget::Table { progressive: true });
let render_table = matches!(render_target, RenderTarget::Table { .. });
- worktrunk::shell_exec::trace_instant("List collect started");
+ worktrunk::trace::instant("List collect started");
// Determine what to fetch speculatively in the parallel phase.
//
@@ -953,7 +953,7 @@ pub fn collect(
max_width,
);
table.render_skeleton()?;
- worktrunk::shell_exec::trace_instant("Skeleton rendered");
+ worktrunk::trace::instant("Skeleton rendered");
Some(table)
} else {
None
@@ -970,7 +970,7 @@ pub fn collect(
handler.on_skeleton(all_items.clone(), skeletons, layout.render_header_line());
// Mirror the `wt list` progressive-table marker so `wt-perf phases`
// sees the same boundary across both commands.
- worktrunk::shell_exec::trace_instant("Skeleton rendered");
+ worktrunk::trace::instant("Skeleton rendered");
}
/// Delay before the `·` loading indicator replaces blank placeholders.
@@ -1177,9 +1177,9 @@ pub fn collect(
// worker-thread split lets the drain loop start consuming results on
// the main thread immediately.
let tx_worker = tx.clone();
- worktrunk::shell_exec::trace_instant("Spawning worker thread");
+ worktrunk::trace::instant("Spawning worker thread");
std::thread::spawn(move || {
- worktrunk::shell_exec::trace_instant("Parallel execution started");
+ worktrunk::trace::instant("Parallel execution started");
all_work_items.into_par_iter().for_each(|item| {
worktrunk::shell_exec::set_command_timeout(command_timeout);
let result = item.execute();
@@ -1261,7 +1261,7 @@ pub fn collect(
let mut s = state_cell.borrow_mut();
if !s.first_result_traced {
s.first_result_traced = true;
- worktrunk::shell_exec::trace_instant("First result received");
+ worktrunk::trace::instant("First result received");
}
s.completed_results += 1;
@@ -1340,7 +1340,7 @@ pub fn collect(
},
reveal_at,
);
- worktrunk::shell_exec::trace_instant("All results drained");
+ worktrunk::trace::instant("All results drained");
// Extract progressive state back out. `progressive_table` is re-bound so
// post-drain code (finalize / error rendering) works unchanged.
@@ -1490,7 +1490,7 @@ pub fn collect(
// - `RenderTarget::Json`: no stdout rendering; data returned for the
// caller to serialize (`wt list --format=json`) or feed into its own
// UI (picker via `progressive_handler`)
- worktrunk::shell_exec::trace_instant("List collect complete");
+ worktrunk::trace::instant("List collect complete");
Ok(Some(super::model::ListData { items }))
}
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index bff476e19..4b7a5098e 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -386,7 +386,7 @@ pub fn handle_picker(
if std::env::var_os("WORKTRUNK_PICKER_DRY_RUN").is_none() && !std::io::stdin().is_terminal() {
anyhow::bail!("Interactive picker requires an interactive terminal");
}
- worktrunk::shell_exec::trace_instant("Picker started");
+ worktrunk::trace::instant("Picker started");
let (repo, is_recovered) = current_or_recover()?;
@@ -395,11 +395,11 @@ pub fn handle_picker(
let change_dir = change_dir_flag.unwrap_or_else(|| config.switch.cd());
let show_branches = cli_branches || config.list.branches();
let show_remotes = cli_remotes || config.list.remotes();
- worktrunk::shell_exec::trace_instant("Picker config resolved");
+ worktrunk::trace::instant("Picker config resolved");
// Initialize preview mode state file (auto-cleanup on drop)
let state = PreviewState::new();
- worktrunk::shell_exec::trace_instant("Picker layout detected");
+ worktrunk::trace::instant("Picker layout detected");
// Prime the current worktree's root / git-dir / branch caches with one
// batched `git rev-parse`. Subsumes the two standalone forks that the
@@ -483,7 +483,7 @@ pub fn handle_picker(
}
estimate
};
- worktrunk::shell_exec::trace_instant("Picker estimate computed");
+ worktrunk::trace::instant("Picker estimate computed");
let preview_window_spec = state
.initial_layout
.to_preview_window_spec(num_items_estimate);
@@ -608,7 +608,7 @@ pub fn handle_picker(
// Legend/controls moved to preview window tabs (render_preview_tabs)
.build()
.map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;
- worktrunk::shell_exec::trace_instant("Picker skim options built");
+ worktrunk::trace::instant("Picker skim options built");
let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();
@@ -651,7 +651,7 @@ pub fn handle_picker(
);
})
.context("Failed to spawn picker-collect thread")?;
- worktrunk::shell_exec::trace_instant("Picker collect spawned");
+ worktrunk::trace::instant("Picker collect spawned");
// Drop main-thread copies so the bg thread's `tx` clone is the last
// sender (its drop is what stops skim's heartbeat).
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 1400d3c54..26cd26a73 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -360,16 +360,6 @@ pub fn set_command_timeout(timeout: Option<Duration>) {
COMMAND_TIMEOUT.with(|t| t.set(timeout));
}
-/// Emit an instant trace event (a milestone marker with no duration).
-///
-/// Re-exported from [`crate::trace::emit::instant`] for convenience at the
-/// call sites that already import from `shell_exec`. Instant events appear as
-/// vertical lines in Chrome Trace Format visualization tools
-/// (chrome://tracing, Perfetto).
-pub fn trace_instant(event: &str) {
- crate::trace::emit::instant(event);
-}
-
/// Maximum lines of captured stdout/stderr emitted to stderr per stream.
/// Exceeded content is elided with a `… (N more lines, M bytes elided)` marker;
/// the full output is still written to `output.log` via
@@ -663,6 +653,63 @@ impl ExternalCommandLog {
}
}
+/// Per-subprocess `[wt-trace]` recorder used by `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.
+struct WtTraceLog<'a> {
+ context: Option<&'a str>,
+ cmd_str: &'a str,
+ started_at: Instant,
+ ts: u64,
+ tid: u64,
+}
+
+impl<'a> WtTraceLog<'a> {
+ fn new(context: Option<&'a str>, cmd_str: &'a str) -> Self {
+ let started_at = Instant::now();
+ let ts = started_at
+ .duration_since(crate::trace::emit::trace_epoch())
+ .as_micros() as u64;
+ let tid = crate::trace::emit::thread_id();
+ Self {
+ context,
+ cmd_str,
+ started_at,
+ ts,
+ tid,
+ }
+ }
+
+ fn completed(&self, success: bool) {
+ let dur_us = self.started_at.elapsed().as_micros() as u64;
+ crate::trace::emit::command_completed(
+ self.context,
+ self.cmd_str,
+ self.ts,
+ self.tid,
+ dur_us,
+ success,
+ );
+ }
+
+ fn errored(&self, err: impl std::fmt::Display) {
+ let dur_us = self.started_at.elapsed().as_micros() as u64;
+ crate::trace::emit::command_errored(
+ self.context,
+ self.cmd_str,
+ self.ts,
+ self.tid,
+ dur_us,
+ err,
+ );
+ }
+}
+
impl Cmd {
fn builder(program: impl Into<String>, shell_wrap: bool) -> Self {
Self {
@@ -1267,11 +1314,17 @@ impl Cmd {
// Prevent vergen "overridden" warning in nested cargo builds
.env_remove("VERGEN_GIT_DESCRIBE");
- let mut child = cmd.spawn().map_err(|e| {
- anyhow::Error::from(GitError::Other {
- message: format!("Failed to execute command ({}): {}", exec_mode, e),
- })
- })?;
+ let trace_log = WtTraceLog::new(self.context.as_deref(), &cmd_str);
+
+ let mut child = match cmd.spawn() {
+ Ok(child) => child,
+ Err(e) => {
+ trace_log.errored(&e);
+ return Err(anyhow::Error::from(GitError::Other {
+ message: format!("Failed to execute command ({}): {}", exec_mode, e),
+ }));
+ }
+ };
// Write stdin content if provided (ignore BrokenPipe - child may exit early)
if let Some(ref content) = self.stdin_data
@@ -1279,6 +1332,7 @@ impl Cmd {
&& let Err(e) = stdin.write_all(content)
&& e.kind() != std::io::ErrorKind::BrokenPipe
{
+ trace_log.errored(&e);
return Err(e.into());
}
// stdin handle is dropped here, closing the pipe
@@ -1346,15 +1400,20 @@ impl Cmd {
(sig != 0).then_some(sig)
});
- let status = wait_result.map_err(|e| {
- anyhow::Error::from(GitError::Other {
- message: format!("Failed to wait for command: {}", e),
- })
- })?;
+ let status = match wait_result {
+ Ok(status) => status,
+ Err(e) => {
+ trace_log.errored(&e);
+ return Err(anyhow::Error::from(GitError::Other {
+ message: format!("Failed to wait for command: {}", e),
+ }));
+ }
+ };
// Handle signals (Unix only)
#[cfg(unix)]
if let Some(sig) = seen_signal {
+ trace_log.completed(false);
external_log.record(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
@@ -1369,9 +1428,11 @@ impl Cmd {
// SIGPIPE (13) is expected when a pager (less, bat) exits before the
// child finishes writing — not an error from the user's perspective.
if sig == SIGPIPE {
+ trace_log.completed(true);
external_log.record(Some(0));
return Ok(());
}
+ trace_log.completed(false);
external_log.record(Some(128 + sig));
return Err(WorktrunkError::ChildProcessExited {
code: 128 + sig,
@@ -1383,6 +1444,7 @@ impl Cmd {
if !status.success() {
let code = status.code().unwrap_or(1);
+ trace_log.completed(false);
external_log.record(status.code());
return Err(WorktrunkError::ChildProcessExited {
code,
@@ -1392,6 +1454,7 @@ impl Cmd {
.into());
}
+ trace_log.completed(true);
external_log.record(Some(0));
Ok(())
@@ -1818,6 +1881,20 @@ mod tests {
}
}
+ #[test]
+ fn test_cmd_stream_spawn_failure_is_errored() {
+ // Spawning a non-existent binary fails inside `cmd.spawn()`, exercising
+ // the `Err` arm of the new spawn-match in `stream()` (and the
+ // `WtTraceLog::errored` path that fires alongside it).
+ let result = Cmd::new("/no/such/binary-7f3a9b2c").stream();
+ assert!(result.is_err());
+ let msg = result.unwrap_err().to_string();
+ assert!(
+ msg.contains("Failed to execute command"),
+ "expected spawn-failure message, got: {msg}"
+ );
+ }
+
#[test]
#[cfg(unix)]
fn test_cmd_shell_stream_with_stdin() {
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index 27007651b..a24b0fc7f 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -38,5 +38,5 @@ pub mod parse;
// Re-export main types for convenience
pub use chrome::to_chrome_trace;
-pub use emit::Span;
+pub use emit::{Span, instant};
pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_lines};