Repository navigation
Description
In a Claude Code session that holds a page, Leaf's hooks take the full uv run python -m leaf hook path. The PostToolBatch hook does this on every tool batch, and in almost every batch it finds nothing pending. Claude Code waits for it before each model call.
Measured over a week of sessions on one Linux host:
| Hook | Session holds a page | p50 | p99 |
|---|---|---|---|
| PostToolBatch | yes | 358 ms | 2.9 s |
| PostToolBatch | no, the stdlib gate answers | 102 ms | 644 ms |
| Stop | yes | 818 ms | 4.6 s |
| SessionStart, resume | yes | 468 ms | 4.8 s at p90 |
Before doing any work, a run in a page-holding session starts two interpreters: the stdlib gate in bin/leaf, then uv run. Medians of 9 runs on the same host:
| Step | As measured | Stdlib bytecode cached |
|---|---|---|
Gate: python -S state.py hook-gate |
78 ms | 24 ms |
uv run's own overhead |
47 ms | 47 ms |
Interpreter start plus importing leaf.hooks, leaf.harness, leaf.hook_transport and leaf.delivery |
359 ms | 120 ms |
That host's Python shipped without compiled stdlib bytecode, so every interpreter start compiled each stdlib module it imported. The right column used a warm PYTHONPYCACHEPREFIX, which matches an ordinary install, where the startup comes to about 190 ms. The left column sums to more than the 358 ms PostToolBatch median, and I haven't reconciled the two. One candidate is batches inside subagents: cmd_hook returns from those right after importing leaf.hooks.
Here is where the roughly 190 ms on an ordinary install goes. Import time is split by -X importtime self time, scaled to the 101 ms the imports take without it.
| Part | ms |
|---|---|
uv run's project check |
47 |
| The gate's separate interpreter | 24 |
| Starting the second interpreter | 13 |
Third-party imports, mostly jsonschema and turbohtml |
52 |
| Stdlib imports | 28 |
| Leaf's own modules | 21 |
Leaf's own code is about a tenth of the total. Three heavy imports happen at module load:
leaf.registry.contractimports one helper fromjsonschema._utils;leaf.registry.schemaimportsjsonschema;leaf.passagesimportsturbohtml.
A hook that finds nothing pending probably needs neither schema validation nor HTML parsing, though I haven't checked. If so, keeping those modules off the hook's import path would save most of the 52 ms. The gate already runs on the environment's interpreter. Where uv run's sync check isn't needed, running the hook in that same process would save uv's 47 ms and the second interpreter's 13 ms.
The proposals below come from reading the hooks at this version and Claude Code 2.1.310's hook runner. Making the existing hooks async: true doesn't work. Claude Code drops an async hook's decisions and plain-text output, and delivers its JSON additionalContext only at the next tool boundary or the next prompt.
1. Deliver mid-turn input from the prompt watch, and drop the PostToolBatch hook
Claude Code queues an asyncRewake hook's exit 2 as a task notification with priority next. At the next tool boundary it adds the notification to the running turn and runs the UserPromptSubmit hooks for it. Transcripts already show Leaf input arriving mid-turn this way when another background notification is added at a boundary. The prompt hook records the handover as hook_additional_context, which receipt confirmation already matches. So the background watch that starts at each prompt could carry mid-turn input, in place of polling on every batch. The changes:
- Wake mid-turn for new input. Let an at-prompt watch wake while its turn runs, for new input only, not for owed reminders. That logic is in
later_turn_wakesinsession.py. The UserPromptSubmit that the wake triggers starts a fresh watch for the rest of the turn. - Watch after a claim. Start a watch after a claiming
leafcommand, for example anasyncRewakePostToolUse registration with the sameif: Bash(leaf *)patterns. - Treat a mid-turn wake as a tool boundary. Have the prompt hook hand over only new input there, with no reminders and no turn renewal.
prompt_idalone can't tell this wake from a prompt the user types mid-turn, because both carry the running turn'sprompt_id. - Accept Stop-time delivery under plain
--print, which runs no watch.
Double wake at turn end. Input can arrive after the turn's last tool boundary. The prompt watch then exits 2, and because Claude Code adds next items only at tool boundaries, that notification opens a new turn after the Stop hooks. Meanwhile the Stop watch finds the same input deliverable with the turn closed, and wakes the session too. The Stop watch's ready() doesn't consult the mark woke_after sets, so it should skip input whose wake is already queued.
Deleting the PostToolBatch registration also removes the mid-turn reconcile_turn that repairs a wrong turn record at the next boundary.
Interim step. Without changing behaviour, the stdlib hook-gate could exit 3 in two more cases:
- a PostToolBatch carrying
agent_id, whichcmd_hookalready ignores, but only after uv has started; - when no owned page's log has changed since the last empty run and no inline handover awaits receipt, judged from a stamp the full hook writes.
That should bring a page-holding session's silent batch down to about the 100 ms a batch costs in a session without a page.
2. Answer Stop from the Stop watch, after making a late Stop safe
In an interactive session, the synchronous Stop hook continues the turn only for a page that re-vendoring left unready. Its other work is confirming receipt and closing the turn record. Moving that work into the Stop watch, which already runs beside it, would save about 600 ms per Stop in a session holding a page.
It isn't safe yet. reconcile_turn assumes Claude Code runs a session's hooks in order. When a Stop names a prompt that the record doesn't hold, it advances the record to that turn. If the next prompt's hook writes turn T2 first, a late Stop for T1 re-advances the record to T1 and closes it while T2 runs. Calling cmd_hook against a throwaway state home shows it. In order, the record ends at T2, open. With the Stop late, it ends at T1, closed.
The watch would need three things:
- stamp the Stop time at spawn and pass it in;
- have
reconcile_turnand the close refuse a Stop older than the record'sturn_opened; - stop turning every clean stdout into exit 2, so the plain
--printStop JSON passes through.
3. Let SessionStart run async except after compaction
On resume, Claude Code waits for SessionStart hooks before it reads the session's messages. Leaf's SessionStart work only reads state to build reconnect notices, and the prompt hook repeats those notices for retained claims, so a late notice loses nothing. Split the registration by matcher. compact stays synchronous, because it tells the agent to re-read the skill before it replies. startup|resume|clear can be "async": true.
Seen on leaf 8ca760b, installed 2026-10-27T16:18:15-07:00.
This was written by Claude Code on behalf of max-sixty
Activity
leaf-agent commentedon Oct 28, 2026
The late-Stop prerequisite reproduces on current main. Moving Stop into the asynchronous watch needs to settle this ordering first:
ClaudeCodeHarness.reconcile_turnreplaces the current turn with an unfamiliar Stop prompt ID before the close guard runs. Adding anended_atcheck only to the close would therefore be too late; reconciliation has already replaced T2 and its opening timestamp.I ran
cmd_hookagainst a throwaway state home at18421075b5dfbba98314ad77c98ab9202aa348be:The existing reconciliation contract deliberately accepts previously unseen turns because a typed prompt can later run under an ID its prompt hook never named. The repair needs to preserve that case while rejecting stale Stops.
Import probing also narrows the startup work: importing
leaf.hooks, thenleaf.harness, leaves bothjsonschemaandturbohtmlunloaded; importingleaf.hook_transportloads both. That makes the page-reading/delivery boundary the place to investigate before changing the launcher. I have not established that an empty page-owning hook can avoid those dependencies throughout its execution.I left this open without a fix PR. The runner has no Claude Code executable, so I could verify Leaf's reordered callbacks but not the replacement wake/receipt path in a real harness. Before removing PostToolBatch, that path still needs to demonstrate how a wake is distinguished from typed mid-turn input, input after the last tool boundary wakes once, and a claim starts observation without a subsequent user prompt. The related measurement and observation backlog items are #4084 and #4083; this report supplies concrete evidence beyond them.
Reproduce the turn-ordering result
Run from the checkout with
uv run python:This isolates lifecycle handling without requiring a page or an active Claude Code session; it does not establish that the current synchronous registrations reorder callbacks in practice.
max-sixty commentedon Oct 28, 2026
@leaf-agent why didn't the triager attempt to fix this??
leaf-agent commentedon Oct 28, 2026
The earlier triage treated the missing native-harness verification as a blocker for too much of the report. It should still have attempted the independently testable startup improvements.
#4627 implements the worker-batch gate: a page-owning parent's worker
PostToolBatchnow exits before starting uv, using the same exclusion as the full hook. The regression failed before the fix and passes after it; controls prove parent batches, prompt hooks and other harnesses still reach uv. The focused hook checks passed (52 tests). The queued review and Tend landing workflow own its remaining review and CI verification; I have not waited for CI withawait_ci: false.This is a partial repair. Parent-session empty batches still take the full path. The watch-delivery replacement, late-Stop handling and SessionStart scheduling remain open here; their end-to-end verification needs a runner with native Claude Code, which this runner lacks. The next verification needs to cover a wake during an active turn, input after its last tool boundary, and observation immediately after a claim before removing batch polling.
fix: skip uv for Claude Code worker tool batches (#4627)
Say where an empty boundary leaves an older page's renewal
List every route a deferred update takes, and hold the transport's im…
Run Claude Code's start hook only after a compaction
Answer Claude Code's empty tool boundaries from the page log (#5051)
Run Claude Code's start hook only after a compaction (#5052)
Read a page in its layer's vocabulary, without composing the layer's …
leaf-agent commentedon Nov 4, 2026
Status: most of this report has landed, and #5246 now holds the remaining latency work. Nothing here needs a new fix from triage.
PostToolBatch.PostToolBatchwith nothing pending from the page log, without folding the page. That keeps jsonschema and turbohtml off the hook's import path, and the median in the claude-code journey fell from 565 ms to 212 ms.compact. Running it async would have delivered the reconnect notice twice, so startup, resume and clear no longer run it at all.Proposals 1 and 2 haven't been built: removing
PostToolBatchin favour of the prompt watch, and answering Stop from the Stop watch along with the late-Stop guard that move needs. #5246 takes a different route. The session's pages follower would answer the hooks over a Unix socket,hooks.jsonstays as it is, and every hook stays synchronous. On that route a Stop never runs late, so thereconcile_turnordering problem from my first comment never arises, and I'm not adding a guard for it on its own. #5246 is a backlog item, so its timing is up to you, and so is whether to close this issue in its favour.max-sixty commentedon Nov 5, 2026
Closing as a duplicate. Most of the report landed (worker batches skip uv, empty boundaries answered from the log, SessionStart only after compaction, prompt/Stop hooks ~700 to ~300 ms), and the remaining latency work is #5246's different route (the pages follower answers hooks over a socket), which also makes this issue's late-Stop prerequisite moot.