Skip to content

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

feat(trace): Span RAII guard for in-process attribution (#2539)

Maximilian Roose47761dc188b
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 3f222aff1..6255755ff 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -51,6 +51,7 @@ use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, verbosity,
warning_message,
};
+use worktrunk::trace::Span;
use crate::commands::command_approval::approve_alias_commands;
use crate::commands::command_executor::{
@@ -430,23 +431,39 @@ 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 Ok(repo) = Repository::current() else {
return Ok(None);
};
- let user_config = UserConfig::load()?;
- let project_config = ProjectConfig::load(&repo, true)?;
- let aliases = load_aliases(Some(&repo), &user_config, project_config.as_ref());
+ let user_config = {
+ let _span = Span::new("user_config_load");
+ UserConfig::load()?
+ };
+ let project_config = {
+ let _span = Span::new("project_config_load");
+ ProjectConfig::load(&repo, true)?
+ };
+ let aliases = {
+ let _span = Span::new("load_aliases");
+ load_aliases(Some(&repo), &user_config, project_config.as_ref())
+ };
let Some(entry) = aliases.get(&name) else {
return Ok(None);
};
- let referenced = referenced_vars_for_entry(entry)?;
+ let referenced = {
+ let _span = Span::new("referenced_vars");
+ referenced_vars_for_entry(entry)?
+ };
if try_intercept_alias_help(&name, &rest, &referenced) {
return Ok(Some(()));
}
let mut alias_args = Vec::with_capacity(1 + rest.len());
alias_args.push(name);
alias_args.extend(rest);
- let (opts, warnings) = AliasOptions::parse(alias_args, &referenced)?;
+ let (opts, warnings) = {
+ let _span = Span::new("parse_alias_args");
+ AliasOptions::parse(alias_args, &referenced)?
+ };
let entry = aliases
.get(&opts.name)
.expect("entry verified above and `opts.name` matches the dispatched name");
@@ -534,6 +551,7 @@ fn run_alias(
entry: &AliasEntry,
global_yes: bool,
) -> anyhow::Result<()> {
+ let _span = Span::new("run_alias");
for warning in &warnings {
eprintln!("{}", warning_message(warning));
}
@@ -541,6 +559,7 @@ fn run_alias(
// Project bodies require approval even when user config also defines the
// alias — same as hooks. `global_yes` is the sole skip source.
if let Some(project_commands) = entry.project.as_ref() {
+ let _span = Span::new("alias_approve");
let project_id = repo
.project_identifier()
.context("Cannot determine project identifier for alias approval")?;
@@ -561,7 +580,10 @@ fn run_alias(
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let mut context_map = build_hook_context(&ctx, &extra_refs)?;
+ let mut context_map = {
+ let _span = Span::new("build_hook_context");
+ build_hook_context(&ctx, &extra_refs)?
+ };
// Forward positional CLI args to templates as `{{ args }}`. Encoded as a
// JSON list so it flows through the stable `HashMap<String, String>`
// context — `expand_template` rehydrates it into a `ShellArgs` sequence.
@@ -590,30 +612,34 @@ fn run_alias(
}
let alias_name = opts.name.clone();
- let mut sourced_steps = Vec::new();
- for (source, cfg) in entry.iter() {
- for step in cfg.steps() {
- let prepared = match step {
- HookStep::Single(cmd) => {
- PreparedStep::Single(alias_prepared_command(cmd, &context_json, &alias_name))
- }
- HookStep::Concurrent(cmds) => PreparedStep::Concurrent(
- cmds.iter()
- .map(|cmd| alias_prepared_command(cmd, &context_json, &alias_name))
- .collect(),
- ),
- };
- sourced_steps.push(SourcedStep {
- step: prepared,
- source,
- // Aliases have no deprecated single-table form, so concurrent
- // commands always run concurrently.
- is_pipeline: true,
- });
+ let foreground_steps = {
+ let _span = Span::new("prepare_steps");
+ let mut sourced_steps = Vec::new();
+ for (source, cfg) in entry.iter() {
+ for step in cfg.steps() {
+ let prepared = match step {
+ HookStep::Single(cmd) => PreparedStep::Single(alias_prepared_command(
+ cmd,
+ &context_json,
+ &alias_name,
+ )),
+ HookStep::Concurrent(cmds) => PreparedStep::Concurrent(
+ cmds.iter()
+ .map(|cmd| alias_prepared_command(cmd, &context_json, &alias_name))
+ .collect(),
+ ),
+ };
+ sourced_steps.push(SourcedStep {
+ step: prepared,
+ source,
+ // Aliases have no deprecated single-table form, so concurrent
+ // commands always run concurrently.
+ is_pipeline: true,
+ });
+ }
}
- }
- let foreground_steps =
- sourced_steps_to_foreground(sourced_steps, &PipelineKind::Alias { name: alias_name });
+ sourced_steps_to_foreground(sourced_steps, &PipelineKind::Alias { name: alias_name })
+ };
execute_pipeline_foreground(
&foreground_steps,
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index beb890bac..f2a6bcd70 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -14,6 +14,7 @@ use worktrunk::styling::{
eprintln, error_message, format_bash_with_gutter, format_with_gutter, info_message,
progress_message, verbosity,
};
+use worktrunk::trace::Span;
use super::format_command_label;
use super::hook_filter::HookSource;
@@ -235,16 +236,22 @@ pub fn build_hook_context(
}
// Default branch
- if let Some(default_branch) = ctx.repo.default_branch() {
- map.insert("default_branch".into(), default_branch);
+ {
+ let _span = Span::new("var_default_branch");
+ if let Some(default_branch) = ctx.repo.default_branch() {
+ map.insert("default_branch".into(), default_branch);
+ }
}
// Primary worktree path (where established files live)
- if let Ok(Some(path)) = ctx.repo.primary_worktree() {
- let path_str = to_posix_path(&path.to_string_lossy());
- map.insert("primary_worktree_path".into(), path_str.clone());
- // Deprecated alias
- map.insert("main_worktree_path".into(), path_str);
+ {
+ let _span = Span::new("var_primary_worktree");
+ if let Ok(Some(path)) = ctx.repo.primary_worktree() {
+ let path_str = to_posix_path(&path.to_string_lossy());
+ map.insert("primary_worktree_path".into(), path_str.clone());
+ // Deprecated alias
+ map.insert("main_worktree_path".into(), path_str);
+ }
}
// Resolve commit from the Active branch, not HEAD at discovery path.
@@ -255,36 +262,42 @@ pub fn build_hook_context(
// iterates over sibling worktrees, and a sibling on detached HEAD has a
// different HEAD than the worktree `wt` runs in. Branched contexts go
// through `rev-parse <branch>`, which is repo-wide.
- let commit = match ctx.branch {
- Some(branch) => ctx
- .repo
- .run_command(&["rev-parse", branch])
- .ok()
- .map(|s| s.trim().to_owned()),
- None => ctx
- .repo
- .worktree_at(ctx.worktree_path)
- .head_sha()
- .ok()
- .flatten(),
- };
- if let Some(commit) = commit {
- if commit.len() >= 7 {
- map.insert("short_commit".into(), commit[..7].into());
+ {
+ let _span = Span::new("var_commit");
+ let commit = match ctx.branch {
+ Some(branch) => ctx
+ .repo
+ .run_command(&["rev-parse", branch])
+ .ok()
+ .map(|s| s.trim().to_owned()),
+ None => ctx
+ .repo
+ .worktree_at(ctx.worktree_path)
+ .head_sha()
+ .ok()
+ .flatten(),
+ };
+ if let Some(commit) = commit {
+ if commit.len() >= 7 {
+ map.insert("short_commit".into(), commit[..7].into());
+ }
+ map.insert("commit".into(), commit);
}
- map.insert("commit".into(), commit);
}
- if let Ok(remote) = ctx.repo.primary_remote() {
- map.insert("remote".into(), remote.to_string());
- // Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)
- if let Some(url) = ctx.repo.remote_url(&remote) {
- map.insert("remote_url".into(), url);
- }
- if let Some(branch) = ctx.branch
- && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()
- {
- map.insert("upstream".into(), upstream);
+ {
+ let _span = Span::new("var_remote");
+ if let Ok(remote) = ctx.repo.primary_remote() {
+ map.insert("remote".into(), remote.to_string());
+ // Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)
+ if let Some(url) = ctx.repo.remote_url(&remote) {
+ map.insert("remote_url".into(), url);
+ }
+ if let Some(branch) = ctx.branch
+ && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()
+ {
+ map.insert("upstream".into(), upstream);
+ }
}
}
@@ -424,10 +437,12 @@ fn run_concurrent_group(
announce_command(cmd, &fg_step.announce);
}
- let expanded: Vec<String> = cmds
- .iter()
- .map(|cmd| resolve_command_str(cmd, repo))
- .collect::<Result<_>>()?;
+ let expanded: Vec<String> = {
+ let _span = Span::new("template_render");
+ cmds.iter()
+ .map(|cmd| 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.
@@ -484,7 +499,10 @@ fn run_one_command(
let directives = &fg_step.directives;
announce_command(cmd, &fg_step.announce);
- let command_str = resolve_command_str(cmd, repo)?;
+ let command_str = {
+ let _span = Span::new("template_render");
+ resolve_command_str(cmd, repo)?
+ };
// Hooks get a documented JSON context on stdin; aliases inherit stdin so
// interactive children (e.g. `wt switch`'s picker) keep their controlling
@@ -494,14 +512,21 @@ fn run_one_command(
} else {
None
};
- let result = execute_shell_command(
- wt_path,
- &command_str,
- stdin_json,
- cmd.log_label.as_deref(),
- directives.clone(),
- fg_step.redirect_stdout_to_stderr,
- );
+ // `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,
+ )
+ };
match result {
Ok(()) => Ok(()),
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 373909304..04e652fdc 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -511,6 +511,11 @@ impl Repository {
return Ok(cached.clone());
}
+ // Span attribution for the cold path: the rev-parse subprocess gets
+ // its own `[wt-trace] cmd=` record from `Cmd::run`, and this span
+ // captures the surrounding canonicalize + cache-insert work too.
+ let _span = crate::trace::Span::new("resolve_git_common_dir");
+
let output = Cmd::new("git")
.args(["rev-parse", "--git-common-dir"])
.current_dir(discovery_path)
diff --git a/src/main.rs b/src/main.rs
index b441db191..9d16c817c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1054,11 +1054,11 @@ fn init_logging(verbose_level: u8) {
// capped). At -vv, `.git/wt/logs/trace.log` mirrors stderr and
// `.git/wt/logs/output.log` receives the uncapped subprocess bodies
// routed via `shell_exec::SUBPROCESS_FULL_TARGET`.
- if verbose_level >= 2 {
- log_files::init();
- }
-
- // Set global verbosity level for styled verbose output
+ //
+ // env_logger registers the logger via `.init()` at the bottom of this
+ // function. `log_files::init()` runs after that so the
+ // `Repository::current()` it triggers (cold cache: 4ms `git rev-parse
+ // --git-common-dir`) is visible in `[wt-trace]` output.
output::set_verbosity(verbose_level);
let mut builder = match verbose_level {
@@ -1121,6 +1121,13 @@ fn init_logging(verbose_level: u8) {
}
})
.init();
+
+ // Open per-file log sinks AFTER env_logger is registered so the
+ // `Repository::current()` rev-parse fired by `try_create` is captured
+ // in the trace.
+ if verbose_level >= 2 {
+ log_files::init();
+ }
}
fn handle_merge_command(args: MergeArgs, yes: bool) -> anyhow::Result<()> {
@@ -1244,6 +1251,12 @@ fn main() {
// from a parent `git` (e.g. when invoked via `git wt ...` with
// `alias.wt = "!wt"`) against a stable reference, rather than against
// each child command's `current_dir`. See issue #1914.
+ //
+ // `[wt-trace]` spans before the logger is registered would silently
+ // no-op, so the prelude up to `init_logging` — `init_startup_cwd`,
+ // `init_rayon_thread_pool`, `force_color_output`, `parse_cli` — isn't
+ // attributed. If startup itself becomes the suspect, capture it as
+ // wall-clock minus the sum of post-init spans.
worktrunk::shell_exec::init_startup_cwd();
init_rayon_thread_pool();
@@ -1267,9 +1280,22 @@ fn main() {
// existing destructure pattern.
apply_global_options(directory.clone(), config);
+ // `init_logging` registers the logger. Run it before `init_command_log`
+ // so the latter's `Repository::current()` → `git rev-parse
+ // --git-common-dir` subprocess is visible in `[wt-trace]` output. With
+ // the previous order the rev-parse fired before any logger was
+ // registered, leaving a 4ms hole in the trace where the subprocess
+ // actually ran. Same reason `init_logging` itself reorders to
+ // register env_logger before opening per-file log sinks.
+ {
+ let _span = worktrunk::trace::Span::new("init_logging");
+ init_logging(verbose);
+ }
let command_line = std::env::args().collect::<Vec<_>>().join(" ");
- init_command_log(&command_line);
- init_logging(verbose);
+ {
+ let _span = worktrunk::trace::Span::new("init_command_log");
+ init_command_log(&command_line);
+ }
let Some(command) = command else {
print_help_to_stderr();
diff --git a/src/trace/chrome.rs b/src/trace/chrome.rs
index ba4423175..081bbae2d 100644
--- a/src/trace/chrome.rs
+++ b/src/trace/chrome.rs
@@ -5,7 +5,7 @@
//!
//! # Event Types
//!
-//! - **Complete events** (`ph: "X"`): Command executions with duration
+//! - **Complete events** (`ph: "X"`): Command executions and in-process spans, both with duration
//! - **Instant events** (`ph: "I"`): Milestones without duration (e.g., "Showed skeleton")
//!
//! See [`crate::trace`] for the capture pipeline and SQL query examples.
@@ -84,8 +84,9 @@ struct ChromeTrace {
///
/// # Event Types
///
-/// - Command entries become Complete events (`"ph": "X"`) with duration
-/// - Instant entries become Instant events (`"ph": "I"`) with global scope
+/// - Command entries become Complete events (`"ph": "X"`) with duration; categorized as `git`/`network`/none.
+/// - Span entries become Complete events with category `wt` so subprocess and in-process work render distinctly.
+/// - Instant entries become Instant events (`"ph": "I"`) with global scope.
pub fn to_chrome_trace(entries: &[TraceEntry]) -> String {
let trace_events: Vec<TraceEvent> = entries
.iter()
@@ -139,6 +140,21 @@ pub fn to_chrome_trace(entries: &[TraceEntry]) -> String {
}),
}
}
+ TraceEntryKind::Span { name, duration } => TraceEvent {
+ name: name.clone(),
+ ph: "X", // Complete event (has duration)
+ ts,
+ dur: Some(duration.as_micros() as u64),
+ s: None,
+ pid: 1,
+ tid,
+ cat: Some("wt".to_string()),
+ args: Some(TraceEventArgs {
+ context: entry.context.clone(),
+ success: true,
+ duration_ms: Some(duration.as_secs_f64() * 1000.0),
+ }),
+ },
}
})
.collect();
@@ -192,6 +208,23 @@ mod tests {
}
}
+ fn make_span_entry(
+ name: &str,
+ duration_us: u64,
+ start_time_us: Option<u64>,
+ thread_id: Option<u64>,
+ ) -> TraceEntry {
+ TraceEntry {
+ context: None,
+ kind: TraceEntryKind::Span {
+ name: name.to_string(),
+ duration: Duration::from_micros(duration_us),
+ },
+ start_time_us,
+ thread_id,
+ }
+ }
+
#[test]
fn test_to_chrome_trace_with_timestamps() {
let entries = vec![
@@ -301,6 +334,26 @@ mod tests {
assert!(events[0]["args"]["duration_ms"].is_null());
}
+ #[test]
+ fn test_span_event() {
+ // 8000 µs (= 8 ms exactly) avoids float-precision noise in duration_ms.
+ let entries = vec![make_span_entry("config_load", 8000, Some(1000000), Some(1))];
+
+ let json = to_chrome_trace(&entries);
+ let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
+ let events = parsed["traceEvents"].as_array().unwrap();
+
+ assert_eq!(events.len(), 1);
+ assert_eq!(events[0]["name"], "config_load");
+ assert_eq!(events[0]["ph"], "X"); // Complete event
+ assert_eq!(events[0]["ts"], 1000000);
+ assert_eq!(events[0]["dur"], 8000);
+ assert_eq!(events[0]["cat"], "wt");
+ assert!(events[0]["s"].is_null());
+ assert_eq!(events[0]["args"]["success"], true);
+ assert_eq!(events[0]["args"]["duration_ms"], 8.0);
+ }
+
#[test]
fn test_mixed_events() {
let entries = vec![
diff --git a/src/trace/emit.rs b/src/trace/emit.rs
index 4cd81873f..549d24820 100644
--- a/src/trace/emit.rs
+++ b/src/trace/emit.rs
@@ -13,8 +13,15 @@
//! [wt-trace] ts=1234567 tid=3 cmd="gh pr list" dur_us=45200 ok=false
//! [wt-trace] ts=1234567 tid=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."
//! [wt-trace] ts=1234567 tid=3 event="Showed skeleton"
+//! [wt-trace] ts=1234567 tid=3 span="build_hook_context" dur_us=8200
//! ```
//!
+//! In-process spans (everything that isn't a subprocess) use [`Span`], an
+//! RAII guard that captures `ts` at construction and emits the completed
+//! record on drop with the elapsed duration. Use it to attribute time spent
+//! in code paths subprocess records can't see (config load, repo open,
+//! template render).
+//!
//! Records are emitted at `log::debug!`, so `-vv` or `RUST_LOG=debug` makes
//! them visible. Subprocess stdout/stderr continuations are emitted via
//! separate log targets: the full output goes to `output.log`, and a bounded
@@ -123,3 +130,57 @@ pub fn instant(event: &str) {
event
);
}
+
+/// Emit a completed in-process span (a named region of code that ran).
+///
+/// Spans are the in-process counterpart to `command_completed`: subprocess
+/// records cover work in child processes; spans cover everything between and
+/// around them (config load, repo open, template render, etc.).
+pub fn span_completed(name: &str, ts: u64, tid: u64, dur_us: u64) {
+ log::debug!(
+ r#"[wt-trace] ts={} tid={} span="{}" dur_us={}"#,
+ ts,
+ tid,
+ name,
+ dur_us
+ );
+}
+
+/// RAII guard that times its enclosing scope and emits a span record on drop.
+///
+/// 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.
+///
+/// The `log_enabled!` check happens on drop, not construction. A span
+/// constructed before `init_logging` (e.g. wrapping the logger init itself)
+/// still fires correctly as long as the logger is up by the time the span
+/// 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,
+ start_ts_us: u64,
+ start: Instant,
+}
+
+impl Span {
+ pub fn new(name: &'static str) -> Self {
+ Self {
+ name,
+ start_ts_us: now_us(),
+ start: Instant::now(),
+ }
+ }
+}
+
+impl Drop for Span {
+ fn drop(&mut self) {
+ if !log::log_enabled!(log::Level::Debug) {
+ return;
+ }
+ let dur_us = self.start.elapsed().as_micros() as u64;
+ span_completed(self.name, self.start_ts_us, thread_id(), dur_us);
+ }
+}
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index 50bf26389..27007651b 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -38,4 +38,5 @@ pub mod parse;
// Re-export main types for convenience
pub use chrome::to_chrome_trace;
+pub use emit::Span;
pub use parse::{TraceEntry, TraceEntryKind, TraceResult, parse_lines};
diff --git a/src/trace/parse.rs b/src/trace/parse.rs
index b6ab9686d..bd063f0db 100644
--- a/src/trace/parse.rs
+++ b/src/trace/parse.rs
@@ -20,7 +20,7 @@
use std::time::Duration;
-/// The kind of trace entry: command execution or instant event.
+/// The kind of trace entry: command execution, instant event, or in-process span.
#[derive(Debug, Clone, PartialEq)]
pub enum TraceEntryKind {
/// A command execution with duration and result
@@ -37,6 +37,15 @@ pub enum TraceEntryKind {
/// Event name (e.g., "Showed skeleton")
name: String,
},
+ /// An in-process span — a named region of code with a duration.
+ /// Distinct from `Command` so consumers can render subprocess vs.
+ /// in-process work differently.
+ Span {
+ /// Span name (e.g., "build_hook_context")
+ name: String,
+ /// Span duration
+ duration: Duration,
+ },
}
/// A parsed trace entry from a wt-trace log line.
@@ -63,13 +72,15 @@ pub enum TraceResult {
impl TraceEntry {
/// Returns true if the command succeeded.
- /// Instant events always return true.
+ ///
+ /// Instant events and spans always return true — they record completion of
+ /// in-process work, not subprocess success/failure.
pub fn is_success(&self) -> bool {
match &self.kind {
TraceEntryKind::Command { result, .. } => {
matches!(result, TraceResult::Completed { success: true })
}
- TraceEntryKind::Instant { .. } => true,
+ TraceEntryKind::Instant { .. } | TraceEntryKind::Span { .. } => true,
}
}
}
@@ -79,9 +90,10 @@ impl TraceEntry {
/// Returns `None` if the line doesn't match the expected format.
/// The `[wt-trace]` marker can appear anywhere in the line (to handle log prefixes).
///
-/// Supports two entry types:
+/// Supports three entry types:
/// - Command events: `cmd="..." dur_us=... ok=true/false` or `err="..."`
/// - Instant events: `event="..."`
+/// - Span events: `span="..." dur_us=...`
fn parse_line(line: &str) -> Option<TraceEntry> {
// Find the [wt-trace] marker anywhere in the line
let marker = "[wt-trace] ";
@@ -92,6 +104,7 @@ fn parse_line(line: &str) -> Option<TraceEntry> {
let mut context = None;
let mut command = None;
let mut event = None;
+ let mut span = None;
let mut duration = None;
let mut result = None;
let mut start_time_us = None;
@@ -130,6 +143,7 @@ fn parse_line(line: &str) -> Option<TraceEntry> {
"context" => context = Some(value.to_string()),
"cmd" => command = Some(value.to_string()),
"event" => event = Some(value.to_string()),
+ "span" => span = Some(value.to_string()),
"dur_us" => {
let us: u64 = value.parse().ok()?;
duration = Some(Duration::from_micros(us));
@@ -157,6 +171,12 @@ fn parse_line(line: &str) -> Option<TraceEntry> {
let kind = if let Some(event_name) = event {
// Instant event
TraceEntryKind::Instant { name: event_name }
+ } else if let Some(span_name) = span {
+ // In-process span - requires span and dur
+ TraceEntryKind::Span {
+ name: span_name,
+ duration: duration?,
+ }
} else {
// Command event - requires cmd, dur, and result
TraceEntryKind::Command {
@@ -384,6 +404,37 @@ more noise
assert_eq!(entry.thread_id, None);
}
+ // ========================================================================
+ // Span event tests
+ // ========================================================================
+
+ #[test]
+ fn test_parse_span_event() {
+ let line = r#"[wt-trace] ts=1736600000000000 tid=3 span="config_load" dur_us=8200"#;
+ let entry = parse_line(line).unwrap();
+
+ assert_eq!(entry.start_time_us, Some(1736600000000000));
+ assert_eq!(entry.thread_id, Some(3));
+ let TraceEntryKind::Span { name, duration } = &entry.kind else {
+ panic!("expected span event, got {:?}", entry.kind);
+ };
+ assert_eq!(name, "config_load");
+ assert_eq!(*duration, Duration::from_micros(8200));
+ assert!(entry.is_success());
+ }
+
+ #[test]
+ fn test_parse_span_minimal() {
+ let line = r#"[wt-trace] span="repo_open" dur_us=1500"#;
+ let entry = parse_line(line).unwrap();
+
+ let TraceEntryKind::Span { name, duration } = &entry.kind else {
+ panic!("expected span");
+ };
+ assert_eq!(name, "repo_open");
+ assert_eq!(*duration, Duration::from_micros(1500));
+ }
+
#[test]
fn test_parse_lines_mixed() {
let input = r#"