Skip to content

perf(alias): scope template-context build to vars the body references - #2556

Merged
max-sixty merged 4 commits into
mainfrom
alias-speed
May 3, 2026
Merged

max-sixty merged 4 commits into
mainfrom
alias-speed

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Summary

Stub-alias dispatch (wt <alias> invoking a body that just echos) was paying ~21 ms of context-build overhead — git subprocesses for default_branch, commit, remote, primary_worktree, plus serial UserConfig + ProjectConfig loads — even when the body never substituted any of those variables. This branch trims the work to what the body actually references.

  • build_hook_context: only the four blocks that shell out (default_branch, primary_worktree, commit/short_commit, remote/remote_url/upstream) honor a referenced: Option<&BTreeSet<String>> gate. Hooks pass None (full JSON-on-stdin contract preserved); aliases pass the body's referenced-var set, extended via alias_context_filter for implicit deps (args always, branch when vars is referenced).
  • LoadedConfigs<'r>: canonical borrowed bundle that warms UserConfig and ProjectConfig in a thread::scope and returns references from the cache. Replaces the prior asymmetric mix of cached-user / inline-project loads.
  • Cheap context vars unconditional: repo, branch, worktree_name, paths, owner, cwd, and extra_vars are always populated — gating them saved no work and turned the verbose table's (unused) label into noise. The label now fires precisely when the gate skipped real work.
  • Signal race: shell_exec's post-wait SIGINT/SIGTERM gate now requires !status.success(), so a child that exited cleanly during the wait window isn't misreported as signal-killed.

Stub-alias dispatch drops from ~21 ms to ~14 ms warm. Cold path (first call after fresh clone) is now equal to warm — no longer pays for default-branch detection.

Test plan

  • cargo run -- hook pre-merge --yes (3431 tests, lints, doc, snapshots)
  • Snapshot diffs for verbose alias output reviewed and accepted
  • Hook integration tests (171) pass — full context preserved via referenced = None
  • cargo bench --bench alias confirms warm-path improvement

🤖 Generated with Claude Code

max-sixty and others added 4 commits May 3, 2026 11:30
`build_hook_context` gains an optional `referenced` set. When `Some`, each
insert is gated on membership: vars the alias body doesn't reference are not
computed (no `default_branch()` cold detection, no `branch().upstream()`
lookup, no commit `rev-parse`). Aliases pass their `referenced_vars_for_config`
through a shared `alias_context_filter` helper that pins down two implicit
deps — `args` is always available, and `branch` must stay reachable when the
body uses `{{ vars.X }}` (lazy git-config lookup keys on it). Hooks pass
`None` to preserve the JSON-on-stdin contract: children may consume keys via
`jq` that aren't in the inline template.

The verbose `-v` table mirrors the filter — referenced rows render
`name = value`, unreferenced rows render dim `(unused)`. `(unset)` stays as
the marker for referenced-but-not-configured (e.g. `upstream`).

Bench (`cargo bench --bench alias`, 30 samples / 10 s):

  variant         baseline   this    delta
  warm/1          20.99      13.70   -35%
  cold/1          22.75      13.72   -40%
  warm/100        21.44      13.69   -36%
  cold/100        26.87      13.80   -49%
  with_vars/warm  20.03      18.21   -9%
  with_vars/cold  22.45      21.64   -4%

Bundled adjacent fixes from the same review pass:

- `Cmd::stream` no longer treats a signal that arrives between `child.wait()`
  returning success and `handle.close()` as a kill — gate `seen_signal` on
  `!status.success()` so the contract on `signal.is_some()` ("this child was
  killed by the signal") holds. Pipeline loops keying on `interrupt_exit_code`
  no longer break on a benign late signal.
- `LoadedConfigs::load` collapses from three threads to two: project-config
  load and `project_identifier` warm share one thread (same Repository,
  same wall pole). Drops one spawn/join + one Repository clone.
- `LoadedConfigs<'r>` now borrows from the per-Repository cache. New
  `Repository::project_config(&self) -> Result<&Option<ProjectConfig>>`
  mirrors the existing `user_config() -> &UserConfig` accessor;
  `load_project_config` becomes a one-line clone wrapper. Both fields go
  through the same caching path — the second loader path inside the bundle
  is gone, no asymmetry to document. `UserConfig` derives `Clone` so the
  two genuinely-owned-config sites (`CommandEnv`, picker's bare-repo
  worktree-path mutation) clone from the cache instead of re-reading.
  `run_alias` switches `repo: Repository` → `&Repository` and
  `user_config: UserConfig` → `&UserConfig` (it never moved either).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts:
#	src/shell_exec.rs
- `Repository::project_config()` returns `Option<&ProjectConfig>` instead of
  `&Option<ProjectConfig>` — Rust idiom; removes `.as_ref()` from the lone
  call site in `LoadedConfigs::load`.
- `format_alias_variables` no longer open-codes the alignment + render loop;
  `format_variables_table` gains the optional `referenced` parameter and
  owns the dim `(unused)` rendering. One canonical formatter for both hook
  and alias scopes.
- `alias_context_filter` takes `BTreeSet<String>` by value instead of by
  reference, dropping the input clone (the sole caller owns the set).
- `try_alias` / `step_alias` thread the `referenced` set they already
  computed for arg parsing into `run_alias`, removing a duplicate
  `referenced_vars_for_entry` call (one minijinja parse + walk per template
  per dispatch).
- Trim over-narrated comments at `CommandEnv::for_action_branchless` and
  the picker's bare-repo fixup site.

No behavior change. Cumulative bench numbers held at ~17 ms warm/1 (the
+3 ms vs. iter-4's 13.7 ms is the merged trace-instrumentation change in
`#2554`, not these cleanups — `build_hook_context` is still 4 µs, the
parallel pole is still ~6 ms).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`build_hook_context`'s `want()` filter now applies only to the four
blocks that actually shell out (`default_branch`, `primary_worktree`,
`commit`/`short_commit`, `remote`/`remote_url`/`upstream`). Cheap vars
(`repo`, `branch`, `worktree_name`, `repo_path`/`worktree_path` and
deprecated aliases, `owner`, `cwd`, `extra_vars`) are populated
unconditionally — gating them saved no work and turned the verbose
table's `(unused)` label into noise on every cheap row.

`format_variables_table` now renders `(unused)` only when the var is
absent from `ctx` *and* not in `referenced`. The label fires precisely
when the gate skipped real work; cheap vars always show their value;
referenced-but-unsupplied vars still show `(unset)`.

Also folds in rustfmt drift on `run_alias` calls from f0f14a1 (the
seventh argument pushed past the column limit) and an intra-doc link
from a public to a private item that had been silently failing
`cargo doc`.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit 2a8db41 into main May 3, 2026
27 checks passed
@max-sixty
max-sixty deleted the alias-speed branch May 3, 2026 19:32
max-sixty added a commit that referenced this pull request May 3, 2026
Merge main into the branch, resolving conflicts in `step_commands.rs` and
`main.rs` from the new `step commit --dry-run` and `step squash --dry-run`
features (#2557 area). The JSON `--show-prompt` guard now also rejects
`--dry-run + --format=json` for the same reason — both emit raw text.

Main also changed `LoadedConfigs` to hold borrowed references (PR #2556),
which is what caused the prior CI compile failure that was invisible
locally. Drop the now-unnecessary `.as_ref()` calls in
`handle_hook_show` (`configs.project` is already `Option<&ProjectConfig>`).

Address tend-bot review feedback on the JSON additions:

- **Display abbreviation**: `commit_staged_changes` and `handle_squash` now
  call `git rev-parse --short HEAD` for the success-line hash (honors
  `core.abbrev` and auto-extends ambiguous prefixes), keeping the full
  40-char SHA only for the JSON payload. Previously a fixed 7-char slice
  silently lost both behaviors.
- **`--format` flag descriptions**: each new `--format` flag now includes
  a one-liner naming the JSON shape, matching the pattern set by
  `wt switch`/`wt remove`/`wt merge`.
- **Missing test**: add `test_step_push_no_ff_json` exercising the
  `merge_commit` outcome and the new `merge_sha` field.

Co-Authored-By: Claude <[email protected]>
@max-sixty max-sixty mentioned this pull request May 5, 2026
2 of 3 tasks
max-sixty added a commit that referenced this pull request May 5, 2026
## Summary
Release v0.48.0. See
[CHANGELOG.md](https://github.com/max-sixty/worktrunk/blob/release/CHANGELOG.md)
for the full notes.

Highlights:
- `--format=json` extends to seven step + hook commands (#2560)
- `wt step commit` / `wt step squash` gain `--dry-run` (#2557)
- New `dirname` / `basename` template filters (#2592, #2605)
- New `[remove] delete-branch` config option (#2589)
- `wt-perf timeline` subcommand (#2558)
- Faster `wt list` on dirty worktrees (#2602) and faster alias dispatch
(#2556, #2573)
- Short-SHA display honors `core.abbrev` (#2576)
- Cleaner `wt config show` shell-integration section for new users

## Test plan
- [x] `cargo run -- hook pre-merge --yes` (3497 tests, lints clean)
- [x] `cargo semver-checks check-release -p worktrunk` consulted; minor
bump confirmed
- [ ] CI green
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants