Skip to content

Cut $( ) subshell forks on SessionStart's config/timestamp/slug paths (#665) - #677

Merged
fdaviddpt merged 3 commits into
mainfrom
fix/665
Sep 12, 2026
Merged

fdaviddpt merged 3 commits into
mainfrom
fix/665

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Closes #665. Part of #660.

What

$( ) forks a subshell to capture output even when the wrapped command execs nothing external -- invisible to tests/spawn_counting.py, which counts execs. This removes that class of fork from SessionStart's hot path:

  • config() (log.sh) is now a thin wrapper over a new config_into VARNAME key default (printf -v, no subshell), used at every flattened-cache config read on the SessionStart/per-tool-call paths -- .features.*, .handoff_mode, .cooldowns.*, .timezone, .prompt_stamp, .model, .reject_pattern, .thresholds.*.
  • log()'s and MEMORY_LOG_DATE's timestamps now call the existing _remember_date_into (lib-clock.sh, user-prompt-hook.sh still ~2.5s p50 / 31s max on Windows Git Bash in 0.21.0 (follow-up to #227) #511) directly instead of $(_remember_date ...).
  • New _remember_forward_slash_into and _stdin_json_string_into siblings, wired into every session-start-hook.sh / lib-memory-context.sh call site.
  • lib-slug.sh's _remember_build_slug_sed -- 22 $(printf '\NNN') calls building the slug's byte-range sed program, run once per hook invocation -- now uses bash's own ANSI-C ($'\NNN') octal quoting: a lexer-level substitution, no fork at all. Proved byte-identical to the old builder by a dedicated test, and independently re-verified by a review round that ran both builders and diffed their output directly.

Deliberately unchanged

Testing

TDD: tests/test_session_start_fork_tax_665.py is new, using a $BASHPID-based fork counter (each real fork() gets bash a brand-new pid, unlike $BASH_SUBSHELL -- nesting depth, verified to undercount 22 real sibling forks as 2 -- or $$, which bash does not reset in a subshell). Red before the fix existed (config_into/_stdin_json_string_into not defined -- command not found; log() still forking 12+ times; the slug builder still forking 44 times, since it's called twice per test setup). Green after. The file skips itself loudly, naming the mechanism, on a host whose resolved bash lacks $BASHPID (pre-4.0, e.g. stock macOS /bin/bash 3.2) rather than reporting a false "broken probe" failure.

Several existing tests needed updates because they extract or byte-pin literal source text, or stub bash functions, whose shape changed: tests/test_case_divergence_298.py (new sanctioned-divergence entry for the byte-identical slug-sed rewrite, verified against the live file), tests/test_config_contract.py and tests/test_shared_rules.py (their config()-call regex now also matches config_into), tests/test_delivery_record_pruning_373.py and tests/test_windows_glob_backslash_517.py (extraction markers/stubs updated for the _into call shape), tests/test_session_start_promo_spawn_budget_660.py (stub harness needed config_into/_remember_forward_slash_into stubs).

Full pytest run four times across this branch (once per commit that could plausibly regress something, since the review rounds kept widening which files the scope touched): 2386 passed, 47 skipped, every time. This is reported honestly rather than credited toward the PR closing -- CI's 13-leg matrix is the actual gate.

Two self-review rounds (Explore + oss:auditor, then a re-spawned oss:auditor against the accumulated diff) found and this branch fixed: a variable-name-collision risk in the new _into helpers' internal locals (narrowed, not fully closed -- bash 3.2 has no nameref); four missed $(_remember_date ...) call sites, including one on the unconditional hot path (TODAY=...) and one at the top level of log.sh (MEMORY_LOG_DATE=..., found by the second round after the first round's fixes); a stale, now-duplicated comment inside config(); and a version probe (_bash_has_bashpid) added to the new test file after the auditor flagged that $BASHPID availability on CI's macos-latest leg could not be verified from this repo. Below-bar note: whether that skip-gate's pre-4.0 branch is ever actually exercised by a real CI runner remains could not check: CI coverage -- the gate itself is correct either way, and this is recorded as an open question rather than a defect.

Docs

changelog.d/665.changed.md added. No docs_targets (README.md) update -- read against the SessionStart section, nothing there describes internal fork counts or config() implementation, and config()'s external contract (key/default) is unchanged.

[AI-generated]

fdaviddpt and others added 3 commits September 12, 2026 13:03
…#665, part of #660)

`$(fn ...)` forks a subshell to capture output even when `fn` itself execs
nothing -- `tests/spawn_counting.py` counts execs, not forks, so this class
of cost was invisible to the existing budget tests. `config_into VAR key
default` (printf -v, no command substitution) now backs every
`.features.*`/`.handoff_mode`/`.cooldowns.*`/`.timezone`/etc. read on the
SessionStart and per-tool-call config paths, with `config()` itself now a
thin wrapper over it so external callers keep the `X=$(config ...)` idiom
unchanged. `log()`'s timestamp now calls `_remember_date_into` (#511)
directly instead of wrapping it in `$( )`. `_remember_forward_slash` and
`_stdin_json_string` each gained an `_into` sibling, wired into every
session-start-hook.sh call site. `lib-slug.sh`'s `_remember_build_slug_sed`
-- 22 `$(printf '\NNN')` calls assembling the slug's byte-range sed program
once per hook invocation -- now uses bash's own ANSI-C ($'\NNN') octal
quoting, a lexer-level substitution that forks nothing, proved
byte-identical to the old builder by a dedicated positive/negative-control
test pair using a $BASHPID-based fork counter (BASH_SUBSHELL undercounts
sibling forks at the same nesting depth, measured directly against this
same builder: 2 vs the real 22).

Deliberately unchanged: log()'s message control-byte scrub (`printf | tr`)
survives two prior attempts at removal (#618/#620 landed correctness fixes,
#621's own optimization was reverted after failing on live CI in ways this
repo could not reproduce locally) and is not reopened here; the
`.hooks.dispatch_*` reads inside `_remember_run_hooks` are left alone to
avoid colliding with a parallel lane's planned edits to that region;
doctor.sh, lib-case-divergence.sh and run-consolidation.sh are not on the
SessionStart hot path and are untouched.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScdCn6Xq622o2cRQhzVhi5
Explore reviewer found: (1) config_into/_stdin_json_string_into's internal
locals (`_cfg_key`, `_sjs_value`, etc.) were named with a generic tag that
could itself be chosen as a caller's destination variable, silently
shadowing the write -- renamed to the function's own full name
(`_cfg_into_*`, `_sjsi_*`) to narrow (not close -- bash 3.2 has no
nameref) the collision, and the doc comment now says so plainly instead of
overclaiming; (2) four `$(_remember_date ...)` call sites survived
unconverted in session-start-hook.sh, one on the unconditional hot path
(`TODAY=...`) -- wired all four to the existing `_remember_date_into`;
(3) config()'s own comment still explained validation logic that moved to
config_into() -- trimmed to a pointer.

oss:auditor found: the new fork-counting test file
(tests/test_session_start_fork_tax_665.py) depends on $BASHPID (bash
>= 4.0), and stock macOS ships bash 3.2 as /bin/bash with no BASHPID --
`resolve_bash()` trusts whatever `bash` is on PATH, and whether that is
old enough to lack it is genuinely host-dependent, not something this
diff could rule out. Added a version probe (`_bash_has_bashpid`) that
skips the whole file loudly, with the mechanism named, on a host where it
would otherwise fail every test with a "broken probe" false negative.

Also fixed a new SC2154 shellcheck warning (`_remember_now` referenced but
not assigned, from shellcheck's inability to see the printf -v indirection)
by seeding it empty first, matching the existing convention at every other
`_into` call site in this diff, and updated
tests/test_delivery_record_pruning_373.py's extraction-block stub for the
now-converted `_remember_date_into` call it exercises.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScdCn6Xq622o2cRQhzVhi5
)

A second self-review round (fresh oss:auditor spawn, prior round's findings
already addressed in 9ace044) found `log.sh:628`'s
`MEMORY_LOG_DATE=$(_remember_date +%Y-%m-%d)` -- a $( ) subshell fork at the
top level of log.sh, run unconditionally on every single hook invocation
(SessionStart, PostToolUse, every hook that sources this file), exactly the
class this whole issue exists to remove, and missed by both prior passes
even though `_remember_date_into` was already in scope three lines above
(lib-clock.sh, sourced immediately before) and `log()`'s own timestamp a
few lines below was already converted. Wired to `_remember_date_into` the
same way.

The auditor's other finding -- whether the new `_bash_has_bashpid` skip
gate (added in 9ace044) actually exercises its pre-4.0-bash branch on the
`macos-latest` CI leg -- is `could not check: CI coverage`, genuinely
unresolvable from a local review (`.github/workflows/tests.yml` pins no
bash version and the runner image's PATH ordering is not visible here);
no action needed beyond the gate already added, since it is correct on
either branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScdCn6Xq622o2cRQhzVhi5
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.

SessionStart: fork tax -- $(config) x13, lib-slug sed build x22, log's printf|tr -- replace with builtins (Part of #660)

1 participant