Skip to content

perf(#660): take 20 subprocesses off the SessionStart foreground path - #696

Merged
fdaviddpt merged 7 commits into
mainfrom
perf/660-foreground-path
Sep 15, 2026
Merged

fdaviddpt merged 7 commits into
mainfrom
perf/660-foreground-path

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Part of #660, which stays open: this cuts the hook's own cost, it does not
close the two questions listed at the bottom. The diagnostic work behind it is
#689, which stays unmerged.

What #660 turned out to be

The headline number in that issue -- 23.5s, then 38.5s, then 188s -- was
environmental and has been withdrawn by the reporter: their machine had
129 hours of uptime and a 23.2 GB kernel paged-pool leak. After a reboot, same
box, same plugin version, the hook measured 2.19s p50 with a fork cost of 21ms
idle. There was no 25-second bug in this code to find.

What remains real is smaller and worth fixing anyway: the hook forks a lot, a
fork on Git Bash costs 10-50x what it costs on Linux, and the failure that
actually breaks a session is the VS Code extension's hard 60,000ms
initialisation ceiling. Halving the hook is what keeps a slow machine on the
right side of that line.

What this does

The hook's only hard obligation is the memory context on stdout. Everything
else either moved off the foreground path or stopped forking.

Deferred into a detached phase that runs after the context is emitted:

  • previous-session resolution, the recovery decision and the capture-gap check
    (their only readers are a save that was already detached, and files
    user-prompt-hook.sh reads on the next prompt)
  • the slug record, the slug index and the case-divergence notice
  • publishing the start-context cache (work done purely for the next start)
  • the before_session_start dispatch, only when git_restore.enabled is
    false and nothing but the bundled script is registered. With the restore on,
    deferring it would render the store it was supposed to repair -- wrong
    memory, silently. A third-party hook there may emit context it expects
    injected, so its contract is kept literally.

Eliminated:

  • rendering a memory file under 16KB no longer forks cat
  • REMEMBER_ROOT no longer forks dirname
  • mkdir -p on an existing tmp/ is skipped

Foreground subprocesses per start: 49 -> 29.

A bug this found

dispatch named its capture files tmp/dispatch-stdout.$$, and $$ is the
shell's pid -- unchanged inside a subshell. Once before_session_start was
deferred, it and the foreground after_session_start dispatch shared those
paths, and the background one's end-of-loop rm -f deleted the capture the
foreground one was still writing. A plugin's injected context disappeared with
no error on any channel. Caught by an existing end-to-end test; fixed by
putting the event name in the path. $BASHPID would be more general and is
deliberately not used -- bash 4.0+, and macOS still ships 3.2.

A regression this PR introduced and then fixed

The render first replaced cat unconditionally with IFS= read -r -d ''.
Measured on the runner (the probe lives in #689's workflow):

size cat x5 read x5
4KB 0.103s 0.029s
256KB 0.086s 1.559s
4MB 0.094s 25.194s

Bash's read walks the delimiter byte by byte. Five forks traded for five
whole-file reads is a win on a toy store and a catastrophe on a real one, and
ubuntu-latest shows the same shape. The emitter now takes the size the render
already computed and picks: read under 16KB, cat over it -- threshold well
below the ~34KB crossover, because being wrong towards cat costs one fork and
being wrong towards read costs seconds.

Counting forks alone would have scored the first version a clean win. That
is the honest limit of the metric, and the reason the probe exists.

Measurements

CI, windows-latest, the hook traced directly (same runner image, no Claude Code
start in the way):

store before after
baseline, cold 2.32s 1.60s
year-old (6MB) 2.08s 1.45s
abandoned (20MB) 2.87s 2.16s

ubuntu-latest, hook durationMs median over 9 runs: 148ms -> 102ms (fresh
store), 290ms -> 181ms (20MB store).

End-to-end wall clock on a shared runner is not quoted as evidence: across
five runs of the same benchmark the no-plugin baseline alone moved 0.93-1.10s,
which is wider than the effect. That instrument could not resolve these
differences and is reported as such.

Behaviour changes

  • The capture-gap notice can arrive one prompt later than before. It describes
    a previous session; nothing else reads the file.
  • REMEMBER_DEFER=0 runs the deferred phase inline. It exists for tests that
    assert on one of those side effects; ten of them set it. A new test covers
    the default deferred path end to end, so the switch cannot become the only
    thing exercised -- records that silently stopped being written would
    otherwise read as a faster plugin.

Not included, deliberately

Deferring promo selection. It works and saves two jq forks, but it changes
when a promo appears, and the tests encoding #574's "marker only after
delivery", #596's agy suppression and #657's star-ask gate all have to be
rewritten around the new timing -- nine, across four files. That belongs in its
own reviewed change. An mtime-keyed cache of the two jq reads would get the
same saving with no behaviour change at all.

What is still open on #660

  • The reporter's healthy-host measurement (18.3s with the plugin against 6.8s
    without) does not reproduce on CI, where the plugin costs ~3.5s of wall
    against a 1.10s baseline. Most of their gap sits outside the hook and neither
    side has instrumented it.
  • The original 12.5s average came from a different reporter on ARM64, where
    x64 jq/git/coreutils under emulation multiply every fork. CI is AMD64 and
    cannot measure it.
  • windows-latest reports real-time protection off with both drives excluded,
    so no antivirus tax is measurable here at any effort.

Local suite: 2465 passed, 47 skipped.

[AI-generated]

Lane A, first slice. The SessionStart hook has exactly one hard obligation:
produce the injected context on stdout. Previous-session resolution, the
recovery decision and the capture-gap check are none of it -- their outputs
are a save-session.sh that was already detached, files under tmp/ whose only
reader is user-prompt-hook.sh on the NEXT prompt, and log lines.

They were on the foreground path anyway, and they are not cheap where it
hurts: previous_transcript sorts every past transcript (0.41s at 2000) and
the capture-gap grep reads the previous transcript to EOF when "tool_use" is
absent (0.197s on a 100MB one, windows-latest), inside a start whose whole
budget on Git Bash is a couple of seconds.

Moved into a detached brace group, not an extracted script: a subshell
inherits the functions and variables already defined above, so there is no
second copy to drift. Verified before the move that no variable assigned in
the span is read after it.

The redirections are load-bearing. At that point stdout is still the real
pipe Claude Code reads, so a child inheriting it would hold the write end
open and the client would not see EOF until the deferred work finished --
a start that no longer waits for the work but still blocks on it, looking
exactly like a change that did nothing. Same #646 fd inheritance, same fix.

Behaviour change, stated: the capture-gap notice can land one prompt later
than before. It is a fact about a previous session; nothing else reads it.

Tests are a pair, and both directions were verified by hand. The blocking
test holds grep open with a gate shim so it is deterministic rather than a
timing threshold, and it was watched failing against the unchanged hook.
The notice test is its positive control -- and the first draft of that
control never fired at all, because _store() ships its own newer previous
transcript and previous_transcript returned that instead; caught by running
the fixture against the unchanged hook, which is the only reason it is a
control and not decoration.

Co-Authored-By: Max <noreply>
(cherry picked from commit 70eb98e)
Second Lane A slice. Moves off the foreground path, same reasoning as the
first: the start's only obligation is the injected context.

- the three record writes (slug record, slug index, case-divergence notice).
  Verified mechanically that none of them assigns anything read later in the
  hook; their readers are user-prompt-hook.sh and /remember:doctor.
- publishing the start-context cache: four forks (mkdir, mktemp, two mv)
  spent entirely on making the NEXT start fast, after this one has already
  rendered and emitted.

The deferred block is now a function, because deferring the records broke ten
existing tests that read a record file the instant the hook exits. The honest
options were to weaken those assertions into polls or to leave the work on the
hot path; REMEMBER_DEFER=0 runs the phase inline instead and keeps both the
assertion and the speed. Those ten tests set it, and a new test covers the
DEFAULT deferred path end to end, so the switch cannot become the only thing
ever exercised -- records that silently stop being written would otherwise
read as a faster plugin.

Measured on the foreground path with a phase label in PS4, because a pid split
cannot tell a deferred child from a command substitution: 49 synchronous forks
before this slice, 16 of them the irreducible core (config flatten, path and
slug resolution, the render, stdout).

Co-Authored-By: Max <noreply>
(cherry picked from commit 58c7eb3)
… it exposed

Third Lane A slice, plus the bug it found.

The dispatch is deferred when BOTH hold: git_restore.enabled is not true, and
nothing but the bundled 50-git-restore.sh is registered. With git_restore ON,
deferring would be a correctness bug rather than an optimisation -- the
restore repairs the store and the render would read the store it was supposed
to repair, which is wrong memory, silently. With a third-party script present,
its stdout may be context it expects to inject, and a deferred dispatch sends
that to /dev/null; their contract is kept literally. Both guards are free: a
cached config read and a glob.

The bug: dispatch named its capture files `tmp/dispatch-stdout.$$`, and `$$`
is the SHELL's pid, unchanged inside a subshell. So the deferred
before_session_start dispatch and the foreground after_session_start dispatch
used the same two paths, and the background one's end-of-loop `rm -f` deleted
the capture the foreground one was still writing. A plugin's injected context
vanished with no error anywhere -- the silent-absence class, introduced by the
optimisation itself and caught by an existing end-to-end test
(test_marketplace_hooks_d_dispatches_from_plugin). Fixed by putting $event in
the name. $BASHPID would be more general and is deliberately not used: bash
4.0+, and macOS still ships bash 3.2.

Also: the gate shim resolves grep through the same bash the hook runs under.
Scanning os.environ for a file literally named "grep" found nothing on
windows-latest (it is grep.exe under Git's usr/bin) and failed both tests on
every Windows leg while passing on macOS and Linux.

Bench samples per arm 5 -> 9: windows-latest moved its own no-plugin baseline
15% between two consecutive runs, which is wider than the differences being
measured.

Co-Authored-By: Max <noreply>
(cherry picked from commit ea50558)
…forks

Deferral moves work; this removes it. On Git Bash a fork costs 10-50x what it
costs on Linux, so the foreground fork count is the thing worth shrinking, and
unlike wall clock on a shared runner it is deterministic enough to state.

- the render no longer forks `cat` once per memory file (five on a typical
  store). `IFS= read -r -d ''` reads a whole text file into a variable with no
  subprocess at all. NOT `printf '%s\n' "$(<file)"`: command substitution
  strips every trailing newline and the printf adds exactly one back, so a
  file ending in two newlines -- or none -- would silently render differently
  in the model's injected context. tests/test_render_is_byte_identical_660.py
  pins six shapes against `cat` itself as the oracle, and carries a
  demonstration that those shapes DO fail against the naive form, because a
  refactor guarded by a test that passes either way is not guarded.
- REMEMBER_ROOT stops forking `dirname`. The replacement is compared against
  real `dirname` over twelve path shapes (trailing slashes, bare names, the
  root, spaces, a quote, unicode) rather than trusted to a comment -- it
  decides where the user-global identity.md is looked for, and getting it
  wrong would silently stop that tier resolving.
- `mkdir -p` on tmp/ is guarded by `[ -d ]` at three sites. The directory
  exists on every start after the first, and the test is a builtin.

tests/test_session_start_prev_session_270.py joins the files that run the
deferred phase inline: its subject is WHICH session gets named, not when.

Not included, deliberately: deferring promo selection. It works and saves two
jq forks, but it changes when a promo is shown, and the tests encoding #574's
"marker only after delivery" rule, #596's agy suppression and #657's star-ask
gate all have to be rewritten around the new timing -- nine of them across
four files. That is its own reviewed change, not a rider on this one. The
cheaper route is probably an mtime-keyed cache of the two jq reads, which
costs no behaviour change at all.

Foreground forks measured with the phase-labelled trace: 49 before this
branch, 29 now, 15 of them moved to the deferred phase rather than removed.
Local suite: 2445 passed, 47 skipped.

Co-Authored-By: Max <noreply>
(cherry picked from commit ab1765d)
…t size-aware

The probe answered, and it says the previous commit made things worse where it
matters. windows-latest, five iterations each:

    size     cat      read
    4KB      0.197s   0.025s     read wins by 8x
    256KB    0.092s   1.505s     read loses by 16x
    4MB      0.099s   24.129s    read loses by 240x

ubuntu-latest has the same shape (4MB: 0.008s vs 0.879s), so it is not a
Windows quirk: bash's `read` walks the delimiter byte by byte, and a fork is a
fixed cost. Replacing five forks with five whole-file reads is a win on a
small store and a catastrophe on a real one -- which is exactly what the
big-store arms showed after the last push (year-old hook 3638 -> 4393ms,
abandoned 3328 -> 4679ms) while the no-plugin baseline and Linux did not move,
and which I first dismissed as runner noise.

So the emitter takes the size the render already computed and picks: `read`
under 16KB, `cat` over it. The threshold sits well below the ~34KB crossover
those numbers imply, because being wrong towards `cat` costs one fork and
being wrong towards `read` costs seconds. A missing or non-numeric size falls
back to `cat` rather than into an arithmetic error that would print an empty
section and read as an empty memory file.

Tests drive both branches by name, plus the no-size fallback. The probe stays
in the workflow: it is the only thing that could have caught this, and it cost
two attempts of its own (`yes` reading a dash-prefixed argument as an option,
then SIGPIPE under pipefail) before it measured anything.

Fork counting alone would have called the first version a clean win. It could
not see the seconds.

Co-Authored-By: Max <noreply>
(cherry picked from commit 57dc4bd)
…o not race it

Two of the four macos-latest legs on #696 failed on

    assert len(list(store.iterdir())) < 400  # store is never pruned

with exactly 400 entries; ubuntu and windows were green, and so were the
other two macos legs. That spread is a race, not a verdict. The prune
lives in _remember_deferred_phase (scripts/session-start-hook.sh:1050),
which this same pull request moved off the foreground path, so it is no
longer finished when the hook exits -- the assertion simply read the
directory too early.

Polls for up to 15s rather than sleeping a fixed amount. Deliberately NOT
REMEMBER_DEFER=0: the default path is the one that has to prune, and an
inline run would still pass if the deferred phase died before reaching
it -- which is the failure this file exists to catch.

Part of #660

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit 521a301 into main Sep 15, 2026
16 checks passed
@fdaviddpt
fdaviddpt deleted the perf/660-foreground-path branch September 15, 2026 13:15
fdaviddpt added a commit that referenced this pull request Sep 15, 2026
…e the tag (#701)

The v0.33.0 release audit (round 1, token rel-0330-429b3dd1) returned six
findings, none in a blocking row. Five are fixed here; the sixth is filed
as #700.

**The scanner credited a nested function's declaration to its parent.**
_function_spans closed a function at the first `}` at column 0, on the
stated assumption that no function is defined inside another. #696 broke
that assumption: capture_was_seen() is defined at column 0 inside
_remember_deferred_phase(), so the outer span was computed as ending at
the inner function's brace and the inner's `local LC_ALL=C` was credited
to 148 outer lines that have none. Neither PR contains this -- #696 has
no scanner, #699 has no nesting -- it existed only once both had landed,
which is the kind of thing only a whole-delta audit sees. Nothing falls
through it today (a direct sweep of those lines finds no ranges), but
the scanner is the entire standing defence for a class that already
shipped a total-failure bug. Now a stack, with a nested fixture pinning
both halves.

**`local LC_ALL=C` never reached the `tr` child.** `local` on a name the
environment never exported leaves it unexported, so on a host whose
language comes from LANG alone -- what setting a system language
actually produces -- the drive-letter uppercase still ran under Turkish
rules and mapped `i` to the dotted `İ`. My own test in #699 passed
because its harness exports LC_ALL, so `local` shadowed an
already-exported name: it passed for a reason that does not hold on a
real host. The new control puts a recording `tr` on PATH and asserts
what locale it was actually called under, which runs on every platform
and does not need a glibc runner to fail. The changelog fragment that
claimed this was fixed is corrected in the same commit.

**An unmeasured file size laundered into 0**, in two places, which made
_remember_emit_file's own "no usable size" arm unreachable from its only
caller: `0` is a digit string and `0 -gt 16384` is false, so a file of
any size took the read path that #660's own threshold exists to keep it
off -- 4MB measured at 24.1s on windows-latest, on the session-start
foreground path. The batched `wc -c` can fail wholesale, leaving every
file in that state at once. Unknown is now kept distinct from zero end
to end, and the compact-mode notice says `size unknown` rather than
printing `0 bytes` for a file nobody measured.

**The deferred default-path control asserted one of the three records
its own docstring named.** It now polls both that this fixture's storage
mode can produce, and says why the third needs external storage and
where it is covered instead.

Local suite: 2483 passed, 58 skipped. The one failure on the way was
this repo's own blanket-win32-skip guard catching a triage row I had not
written yet -- added.

Part of #695
fdaviddpt added a commit that referenced this pull request Sep 15, 2026
macos-latest 3.10 went red on #702, a pull request touching none of this
code. It was not a flake, and the red leg was the smaller half of what
it exposed.

#660 moved the capture-gap check into _remember_deferred_phase, where it
is the LAST thing that phase does -- session-start-hook.sh writes the
notice at the end, after the records and after the evidence-store prune.
So the hook returning says nothing about whether the check has run yet.
Every assertion in tests/test_capture_gap_notice.py reads that file
immediately after the hook returns.

The positives fail intermittently, which is the red leg. The six
negatives are worse: `assert not notice.exists()` is satisfied just as
well by a phase that has not reached the check yet, or that died before
it -- the negative and the absence are the same file-not-found. Those
six have been passing without being able to fail, on every leg, since
#660 landed. CLAUDE.md says this in as many words: "an assertion that
something does not happen also passes when nothing happens at all".

Split along that line:

  the three positives stay on the DEFAULT deferred path and poll, which
  is what proves the phase actually reaches its end;

  the six negatives run the phase inline (REMEMBER_DEFER=0), where "did
  not fire" is a verdict rather than a race.

_env() takes the choice as an explicit keyword rather than a flag
somebody has to remember, and its docstring carries the reason.

I had already fixed one instance of this shape on #696 -- the evidence
store prune, in this same file -- without noticing the rest of the file
had it too. Three mechanisms missed it (the per-PR review, both audit
rounds, and eleven green legs); the twelfth leg caught it.

Local suite: 2486 passed, 58 skipped.

Part of #695

Co-Authored-By: Max <noreply>
fdaviddpt added a commit that referenced this pull request Sep 15, 2026
* fix(#695): the third call site the round-1 repair missed, and two traps logged

Round 2 of the v0.33.0 release audit (token rel-0330-r2-96ee92d0) returned
three findings, all ranked `misreports`, none blocking:
carry-forward-and-proceed. Two are carried forward as trap.d fragments.
The third is a defect in the round-1 repair itself and is fixed here,
because leaving it would also leave a false sentence in the release
notes.

The round-1 repair changed _remember_wc_size_get_into's contract: it used
to answer `0` for a path it holds no measurement for, and now answers the
empty string, so that _remember_emit_file's "no usable size" arm can
actually be reached. Two of the getter's three call sites were updated to
say `size unknown`. The third -- the rotated-slices listing -- still
formatted the value straight into `%s bytes`, so with the batched `wc -c`
failing (the exact scenario the repair exists for) it renders

    /path/archive-2026-01-01.md ( bytes)

a number-shaped slot holding nothing, which reads as neither a size nor
an absence. Same three-state `case` the deferred listing already carries.

The new control is source-shape rather than behavioural, and says so:
reaching that third site behaviourally means driving the whole render
with rotated slices present and `wc` broken, while the invariant -- a
line that formats a byte count has a `size unknown` branch near it -- is
cheap, and the next call site added meets it. Verified red before the
fix and green after, with a must-fire control pinning that the detector
still sees the format string it scans for.

changelog.d/695.fixed.audit.md claimed the unmeasured size was "kept
distinct from zero all the way through". It was not, and that sentence
is corrected rather than left to ship.

Carried forward, per the ranking table's `misreports` row:

  trap.d/695.outward-walk-assumes-lexical-scope.md -- _is_protected
  credits an enclosing function's `local LC_ALL=C` to a function merely
  defined inside it. bash scoping is dynamic, so that only holds when
  the nested function is called from within its definer. No instance in
  this tree today: the one nested pair is called from inside, and that
  definer carries no such declaration.

  trap.d/695.emit-read-max-is-an-unvalidated-knob.md --
  REMEMBER_EMIT_READ_MAX is the one numeric read in
  lib-memory-context.sh with no digit guard; a non-numeric value prints
  a bash error, does not abort inside an `if`, and falls through to the
  read arm -- the same failure the round-1 repair fixed from the other
  direction.

Local suite: 2486 passed, 58 skipped.

Part of #695

Co-Authored-By: Max <noreply>

* fix(#660): the capture-gap tests raced the phase that writes the notice

macos-latest 3.10 went red on #702, a pull request touching none of this
code. It was not a flake, and the red leg was the smaller half of what
it exposed.

#660 moved the capture-gap check into _remember_deferred_phase, where it
is the LAST thing that phase does -- session-start-hook.sh writes the
notice at the end, after the records and after the evidence-store prune.
So the hook returning says nothing about whether the check has run yet.
Every assertion in tests/test_capture_gap_notice.py reads that file
immediately after the hook returns.

The positives fail intermittently, which is the red leg. The six
negatives are worse: `assert not notice.exists()` is satisfied just as
well by a phase that has not reached the check yet, or that died before
it -- the negative and the absence are the same file-not-found. Those
six have been passing without being able to fail, on every leg, since
#660 landed. CLAUDE.md says this in as many words: "an assertion that
something does not happen also passes when nothing happens at all".

Split along that line:

  the three positives stay on the DEFAULT deferred path and poll, which
  is what proves the phase actually reaches its end;

  the six negatives run the phase inline (REMEMBER_DEFER=0), where "did
  not fire" is a verdict rather than a race.

_env() takes the choice as an explicit keyword rather than a flag
somebody has to remember, and its docstring carries the reason.

I had already fixed one instance of this shape on #696 -- the evidence
store prune, in this same file -- without noticing the rest of the file
had it too. Three mechanisms missed it (the per-PR review, both audit
rounds, and eleven green legs); the twelfth leg caught it.

Local suite: 2486 passed, 58 skipped.

Part of #695

Co-Authored-By: Max <noreply>
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.

1 participant