Skip to content

Part of #1002: widen the Windows detach watchdog and narrow the double-save race it can trigger - #1012

Merged
fdaviddpt merged 3 commits into
mainfrom
fix/1002-watchdog-race
Oct 10, 2026
Merged

fdaviddpt merged 3 commits into
mainfrom
fix/1002-watchdog-race

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Part of #1002.

Round 4 of the ongoing Windows background-save fix. Prior rounds (merged: #1004, #1010) replaced the visible nohup console with a hidden wscript.exe launcher and gave it a watchdog bound so a disabled or broken WSH host cannot hang the save forever. The push-triggered CI run on main after #1010 merged showed that bound (5s, set in round 3 off a 5-run sample) was not representative of a loaded Windows runner: run #38062128176 / job #114242348418 recorded a healthy hidden-route call taking 5.13s (passed) right next to a sibling call that took 6.03s and got killed by the watchdog (RC=137).

What changed:

  • scripts/lib-detach.sh: raised the watchdog bound 5s -> 15s, overridable via a new _REMEMBER_DETACH_WIN_WATCHDOG_SECS env var so a test can force a deterministic kill without waiting out the production bound.
  • A watchdog kill (rc=137) is not a structural this-host-cannot-do-this verdict the way a missing wscript.exe/cygpath is, so it no longer shares the 1-hour unusable cache TTL. It also is not left uncached (which would reopen a stalls-every-save-forever pathology for a persistently slow host) -- it gets its own short-lived slow verdict with a 5-minute TTL.
  • scripts/post-tool-hook.sh: because WshShell.Run detaches the real save from the wscript.exe process itself, killing wscript.exe via the watchdog does not necessarily stop a save that already started. The nohup fallback now checks PID_FILE for a live pid before double-launching, but only when the detach call returned exactly 137 -- never for a genuine structural failure, where PID_FILE cannot have changed and trusting it risks a rare pid-reuse false positive silently dropping a save.

This narrows, not eliminates, the double-save race: a pidwrap chain that is itself slow may not have written PID_FILE yet when the watchdog bound expires.

Testing: red-before-fix confirmed by temporarily reverting the PID_FILE check and rerunning test_post_tool_fallback_skips_when_hidden_route_already_claimed_pid_file (failed, double save reproduced); the positive-control test test_post_tool_fallback_still_fires_when_hidden_route_claimed_nothing stayed green throughout. All tests in tests/test_windows_hidden_detach_1002.py plus adjacent scanner/guard tests green locally (darwin, python 3.13.15) after both commits. Full suite not run locally per repo policy -- CI is the matrix gate across three OSes and four interpreters; CI on this PR is the gate.

Self-review: two rounds, an Explore subagent (4 findings, all fixed: the slow-cache TTL above, scoping the PID_FILE check to rc=137 specifically, softening closes to narrows in comments/docs/changelog, and a docs/windows.md paragraph that had gone stale) and a separate oss:auditor per-class audit (1 finding, fixed: a new test helper used os.kill(pid, 0), an idiom unsafe on Windows that this repo had already retired once elsewhere -- replaced with the existing tasklist-based cross-platform probe).

This is round 4 of an ongoing fix tracked across multiple PRs under #1002; prior rounds are still landing and the maintainer is tracking this across several pull requests, so this PR is deliberately left as Part of #1002 rather than a closing reference.

[AI-generated]

fdaviddpt and others added 3 commits October 10, 2026 17:39
… could trigger

main HEAD (PR #1010 squash) was RED on windows-latest/3.10: the 5s watchdog
bound round 3 sized off a 5-run sample (max 0.422s) did not hold under a
loaded CI runner. The same PR's own job (#114242348418) shows a healthy
hidden-route call taking 5.13s (passed) next to a sibling taking 6.03s and
getting killed (RC=137) -- OBSERVED, confirming the watchdog-kill hypothesis
rather than a genuine wscript.exe hang.

Raised the bound to 15s (REASONED margin over those two data points). More
importantly, a watchdog kill is no longer risky on its own:

- post-tool-hook.sh's nohup fallback now checks whether PID_FILE already
  names a live pid before launching a second, independent save -- closing
  a double-save race: WshShell.Run detaches the real command from
  wscript.exe's own process, so a watchdog kill of wscript.exe does not
  stop a save that already started.
- lib-detach.sh's hour-long "hidden route unusable" cache no longer treats
  a watchdog kill (RC=137) the same as a structural failure (missing
  wscript.exe/cygpath, RC=1) -- one slow call now costs exactly that call,
  not an hour of every save going through the slower nohup fallback.

tests/test_windows_hidden_detach_1002.py adds direct coverage for both,
using a stubbed wscript.exe and a new _REMEMBER_DETACH_WIN_WATCHDOG_SECS
override that lets the suite force a real watchdog kill in well under a
second. Confirmed red against the pre-fix post-tool-hook.sh (nohup fired
unconditionally, double save reproduced) before restoring the fix.

docs/windows.md and a changelog.d fragment record round 4.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… fix, fix a test platform idiom

Three findings from the Explore reviewer and one from oss:auditor against
590de9e, addressed before handoff:

- The rc=137 cache exception (never cache a watchdog kill) reopened the
  "stalls every single save, forever" pathology the TTL cache exists to
  remove, for a host that is persistently -- not just transiently -- slower
  than the watchdog bound. A watchdog kill now gets its own short-lived
  "slow" cache verdict (5 minutes) instead of either extreme: the structural
  failure's full hour, or no caching at all.
- The post-tool-hook.sh PID_FILE-liveness check now fires only when the
  detach call's own return code is specifically 137. A genuine structural
  failure (missing wscript.exe/cygpath) never changes PID_FILE during the
  call, so re-trusting it there risked a rare pid-reuse false positive that
  would silently DROP a save rather than merely race one -- worse than the
  bug being fixed.
- Code comments, docs/windows.md and the changelog fragment now say the
  double-save fix narrows the race rather than closes it: a pidwrap chain
  that is itself what is slow may not have written PID_FILE yet when the
  bound expires, in which case the old race still occurs.
- tests/test_windows_hidden_detach_1002.py's own _pid_alive helper used
  os.kill(pid, 0), which on Windows maps to CTRL_C_EVENT (a process-group
  broadcast, not a liveness probe) rather than a clean existence check --
  the same idiom this repo already retired once in
  test_session_end_log_names_488.py. Replaced with the same tasklist-based
  probe, since this test's own windows-latest CI leg is not skipped.

The rewritten test_detach_windows_watchdog_kill_caches_as_slow_not_unusable
exercises the new throttle directly: a watchdog kill publishes VERDICT=slow
(not unusable), a second call shortly after is short-circuited rather than
re-attempted, and a stale "slow" entry still expires and re-attempts, same
technique as the existing cache-ignores-stale-entry test.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The two Windows pytest legs failing on PR #1012
(test_post_tool_fallback_skips_when_hidden_route_claimed_a_live_pid)
asserted "PID_FILE's pid is not actually alive" even though the stub had
just written a live pid there. Root cause: the pid is bash's own "$!"
(an MSYS/Cygwin pid), but the test's _pid_alive probed it with tasklist,
which only resolves WINPIDs -- an MSYS pid there always reads as dead.
Confirmed by reading what each side actually does: the stub's wscript.exe
backgrounds a job inside bash and captures "$!"; the product
(post-tool-hook.sh) checks PID_FILE liveness with a plain "kill -0 $pid"
run inside the same MSYS bash that wrote it, so the product was already
self-consistent -- only the test's liveness probe used the wrong
namespace.

Fixed both _pid_alive probes that check an MSYS-pid PID_FILE through
tasklist: the new #1002 round-4 test in
tests/test_windows_hidden_detach_1002.py, and the sibling in
tests/test_session_end_log_names_488.py, whose save-session.pid is
written the same way ("echo $! > ...") by session-end-hook.sh -- same
instance of the bug class, previously silent because it only gated a
wait loop rather than an assertion. Both now shell out to the resolved
MSYS BASH and run "kill -0 $pid" instead of asking a native Windows tool
to resolve an MSYS pid.

Verified the product side does not make this mistake anywhere: every
PID_FILE read in post-tool-hook.sh is checked via "kill -0" inside bash,
never against a WINPID-based tool.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@fdaviddpt
fdaviddpt merged commit af218ac into main Oct 10, 2026
34 checks passed
@fdaviddpt
fdaviddpt deleted the fix/1002-watchdog-race branch October 10, 2026 17:36
fdaviddpt added a commit that referenced this pull request Oct 10, 2026
…allowlist, document the Windows skip

Rebasing fix/913 onto main (after #1010/#1012's Windows detach watchdog and
rc=137 double-save guard) surfaced a real regression on CI that neither the
targeted local run nor lane_setup's guard sweep could see:
tests/test_hot_path_cost_pin_330.py's own #353/#395 sidecar-trust pins failed
on every leg, because the #913 cooldown-before-scan reorder had nested the
WHOLE #353 "last saved position" lookup (and the DELTA it feeds) inside the
same `if IN_COOLDOWN=false` block that gates the new incremental scan -- not
just the scan itself. Since test_hot_path_cost_pin_330.py's own fixture
always leaves a recent save-cooldown marker set, IN_COOLDOWN was always true
in that fixture, so the #353 branch (and its own regression tests) never ran
at all under it.

Fixed by scoping the `if [ "$IN_COOLDOWN" = false ]` wrapper to just the scan
(through the SCAN_SIDECAR write) again, restoring the #353 lookup and the
final DELTA assignment to run unconditionally as they did before #913 ever
touched this file. The sidecar's own upper-bound sanity check now skips
itself (rather than comparing against a never-computed CURRENT_LINES of 0)
when the scan was skipped, via one added `[ "$IN_COOLDOWN" = false ] &&`.
#913's own win (incremental, not whole-transcript, line counting) and the
cooldown-skips-the-scan behaviour (#1011's own motivation) are both still
intact; only the accidental, broader skip is undone.

Re-pinned tests/test_locale_ranges_695.py's ALLOWLIST line numbers for the
two shifted ASCII-only basename-sanitiser ranges (860->868, 955->970).

Documented the new tests/test_post_tool_incremental_scan_913.py's win32
blanket-skip in docs/windows-skip-triage.md (not-convertible: same
bash-hook-subprocess shape as test_post_tool_fast_path_350.py, plus a
spawn-counting assertion measured only against macOS system bash) -- CI's
own tests/test_windows_skip_triage_497.py was failing on every leg for its
absence.

Re-measured tests/test_post_tool_fast_path_350.py's own
FAST_PATH_SPAWN_MEASURED: already stale at 6 before this PR (an earlier,
separate #913 PR had removed the slug/cygpath fork this constant's comment
still described, without updating the number); corrected to the measured 5.

Closes #913.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
fdaviddpt added a commit that referenced this pull request Oct 10, 2026
…can under save-cooldown (#1013)

* Fix #913: make post-tool-hook's transcript line count incremental, not O(session length)

`wc -l < "$TRANSCRIPT"` used to read the whole transcript on every tool
call, so the hook got slower every turn of a long session. This stores a
(byte offset, line count) sidecar keyed by the transcript's own basename
and reads only the bytes appended since the last call via `tail -c
+OFFSET`, whose own leading byte doubles as a validator against a shrunk
or rewritten transcript -- a shorter read, or a first byte that is not the
expected newline, falls back to a full recount. A half-written last line
(no trailing newline yet) is never counted and never advances the offset.

The cooldown check that decides whether a save can fire at all now runs
BEFORE this scan rather than after it, so a tool call inside the
post-save cooldown window skips the scan entirely -- a fork avoided here
on an affected Windows 11 25H2 build (#1011) is a kernel Token object
that never leaks, not merely latency saved. Which saves fire, and at
what threshold, is unchanged.

Measured on macOS bash 3.2.57, the shared fast-path fixture
(tests/test_post_tool_fast_path_350.py) with cooldown active: before 5
spawns (head, ls, wc, mv, date), after 4 (head, ls, mv, date) -- wc is
gone entirely. Without cooldown, below the save threshold: before 4
(head, ls, wc, mv), after 4 (head, ls, tail, mv) -- same fork count, now
O(delta) instead of O(session length).

tests/spawn_counting.py's shared COUNTED list gains `tail`, which it did
not carry before this change -- a tail-based fix would otherwise have
passed every existing fork-count assertion while the harness itself
stayed blind to the fork it claims to measure.

tests/test_post_tool_incremental_scan_913.py pins the new mechanism and
its named edge cases: incremental reads only the appended bytes, the save
decision is unchanged across several incremental calls, a half-written
last line is not counted until complete, a shrunk transcript falls back
to a full recount, a rewritten transcript (same offset, different
content) falls back too, and cooldown skips the scan entirely.

tests/test_locale_ranges_695.py's ALLOWLIST is re-pinned to the shifted
SESSION_ID bracket-range checks and gains one entry for the new sidecar
key's own sanitiser (same ASCII-only charset, same reason).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #913 self-review: validate the scan sidecar's two fields as a pair

A self-review spawn found that a write interrupted between OFFSET and
LINES (OOM, disk full, a kill mid-printf) can leave a syntactically valid
OFFSET -- a real prior scan position, so the newline-validation in
_pt_scan_lines passes -- paired with a missing/empty LINES field. The
per-field validation defaulted only the missing field to 0, silently
pairing a real byte offset with a wrong line count, undercounting every
line that existed before it. Both fields are now invalidated together on
any parse failure, forcing the same full recount an absent sidecar
already gets.

tests/test_post_tool_incremental_scan_913.py gains a regression test that
reproduces the exact partial-write shape (a real OFFSET, a truncated
LINES field) and asserts the sidecar recovers the true count rather than
reporting zero.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* trap(#913): log auditor finding on tail exit-status masking in scan fallback (non-blocking)

Self-review's oss:auditor spawn found that `_pt_scan_lines`'s
fallback-to-full-recount branch cannot distinguish a genuine
shrink/rewrite from a transient `tail` read failure, because the
command substitution's exit status is masked by the trailing `printf`
needed to preserve a trailing newline through `$()`. Ranked non-blocking
and self-healing (next call recounts fully); left for the curator.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #913 CI round: restore #353 sidecar-trust under cooldown, re-pin allowlist, document the Windows skip

Rebasing fix/913 onto main (after #1010/#1012's Windows detach watchdog and
rc=137 double-save guard) surfaced a real regression on CI that neither the
targeted local run nor lane_setup's guard sweep could see:
tests/test_hot_path_cost_pin_330.py's own #353/#395 sidecar-trust pins failed
on every leg, because the #913 cooldown-before-scan reorder had nested the
WHOLE #353 "last saved position" lookup (and the DELTA it feeds) inside the
same `if IN_COOLDOWN=false` block that gates the new incremental scan -- not
just the scan itself. Since test_hot_path_cost_pin_330.py's own fixture
always leaves a recent save-cooldown marker set, IN_COOLDOWN was always true
in that fixture, so the #353 branch (and its own regression tests) never ran
at all under it.

Fixed by scoping the `if [ "$IN_COOLDOWN" = false ]` wrapper to just the scan
(through the SCAN_SIDECAR write) again, restoring the #353 lookup and the
final DELTA assignment to run unconditionally as they did before #913 ever
touched this file. The sidecar's own upper-bound sanity check now skips
itself (rather than comparing against a never-computed CURRENT_LINES of 0)
when the scan was skipped, via one added `[ "$IN_COOLDOWN" = false ] &&`.
#913's own win (incremental, not whole-transcript, line counting) and the
cooldown-skips-the-scan behaviour (#1011's own motivation) are both still
intact; only the accidental, broader skip is undone.

Re-pinned tests/test_locale_ranges_695.py's ALLOWLIST line numbers for the
two shifted ASCII-only basename-sanitiser ranges (860->868, 955->970).

Documented the new tests/test_post_tool_incremental_scan_913.py's win32
blanket-skip in docs/windows-skip-triage.md (not-convertible: same
bash-hook-subprocess shape as test_post_tool_fast_path_350.py, plus a
spawn-counting assertion measured only against macOS system bash) -- CI's
own tests/test_windows_skip_triage_497.py was failing on every leg for its
absence.

Re-measured tests/test_post_tool_fast_path_350.py's own
FAST_PATH_SPAWN_MEASURED: already stale at 6 before this PR (an earlier,
separate #913 PR had removed the slug/cygpath fork this constant's comment
still described, without updating the number); corrected to the measured 5.

Closes #913.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
fdaviddpt added a commit that referenced this pull request Oct 10, 2026
* Part of #1011: re-apply the fork-reduction fix onto #913's incremental scan

A previous lane implemented #1011's fork-reduction half on a branch whose
merge-base predated #913 (which rewrote the same region of
post-tool-hook.sh to scan the transcript incrementally rather than with a
whole-file `wc -l`, and moved the save-cooldown check ahead of that scan).
This ports the same two fixes -- by hand, re-applied to the post-#913 code,
not cherry-picked -- and re-measures against what main actually does today.

Two forkless changes to post-tool-hook.sh's no-save path:

- The transcript lookup (`ls -t "$SESSION_DIR"/*.jsonl | head -1`) is now a
  glob-plus-mtime walk, falling back to `ls -t` only on a genuine
  same-second mtime tie -- bash 3.2's `-nt` compares mtimes at whole-second
  resolution, so two transcripts written moments apart inside the same
  second can tie in either direction even though the filesystem's own
  finer-grained timestamp orders them correctly. An unresolved tie would
  silently keep whichever same-second file lexical glob order visited
  first, which is exactly the misattribution #204/#129 already named as
  worse than capturing nothing.
- The capture-alive marker's atomic write (`mv -f`) is skipped whenever it
  already holds the current session id -- every tool call after the first
  in a session -- but still WRITTEN in place (no tmp file, no `mv`, so no
  fork added back) rather than doing nothing at all: doctor.sh reads this
  marker's mtime, not just its content, as "is PostToolUse still firing",
  and skipping the write outright would freeze that mtime at a session's
  first tool call.

Measured on real `/bin/bash` 3.2 (not the Homebrew bash 5 normally ahead of
it on PATH) against current `main`, which already carries #913's own
spawn-shape change (`wc` -> `tail`, cooldown-gated): the cooldown path
dropped from 4 spawns (`ls`, `head`, `mv`, `date`) to 1 (`date` only); the
below-threshold path from 4 spawns (`head`, `ls`, `mv`, `tail`) to 1
(`tail` only).

Re-pinned to the newly measured values, all re-measured on real bash 3.2,
none copied from the pre-#913 lane:
- tests/test_post_tool_fast_path_350.py: FAST_PATH_SPAWN_MEASURED 5 -> 1
- tests/test_post_tool_hook_spawns.py: POST_TOOL_SPAWN_MEASURED 19 -> 14
- tests/test_hot_path_cost_pin_330.py: READ_BUILTIN_MEASURED 17 -> 18,
  SIDECAR_READ_BUILTIN_MEASURED 18 -> 19 (the new capture-alive
  `read -r _ptl_capture_current` builtin)
- tests/test_locale_ranges_695.py: re-pinned the ALLOWLIST line numbers the
  edits shifted (719/762/868/970 -> 759/802/940/1042)

Several existing tests used `ls` spawning as the positive control for "the
hook looked for a transcript" -- no longer valid once that lookup is
forkless on the common path, and the incremental scan it used to also
prove is itself skipped entirely under an active save-cooldown (#913). Both
affected files (test_post_tool_fast_path_350.py,
test_post_tool_incremental_scan_913.py) now check the capture-alive marker's
existence instead: a filesystem effect written unconditionally for any run
that found a transcript at all, reachable whether the lookup or the scan
forked or not.

Added two regression tests: the same-second mtime-tie fallback (red
confirmed by reverting the tie-detection branch in place and re-running),
and the capture-alive marker's mtime still advancing on an unchanged
session id (doctor.sh's own "is PostToolUse still firing" check).

#913's own incremental-scan sidecar, the cooldown-before-scan ordering, the
#353 lookup running unconditionally, and #1012's Windows detach
watchdog/rc=137 PID_FILE guard are all untouched -- confirmed by diff hunk
boundaries, not just by intent.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Part of #1011 self-review: fix three findings from Explore's own review

Spawned Explore and oss:auditor against commit 401c733 (the fork-reduction
port). oss:auditor returned NO FINDINGS; Explore found three real,
low-severity issues, none touching the tree (confirmed via tree_snapshot
before/after and the auditor's own independent compare):

1. A comment just above the forkless glob-walk still described the common
   path as an "ls -t/slug-match dance" after #1011 made that path forkless
   -- stale prose left behind when the two surrounding comment blocks were
   rewritten but this one in between was not. Reworded to describe the
   actual behaviour.

2. The same-second mtime-tie flag (_ptl_jsonl_tie) stayed set for the rest
   of the glob walk even after a later, unambiguous comparison found a
   strictly newer file -- so the walk paid for the `ls -t` fallback in a
   case (3+ live transcripts, an early tie superseded by a clear later
   winner) that was never actually ambiguous by the time the walk ended.
   Not a correctness bug (`ls -t` always recomputes the right answer), but
   it contradicted the design's own claim to pay the fallback "only on a
   genuine same-second tie". Fixed by clearing the flag whenever a later
   comparison produces an unambiguous winner.

3. The capture-alive in-place write (the `else` branch, content unchanged)
   used a plain `>` redirect, which truncates the file to zero bytes before
   `printf` writes anything -- a real (if brief) window in which a
   concurrent PostToolUse invocation's own `read` could see an empty marker
   and misread it as a session change. Fixed with `1<>`, which opens the
   file for read+write with no truncation; safe specifically because this
   branch only runs when the new bytes are byte-identical in length to what
   is already there, so there is no length change for the lack of atomicity
   to expose.

Re-pinned tests/test_locale_ranges_695.py's ALLOWLIST line numbers again
(759/802/940/1042 -> 767/810/957/1059), since both the comment fix and the
longer in-place-write comment shift lines above them. Full targeted suite
(499 tests, the same set as the prior commit) re-run green on real
/bin/bash 3.2 after every change in this commit.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
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