Skip to content

Fix #1056: fewer forks and a bounded retry on SessionEnd's flush - #1095

Merged
fdaviddpt merged 5 commits into
mainfrom
fix/1056
Nov 1, 2026
Merged

fdaviddpt merged 5 commits into
mainfrom
fix/1056

Conversation

@fdaviddpt

@fdaviddpt fdaviddpt commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Windows/MSYS sessions starting or ending together exhaust the fork table (fork: retry: Resource temporarily unavailable, #1056). This removes avoidable forks on the SessionEnd hot path (and in save-session.sh/lib-lock.sh, which SessionStart's own background recovery call also goes through) and adds one bounded retry to SessionEnd's save.

Closes #1056
Refs #660 -- #660's own thread (erdogan-deniz, 2026-10-19) names fewer forks on the foreground path as the remaining lever for its SessionStart latency measurements; this PR does not touch session-start-hook.sh itself, but the shared save-session.sh/lib-lock.sh fork reductions below also run on SessionStart's own background recovery path.

What changed (five commits)

  1. scripts/save-session.sh: removed six dirname "$0" forks (one per sibling library sourced) by switching to parameter expansion (_SAVE_SCRIPT_DIR="${BASH_SOURCE[0]%/*}"), matching the pattern already used by session-start-hook.sh/session-end-hook.sh/post-tool-hook.sh/user-prompt-hook.sh (post-tool-hook pays the same resolution prefix on every tool call #230).
  2. scripts/session-end-hook.sh: replaced several $(_remember_date ...) command substitutions (each forks a subshell even when _remember_date itself is forkless) with the existing _remember_date_into helper, which writes directly into a named variable.
  3. scripts/lib-lock.sh (found during self-review, same bug class, in the exact lock-acquire path save-session.sh's flush takes 3+ times per run): removed an unconditional dirname "$_dir" fork and an unconditional date +%s fork from _lock_acquire_impl()'s uncontended fast path, deferring the deadline computation to first actual contention.
  4. Round 2 self-review, in response to a further review pass: SessionEnd's bounded retry used to fire on ANY nonzero exit from save-session.sh --force, which could (a) double-count a summarizer failure against thresholds.max_summary_failures and (b) turn a failure in the position write itself -- after now.md's append had already succeeded -- into a genuine duplicate save, because the retried run re-extracts and re-summarizes the same unadvanced span. Fixed at the source: save-session.sh now reserves one exit code, EXIT_RETRYABLE_BEFORE_WRITE (75), for an unexpected failure that struck before now.md was touched -- the only thing a blind retry is safe to repeat -- and every deliberate outcome (lock timeout, invalid session id, summarizer failure, write error, cooldown, nothing-to-save) keeps its ordinary 0/1. session-end-hook.sh's retry is now gated on that one code instead of "any nonzero exit". A second, independent defence (PENDING_POSITION_MARKER) catches the same half-success for a retry the exit code cannot gate at all -- a human re-running --force by hand, or a later cooldown tick: the next invocation recovers the interrupted position write without re-appending.
  5. scripts/lib-lock.sh again: commit 3 above introduced _lock_parent="." as a quoted lone-dot literal, which the plugin directory's own scanner (tests/test_scanner_shapes_source_898.py) correctly flagged -- caught by this PR's own CI, not by review. Rewritten via printf -v with octal escape 056, the same convention every other dirname-no-slash fallback in this repo already uses.

Before/after fork counts

  • save-session.sh's sourcing preamble: 6 dirname forks -> 0.
  • lib-lock.sh's _lock_acquire_impl: 1 dirname fork + 1 unconditional date fork per acquisition -> 0 dirname and 0 date on the uncontended path (still 1 date fork on first contention, same as before, just deferred).
  • session-end-hook.sh: at least 2 unconditional $(_remember_date) subshell forks on the unconditional hot path -> 0 (moved to _remember_date_into, no subshell).

Tests (red before, green after)

  • tests/test_save_session_spawn_reduction_1056.py -- RED: save-session.sh still forks dirname to locate its sibling libraries (6 hits). GREEN: 3 passed.
  • tests/test_session_end_retry_1056.py -- RED (round 2): the retry fired on exit 1 (a plain deliberate failure) and on a persistent exit 1, not just the new retryable code. GREEN: must-fire case on exit 75, a clean-success control, the persistent-75 bound, and two new must-NOT-retry cases (exit 1, exit 0).
  • tests/test_save_session_exit_codes_1056.py (new, round 2) -- RED: an unexpected early failure exited whatever raw code the broken dependency returned, not 75; a summarizer failure and a lock timeout had no assertion distinguishing them from 75; the half-success scenario duplicated the append on a second run. GREEN: all four cases, including the PENDING_POSITION_MARKER recovery test (append happens once, position write fails, next run recovers the position without re-appending).
  • tests/test_lock_fork_reduction_1056.py -- RED: still forks dirname and/or date for values nothing ends up reading. GREEN, combined with the full lock suite: 85 passed.
  • Combined targeted run across every touched/related suite plus the brief's own mandated guard set (test_hot_path_cost_pin_330.py, test_session_start_spawn_reduction_679.py, test_locale_ranges_695.py, test_arith_base_lint_332.py, test_scanner_shapes_source_898.py, test_strip_shell_comments_900.py, test_release_branch_check_900.py, test_windows_skip_triage_497.py): green. Also re-run under /bin/bash 3.2.57 (Apple's shipped interpreter) specifically.
  • Not run here: the repository's full pytest suite -- CI is the full-suite gate (repo CLAUDE.md), run across 3 OSes and 4 interpreters. CI is now 19/19 green, including a windows-latest leg that was genuinely red for two rounds (the scanner finding above, and the retry-test finding below) before this PR's own CI caught and fixed each.

Cross-platform claims

Observed (this darwin host, both homebrew bash 5.3 and /bin/bash 3.2): every test above, both fork-count reductions and the retry/recovery logic end-to-end with stubs. Also observed on windows-latest CI (not reasoned): the lib-lock.sh scanner fix above, confirmed green there.

Reasoned, not reproduced on a real machine: the actual Windows/MSYS fork-exhaustion scenario #1056 reports was never reproduced on a live Windows/MSYS host -- no such environment is available on this machine, and CI's windows-latest runner is not the same MSYS-based Git Bash the reporter's own error string names. The fix rests on fewer forks per invocation (directly measured here, generalizing to Windows by the same mechanism the issue names) and a platform-agnostic retry/recovery mechanism.

A genuine Windows-portability attempt, and what it found: tests/test_session_end_retry_1056.py was converted to resolve_bash() (no blanket skip, the #432 pattern) and pushed to let windows-latest CI test the claim rather than assume it. It failed for real: session-end-hook.sh's own detached-relaunch fork (nohup bash "${BASH_SOURCE[0]}" ...) hardcodes the bash binary name internally, which this test's outer _run_hook() cannot influence. Fixing that is a session-end-hook.sh production-code question (what that fork should resolve to on a real Windows host), out of this issue's own scope, so this reverted to a blanket skip and recorded the finding in docs/windows-skip-triage.md (not-convertible) rather than claim coverage the module does not have. tests/test_save_session_spawn_reduction_1056.py's own dirname-fork-count guard is separately skipped entirely on windows-latest (Git's bash.exe prepends /usr/bin ahead of the shim dir, a documented limitation shared with #679) -- so the one platform #1056/#660 are about still has no automated regression guard for the fork-COUNT claim specifically, even though the fork-REDUCTION and retry-GATING code itself is now exercised and green on every CI leg including windows-latest.

🤖 Generated with Claude Code

[AI-generated]

fdaviddpt and others added 2 commits November 1, 2026 15:55
save-session.sh forked `dirname "$0"` six times every invocation to locate
its own sibling libraries, on both the SessionStart recovery path and the
SessionEnd flush -- paid once per session, and under #1056's own scenario
(many Claude Code windows in one project starting/ending together) paid
N times simultaneously, competing for the same exhausted MSYS fork table
that produces "fork: retry: Resource temporarily unavailable". Replaced
with the same parameter-expansion pattern the four hooks already use
(#230).

session-end-hook.sh's own "$(_remember_date ...)" command substitutions
each forked a subshell even though _remember_date itself is forkless on a
warm bash -- replaced with _remember_date_into, which already exists for
exactly this (lib-clock.sh).

SessionEnd's backgrounded flush now retries once, after a short sleep,
when save-session.sh exits nonzero -- not conditioned on recognizing
MSYS's own error text, which is not a stable contract across versions.
save-session.sh's own cooldown/position bookkeeping only advances on an
actual successful save, so retrying any failure once is safe and costs at
most one harmless extra invocation.

TDD: tests/test_save_session_spawn_reduction_1056.py pins the dirname
fork count to zero with a positive control proving the shim harness can
see a dirname fork at all; tests/test_session_end_retry_1056.py proves
the retry fires on failure, does not fire on a clean run, and gives up
after exactly one retry (not an unbounded loop).

Observed: red before the fix (6 dirname forks measured; 2/3 retry tests
failing with invocation count 1 not 2), green after. Targeted suites
(save-session gates, session-end hook, spawn-reduction/scanner guards)
and the mandated guard set pass under both bash 5.3 (homebrew) and bash
3.2 (/bin/bash, forced first on PATH) on this darwin host -- observed on
this platform only; the Windows/MSYS fork-exhaustion scenario itself is
reasoned from the issue's own report, not reproduced here.

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

Two findings from the Explore reviewer against 254cac9, both real instances
of the same bug class this issue exists to fix, missed in the first pass
because lib-lock.sh's own acquire path was not audited:

- _lock_acquire_impl() forked `dirname "$0"` -- sorry, `dirname "$_dir"` --
  on every single lock acquisition, used by save-session.sh at least three
  times per flush (the save lock, the staging lock, the NDC commit lock).
  Replaced with the same parameter-expansion pattern this issue already
  applied to save-session.sh's own sourcing preamble.
- The same function forked `date +%s` unconditionally to compute a
  deadline, even on the fully uncontended fast path where the first
  `mkdir` succeeds immediately and the deadline is never read. Deferred to
  first actual need -- only computed once contention is detected -- which
  shifts the effective timeout later by at most one steal/adopt attempt,
  never earlier.

One finding from the oss:auditor against the same commit: the win32 skip
reason on tests/test_save_session_spawn_reduction_1056.py claimed "the
byte-identity-free static check below still runs there", referring to a
check that does not exist in that file (likely copied from the shape of
test_session_start_spawn_reduction_679.py's own skip comment without the
claim being true here). Corrected to say plainly that this file's own
dirname-fork-count guard has no coverage on win32.

New test: tests/test_lock_fork_reduction_1056.py, same TDD shape as the
rest of this issue -- a positive control proving the shim harness can see
a dirname/date fork, paired with the assertion that an uncontended
lock_acquire makes neither. Red before (both dirname +%s and date +%s
forked), green after. Full lock suite (test_lock_primitive.py,
test_lock_timing.py, test_cross_host_lock_contract_491.py,
test_ndc_commit_lock.py, test_slug_index_297.py) passes alongside it --
85 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@fdaviddpt fdaviddpt changed the title Fix #1056, #660: fewer forks and a bounded retry on SessionEnd's flush Fix #1056: fewer forks and a bounded retry on SessionEnd's flush Nov 1, 2026
fdaviddpt and others added 3 commits November 1, 2026 16:39
…recover a half-written position without duplicating

Self-review on PR #1095 found that retrying on ANY nonzero exit from
save-session.sh --force was unsafe: a summarizer failure already counts
itself against thresholds.max_summary_failures (so a retry doubled that
count and could drop a span for good in one SessionEnd), and a failure
during the position write AFTER now.md's append had already succeeded was
retried into a genuine duplicate save, because the retried run re-extracts
and re-summarizes the same unadvanced span.

save-session.sh now reserves EXIT_RETRYABLE_BEFORE_WRITE (75) for an
unexpected failure its own ERR trap catches before now.md is touched --
the only thing a blind retry is safe to repeat. Every deliberate outcome
(lock timeout, invalid session id, summarizer failure, write error,
cooldown, nothing-to-save) keeps its ordinary 0/1. session-end-hook.sh's
retry is now gated on that one code instead of "any nonzero exit", and its
own comment claiming a retry "costs one harmless extra invocation, not a
duplicate save" is corrected.

A second, independent defence (PENDING_POSITION_MARKER) catches the same
half-success for a retry the exit code cannot gate at all -- a human
re-running --force by hand, or a later cooldown tick: the next invocation
recovers the interrupted position write without re-appending.

Also: dropped changelog.d/660.fixed.md (another lane owns #660), retitled
the PR to drop #660, and removed the body's claim that this PR touches the
SessionStart hot path (it does not -- only the shared save-session.sh/
lib-lock.sh fork reductions run on SessionStart's own background recovery
call). test_session_end_retry_1056.py now resolves a real Git-Bash binary
instead of a blanket win32 skip (#432's own route).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…windows-latest failed it for a real reason

Pushed the resolve_bash()-based skip and let CI test the claim rather than
assume it, per this round's own instruction. windows-latest failed all
three original tests with genuine assertion failures, not a missing
interpreter: session-end-hook.sh's own detached-relaunch fork hardcodes
the bash binary name internally, which this test's _run_hook() cannot
reach from the outside -- resolving bash for the OUTER hook invocation
does not change what the hook forks for itself. Fixing that is a
session-end-hook.sh production-code question, out of this issue's scope,
so this reverts to a blanket win32 skip and records the finding in
docs/windows-skip-triage.md (not-convertible), per the fallback this
repo's own convention names for exactly this outcome.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…earlier round

eebbbe8 (this branch's own self-review commit) introduced `_lock_parent="."`
as a quoted lone-dot literal, which tests/test_scanner_shapes_source_898.py
correctly flags: the plugin directory's own scanner can misread a literal
"." string value as a `.` (source) command (#898 round 8). Every other
dirname-no-slash fallback in this repo already writes that byte via
`printf -v` with octal escape 056 (lib-memory-context.sh's REMEMBER_ROOT,
write-handoff.sh's _WH_REMEMBER_ROOT, capture-gap-check.sh) -- this just
brings lib-lock.sh's new one into line with that existing convention.

Found while watching this PR's CI: this was failing every pytest leg
(macOS, Linux, Windows alike) on its own, unrelated to round 2's retry/
exit-code work above.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@fdaviddpt
fdaviddpt merged commit dfff7e6 into main Nov 1, 2026
19 checks passed
@fdaviddpt
fdaviddpt deleted the fix/1056 branch November 1, 2026 18:10
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.

Windows/MSYS: fork: retry: Resource temporarily unavailable in hooks when several sessions start or end together

1 participant