Skip to content

DIAGNOSTIC (do not merge): where does session-start-hook.sh spend its time on Windows? (#660) - #689

Open
fdaviddpt wants to merge 12 commits into
mainfrom
diag/660-where-time-goes
Open

fdaviddpt wants to merge 12 commits into
mainfrom
diag/660-where-time-goes

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

DO NOT MERGE. DO NOT REVIEW. Throwaway diagnostic for #660; this branch and this pull request get deleted once the tables are read.

It exists only because .github/workflows/tests.yml fires on push: [main] and pull_request — a branch on its own reaches no Windows leg, and windows-latest is the one Windows box this project controls.

The test fails on purpose, on every leg. pytest prints nothing from a passing test without -s, and this test exists only to print. Red here means it worked.

What it measures

Part of #660. The reporter measured ~40 subprocess calls on 0.32.0 and ~90ms per fork on their host: 3.6s accounted against 38.5s observed. Nine tenths of the time is unexplained by the model the whole thread has been reasoning from, this repo's own latency numbers included.

So: run the real hook under a trace with PS4 carrying $EPOCHREALTIME, charge the gap between consecutive timestamps to the command on the earlier line, aggregate, print the 25 slowest for a cold and a warm run.

Scaled over 1 / 500 / 2000 past transcripts against a ~400KB store, because previous_transcript() runs ls -t "$SESSIONS_DIR"/*.jsonl and stats every past transcript to read one line off the top. The existing benchmark fixture has exactly one; a heavy user has thousands. If that is where the time goes the curve says so, and if it is flat the suspicion is dead and the trace still names what is actually slow.

One finding already, before any CI number

The trace has to run on its own fd. scripts/bootstrap-dirs.sh:364 runs exec 2>> "$REMEMBER_DIR/logs/hook-errors.log", which captures the xtrace stream from that line onward — a plain bash -x of this hook reads wall 0.71s, traced span 0.07s and says nothing about the 90% it lost. Any profiling of this hook that did not move the trace off fd 2 stopped there silently. That may include the measurements #660 has been reasoning from.

Local macOS baseline, 400KB store, 1 transcript: cold 0.71s, warm 0.39s, of which roughly 0.28s is five separate jq invocations.


🤖 Generated with Claude Code

[AI-generated]

fdaviddpt and others added 3 commits September 14, 2026 16:59
…ts time (#660)

Throwaway, to be deleted with its branch. Runs the real hook under a
BASH_XTRACEFD trace with PS4 carrying $EPOCHREALTIME, charges the gap between
consecutive timestamps to the command on the earlier line, and fails on
purpose so the table lands in the job log.

BASH_XTRACEFD rather than bash -x: bootstrap-dirs.sh:364 runs
exec 2>> logs/hook-errors.log, which hijacks a fd-2 trace part-way through
the run -- measured here first as wall 0.71s against a traced span of 0.07s.
Any xtrace profiling of this hook that did not move the trace off fd 2
stopped at that line without saying so.

Scaled over 1/500/2000 past transcripts, because previous_transcript() runs
ls -t on every past transcript to read one line off the top, and the existing
fixture has exactly one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…usion

Round 1 measured session-start-hook.sh at 2.25s cold / 1.80s warm on
windows-latest with a 400KB store, against the 38.5s the reporter measures on
their own Windows 11 ARM64 box. Nothing in the trace was pathological, so the
gap is environmental and this round removes the one environmental difference
CI controls.

tests.yml has excluded the checkout and RUNNER_TEMP from Defender real-time
scanning since claude-jit-context#310. Note it never covered the fixtures:
pytest tmp_path lands in the user TEMP, not RUNNER_TEMP, so round 1 was
already scanning the store and exempting only the scripts bash reads.

This branch drops the exclusion step entirely and reports Defender state
instead, so every file the hook touches is scanned, the way a real user is.
Reverted with the branch; nothing here is proposed for main.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Rounds 1 and 2 scaled transcript count and found it nearly flat: 0.41s of a
3.2s run at 2000 transcripts, and removing the Defender exclusion changed
nothing because windows-latest reports RealTimeProtectionEnabled: False with
C:\ and D:\ already excluded -- the exclusion step in tests.yml is inert on
that image and CI cannot measure an antivirus tax at all.

So this round scales what a long-lived store actually grows along:

  store_kb      the six memory files, 400KB to 20MB
  previous_mb   the newest transcript, 0.01MB to 100MB. capture-gap greps it
                (session-start-hook.sh:999) and grep -q reads to EOF when the
                pattern is absent, which it is in this fixture
  slices        rotated archive-*.md / recent-*.md, globbed and sorted by the
                memory render on a cache miss
  staging       past-day today-*.md, counted by the consolidation trigger

Three scenarios: baseline, year-old-store, abandoned-store.

Already visible locally on macOS at the middle scenario: the 20MB transcript
grep is 0.279s, the largest single line in the trace, on a fast SSD with
nothing scanning it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… the hook

Every existing #660 instrument invokes scripts/session-start-hook.sh
directly, so none of them can see what the reporter last measured: a full
Claude Code cold start at 18.3s median with the plugin enabled against 6.8s
disabled, of which the hook own durationMs accounts for about 2.2s. Most of
the gap sits outside the hook path, and nothing in this repo looks there.

This launches the real claude binary with the plugin installed the real way
(a local marketplace) against a local stub endpoint that speaks the Anthropic
SSE shape. No API key, no spend, no network variance. A deliberately invalid
key was tried first and rejected: a 401 costs 187s of retry backoff.

Three numbers per run -- wall, launch-to-first-API-request (the init cost,
which durationMs does not report), and the hook durationMs read back out of
the transcript, the same field the issue was opened on.

Positive control: the no-plugin arm must record no SessionStart hook and
every plugin arm must record one, or the runner exits non-zero. An arm whose
plugin silently failed to install would otherwise read as a fast arm.

Store shapes reuse the round-3 scenarios from #689, so the two tables
describe the same stores.

Throwaway, like the rest of the branch. Not a gate.

Co-Authored-By: Max <noreply>
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>
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>
… 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>
…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>
The Windows bench got slower on exactly the big-store arms after the render
stopped forking `cat` (fresh 2600 -> 3220ms, year-old 3638 -> 4393ms,
abandoned 3328 -> 4679ms) while the no-plugin baseline did not move and Linux
did not move either. Two explanations fit: bash reading a multi-megabyte file
byte-wise under `read -d` is slower than the five forks it replaced, or this
runner is noisy in the way the last four runs have already shown. Staring at
medians cannot separate them.

So the job measures both directly, at 4KB, 256KB and 4MB. Whichever way it
comes out, the answer is a number from the platform that has the problem
rather than an argument from first principles -- and if `read` loses at size,
the fix is to keep it for small files and let `cat` have the large ones.

Co-Authored-By: Max <noreply>
`yes '- a remembered line...'` read its argument as an option and the step
died before measuring anything ("yes: unknown option -- ", windows-latest).
`yes --` ends option parsing.

Co-Authored-By: Max <noreply>
`yes | head -c` under `bash -e -o pipefail` fails the step: head closes the
pipe once it has its bytes and the SIGPIPE that kills `yes` is the pipeline's
status (exit 141, windows-latest). python writes the file directly.

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