Repository navigation
Add trace.jsonl structured-event sink and migrate logging to native tracing - #3232
Conversation
Write `trace.jsonl` alongside `trace.log` at `-vv`: one JSON object per
line, machine-first for agents and `jq`. A single `JsonFieldVisitor`
serializes whatever typed fields an event carries, so adding detail at a
call site needs no formatter change. A `[wt-trace]` record comes through
rich (`cmd`, `seq`, `dur_us`, ...); a free-form line falls through as
`{"message":...}` until its call site is given fields. The layer admits
every event except the two subprocess-output targets.
Migrate a first batch of 12 `log::` sites to structured `tracing::`
(ci_platform, cache, remove), keeping each message verbatim so stderr
and snapshots are unchanged while adding queryable fields.
Tighten `is_command_log_file` to exact names (`commands.jsonl`,
`commands.jsonl.old`) so `trace.jsonl` is not misfiled as a command
audit log, and add it to the diagnostic bundle file list.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Convert every remaining `log::{trace,debug,info,warn,error}!` emit site
(85 across 31 files) to native `tracing::`, adding structured fields
while keeping each message verbatim so stderr output and snapshots are
unchanged. Worktrunk's own code is now on one logging API; the
`LogTracer` bridge stays because dependencies (`mio`, `ignore`,
`image`/`skim`) still emit through `log`.
Fix a latent underflow panic the cutover exposed in `CiStatus::detect`:
its cache debug used a raw `now_secs - cached.checked_at`. Under
`log::debug!` that never evaluated below the level cap; a `tracing::debug!`
evaluates its args at every verbosity (the layered subscriber does not
short-circuit Debug callsites), so under the test harness's pinned
`WORKTRUNK_TEST_EPOCH` the subtraction underflowed. Use `saturating_sub`,
matching `is_valid` — a future-dated cache means age 0, not a panic.
Keep the `log::log_enabled!` deep-logging guard in `shell_exec::log_output`
rather than `tracing::enabled!`: the absent (`None`) file layers report
`enabled() == true`, so `tracing::enabled!` never short-circuits and would
format every command's output even at `-v0`.
Rewrite `test_select_binding_window_logs_at_debug` to force lazy-arg
evaluation via a DEBUG-level `with_default` subscriber, since a
`tracing::` event ignores `log::set_max_level`.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # src/commands/picker/mod.rs
The always-present stderr layer filters with `EnvFilter.and(filter_fn)`, and the target `filter_fn` carried no `max_level_hint`. `And::max_level_hint` is `cmp::min`, and a `None` hint sorts below any `Some`, so the AND collapsed to `None`. That propagated through the layered subscriber's `pick_level_hint` to the global `LevelFilter::current()`, pinning it at TRACE. Every `tracing::debug!` then built its format args at every verbosity, even at `-v0` where nothing records them (the cause of the CI-status underflow panic and a perf regression from the log:: to tracing:: migration). Tag each target filter with an honest TRACE `max_level_hint` (it bounds by target, not level) via a `target_filter` helper, so the EnvFilter's level bound survives the AND. The global hint is now OFF at `-v0`, INFO at `-v1`, TRACE at `-vv`, and the macros short-circuit below the active verbosity as `log::debug!` did. Add a regression test locking the AND-collapse mechanism; correct the now-stale comments in logging.rs, ci_status, and shell_exec. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
worktrunk-bot
left a comment
There was a problem hiding this comment.
The logging migration itself is clean and reads well — the level-hint fix (target_filter tagging each predicate with an honest TRACE hint so the EnvFilter bound survives Filter::and's cmp::min) is subtle but correctly reasoned and has a focused regression test, the generic JsonFieldVisitor/event_json serializer is a nice design (serde_json owning all escaping, ts/tid filled only when the event omits them), and the now_secs.saturating_sub(cached.checked_at) change is a real latent-panic fix. The log:: → tracing:: migration is mechanical and consistent. No correctness concerns.
Holding off on approving only because codecov/patch is red. Almost all of the uncovered patch lines are the migrated tracing::debug!/warn!/error! statements themselves — error/warn paths the suite doesn't drive, and the coverage run doesn't execute at -vv — so per-line coverage of those is neither feasible nor worth chasing.
The one genuinely closeable gap is in the new functional code: JsonFieldVisitor::record_i64 (src/logging.rs lines 357–359) is the only visitor method event_json_serializes_structured_and_freeform_events never reaches — every field in the test events is u64/bool/str. Adding one i64 field exercises it and clears the only non-log-line miss. Inline suggestions below.
Resolves a conflict in src/commands/statusline.rs: main (#3229) added the expected-lockout severity coloring (the `lockout` var, the extended debug message, and the `lockout_cost` arg) to the same per-window debug line this branch migrated from `log::debug!` to `tracing::debug!`. Took main's lockout feature with the `tracing::` macro. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a negative i64 field to the event_json round-trip test, the one JsonFieldVisitor method the suite never reached (every other field is u64/bool/str). Closes the lone genuinely-coverable codecov/patch gap the auto-reviewer flagged at src/logging.rs:357-359. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
worktrunk-bot
left a comment
There was a problem hiding this comment.
The new severity axis (expected_lockout + colorize_pace/lockout_cost) is a clean addition. Splitting the one Bayes update into posterior_lambda so p_over (the show gate) and expected_lockout (the colour axis) can't drift is the right factoring, and the Gauss–Hermite quadrature is sound: per-node lockout is bounded by 1 − t, the 7 weights sum to √π so the normalised average stays in [0, 1], and the negative-λ clamp keeps the headroom/λ term from blowing up on the Gaussian's lower tail. The duration-weighted √(window/5h) cost with the 5h anchor at weight 1 keeps the existing thresholds and snapshots intact while letting a week's worth of forfeited time outrank the same fraction of five hours. Tests cover bounds, monotonicity, the marginal-cross-stays-small case, tier deepening, and the cross-window weighting — good coverage of the math.
The earlier record_i64 gap is closed (the negative exit field now exercises it), and the new feature is fully covered: src/commands/statusline.rs and src/logging.rs both report 100% patch coverage.
Not approving only because codecov/patch is still red — but every remaining uncovered patch line is a migrated tracing::{debug,warn,error}! statement on an error/warn/debug path the suite doesn't drive (cache-serialize failure, fsmonitor daemon start, branch-delete fallbacks, CI-status fetch warnings, pager fallbacks). The coverage run doesn't execute at -vv, so per-line coverage of those isn't feasible and isn't worth chasing. No functional patch line is uncovered. Per CLAUDE.md's codecov gate, the merge call over that residual red is yours.
…3297) At `-vv`, worktrunk's `trace.log` carried machine-parseable `[wt-trace] ts=… tid=… seq=… cmd="git status" dur_us=12300 ok=true` lines *alongside* a `$ git status [ctx]` start echo — so every command appeared twice in two inconsistent renderings, and the human file was cluttered with `key=value` machine fields. The root cause: `trace.log` was doing double duty as both the human artifact and the machine-parsed source, even though `trace.jsonl` (added in #3232) already carries the same fields losslessly and nothing read it as input. This decouples the two. `trace.log` + stderr become purely human; `trace.jsonl` becomes the sole machine format. ```text # BEFORE — two inconsistent renderings of one command [h] $ git rev-parse --show-toplevel [worktrunk.rev-parse-dedup] [h] [wt-trace] ts=11593 tid=8 seq=5 context=worktrunk.rev-parse-dedup cmd="git rev-parse --show-toplevel" dur_us=6101 ok=true # AFTER — start ($) and finish (✓) pair, one `cmd [ctx]` rendering, no clutter [h] $ git rev-parse --show-toplevel [worktrunk.rev-parse-dedup] [h] ✓ git rev-parse --show-toplevel [worktrunk.rev-parse-dedup] 6.1ms ``` Commands render `$ …` (start) → `✓`/`✗ … dur` (finish), in-process spans `◷ name dur`, milestones `· event` — the leading glyph names the line type at a glance. ## What a reviewer needs - **`src/trace/parse.rs`** — rewritten to parse `trace.jsonl` (one JSON object per line) via a `kind`-dispatch (`cmd_completed`/`cmd_errored`/`instant`/`span`), skipping non-records (`{"message":…}` logs, `$ cmd` echoes, non-JSON). Cleaner than inferring kind from which fields are present. - **`src/logging.rs`** — `format_wt_trace` now emits the human line; `style_stderr_line` bolds the command for `$`/`✓`/`✗` lines so a start and its finish read as a pair. The machine fields (`ts`/`tid`/`seq`) live only in `trace.jsonl` (via the separate JSON visitor). - **Consumers repointed at `trace.jsonl`**: `wt config state logs profile`, the `wt-perf` helper (`timeline` now runs `wt -vv` and reads the file, located via `git rev-parse --git-common-dir`), and the `diagnostic.md` profile section (while still inlining the human `trace.log`). - **Docs** — help text, the FAQ file inventory (added `trace.jsonl`), and the `[wt-trace]`-grammar descriptions across `emit.rs`/`log_files.rs`/`benches/CLAUDE.md` updated. One behavior note: `wt-perf timeline` now writes trace files to the repo's `.git/wt/logs/` (a side effect of `-vv`) where the old `RUST_LOG=debug` path didn't — expected for a `-vv`-based perf helper. ## Testing Well-covered: parser (14 unit tests), renderer + stderr styling (8), `logs profile`/`diagnostic`/`switch`/`completion` integration tests migrated to JSON fixtures, plus a `wt_target_dir` unit test for the wt-perf `-C` resolution. Verified `logs profile`, `wt-perf timeline` (text + `--chrome`), and `cache-check` end-to-end on a real `-vv` capture. An independent review pass found no correctness issues; its findings (a missed doc, two wt-perf robustness fixes) are folded in. > _This was written by Claude Code on behalf of max_ Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
This branch reworks
wt's deep logging (-vv) around nativetracing, in three steps.trace.jsonl sink
Adds a structured-event sink that writes one JSON object per event to
wt/logs/trace.jsonl, alongside the existingtrace.logandsubprocess.log. The serializer is generic over an event's typed fields, so a[wt-trace]record serializes its full grammar (kind,seq,cmd,dur_us, ...) while a free-form message serializes as{"message": ...}. serde_json owns all escaping, so embedded quotes and control bytes round-trip losslessly where thekey="value"text grammar would truncate.Migrate
log::to nativetracing::Moves all of worktrunk's own emit sites from
log::{trace,debug,info,warn,error}!totracing::, attaching structured fields (branch = %b,error = %e, ...) so they land in trace.jsonl as queryable keys rather than opaque messages. Thelogtotracingbridge stays for transitive dependencies (mio,ignore,image/skim, ...) that still emit throughlog.Restore the macro short-circuit
The migration exposed a latent level-hint bug. The always-present stderr layer filters with
EnvFilter.and(filter_fn), and the targetfilter_fnreported nomax_level_hint.And::max_level_hintiscmp::min, where aNonehint sorts below anySome, so the AND collapsed toNone, which propagated to the globalLevelFilter::current()and pinned it at TRACE. Everytracing::debug!then built its format args at every verbosity, even-v0(this underflow-panicked one CI-status debug line). Tagging each target filter with an honest TRACE hint lets the EnvFilter's level bound survive the AND, so the macros short-circuit below the active verbosity aslog::debug!did.Testing
The structured serializers (
event_json,format_wt_trace, the field visitors) and the level-hint mechanism have unit tests; the migrated emit sites run under the existing integration suite. The-vvfile routing is covered by the trace-format integration tests.