Skip to content

fix(bin): bound lock stealing to one .steal level and refuse uncreatable locks - #2796

Open
benlamlih wants to merge 16 commits into
kunchenguid:mainfrom
benlamlih:fm/fm-lock-steal-recursion
Open

benlamlih wants to merge 16 commits into
kunchenguid:mainfrom
benlamlih:fm/fm-lock-steal-recursion

Conversation

@benlamlih

@benlamlih benlamlih commented Aug 22, 2026 •

Copy link
Copy Markdown

Intent

Fix the conflicts on #2796 so it can merge.

The PR is "fix(bin): bound lock stealing to one .steal level and refuse uncreatable locks" on branch fm/fm-lock-steal-recursion. It is open, not a draft, and GitHub reports it dirty against main.

What the PR does, because you must not change its behaviour while resolving:
fm_lock_try_acquire in bin/fm-wake-lib.sh serialized a stale-owner reclaim through a steal mutex by calling itself with "$lockdir.steal". When the steal lock itself looked stale it recursed on "$lockdir.steal.steal", with no depth bound and no base case, walking down a chain of .steal suffixes until the path exceeded the filesystem limit. It was hit for real on this machine while it was out of disk space, filed as issue #2787. The fix bounds the steal to exactly one level, and makes a lock that cannot be created refuse rather than proceed, because two sessions both believing they hold the home's session lock is the exact failure the mechanism exists to prevent.

Deliberate decisions already taken on this PR, which stand and must be preserved:

  • The steal mutex is kept. Removing it to remove the recursion was explicitly ruled out; fm_autoarm_release_abandoned depends on its serialization.
  • Refusing to proceed when the lock cannot be acquired is the intended behaviour, not a missing fallback.
  • A failure of the underlying primitive is reported distinctly from a lock that is merely held.
  • The integer-expression symptom reported alongside the original bug was already fixed separately, was verified, and is deliberately out of scope. Do not re-fix it and do not report it as a finding.

What Changed

  • fm_lock_try_acquire in bin/fm-wake-lib.sh no longer calls itself on "$lockdir.steal". It now reclaims a stale owner through a single steal mutex using a new non-recursive fm_lock_try_acquire_leaf, which claims a stale lock by renaming it aside. The steal mutex still serializes fm_autoarm_release_abandoned, which now also checks that it still owns the steal mutex before going on. Chains of .steal directories left by the old recursive code are cleared one level at a time, stopping at the first live or fresh level. FM_LOCK_LEGACY_STEAL_SCAN_MAX (default 8) caps how many levels are walked. A leftover steal mutex next to a missing primary lock is now reclaimed instead of being read as a held lock.
  • When the filesystem refuses to create a lock (disk full, read-only, or parent not writable), acquisition refuses and does not proceed. A new FM_LOCK_FAIL_REASON tells unavailable apart from held, working from the ln -s error and whether the path exists. If a creation race's winner releases the lock before the loser checks, the loser retries once instead of reporting a refusing filesystem. The explanation is printed on stderr, throttled by FM_LOCK_UNAVAILABLE_REPORT_EVERY (default 100).
  • Callers now report unavailable distinctly. fm-watch.sh exits nonzero saying no watcher is running and none was started. The Claude Stop auto-arm prints on stderr that supervision is not running for this home, and still exits 0. The turn-end guard (block budget), the cycle-ledger writes in fm-watch-arm.sh, the watch-delivery record in fm-push-transition-lib.sh and herdr session cleanup each name the record or lock the filesystem refused, instead of passing silently or calling it busy. docs/configuration.md and docs/watcher-continuity.md document the new knobs and behaviour, and the lock, auto-arm, turn-end, watch-arm, herdr-cleanup and supervision-events test suites gain coverage for them.

Risk Assessment

⚠️ Medium: The merge resolution keeps every stated decision: the steal mutex is kept and bounded to one level through fm_lock_try_acquire_leaf, an uncreatable lock refuses, and the unavailable reason stays separate from held, including ahead of main's eviction loop. I found no conflict markers and no concrete defects, but the branch changes a concurrency-sensitive lock primitive that every session-lock caller depends on.

Testing

I ran every test file the PR touches on the merge commit. That includes the bounded-steal, unavailable-lock and live-holder tests, and main's test that evicts a watcher whose beacon stalled past the hard bound. All passed except one watch-arm test that fails intermittently; the same test fails at a similar rate on an untouched copy of base 1a814e4, so it is not caused by this merge. I also ran three manual CLI scenarios and saved a transcript. In the first, a lock whose .steal mutex was also stale was acquired without creating a .steal.steal chain. In the second, a lock that couldn't be created was refused and reported as unavailable. In the third, the merged fm-watch.sh loop exits 1 with its 'no watcher is running' message when it can't create its lock. Overall result: the PR's behaviour is preserved. The temporary base copy and scratch directories were deleted and the worktree is clean.

Evidence: Manual CLI transcript: bounded steal, unavailable refusal, watcher refusal in the merged loop

Scenario 1 (dead-pid lock + dead-pid .steal): acquire rc=0; paths: .contend.lock, .contend.lock.owner.* (no .steal.steal) Scenario 2 (lock parent not writable): fm_lock: … cannot create the lock and none exists to reclaim …; refusing to acquire acquire rc=1 reason=unavailable held_pid=none; steal paths created: 0 Scenario 3 (fm-watch.sh, state dir not writable): watcher: cannot create …/.watch.lock - the filesystem refused the operation …; no watcher is running and none was started. fm-watch.sh exit=1

$ # Scenario 1: primary lock AND its .steal mutex both held by a dead pid (the #2787 trigger)
acquire rc=0 holder=21103 (self=21103)
lock-related paths after acquire (no .steal.steal chain):
.contend.lock
.contend.lock.owner.YxfXmP

$ # Scenario 2: lock parent not writable (stand-in for out-of-disk / read-only)
fm_lock: /var/folders/0y/_6sdnhx150sbz5mvn5plrshm0000gn/T/tmp.JlzD2duiUO/ro/session.lock: cannot create the lock and none exists to reclaim - the filesystem refused the operation (out of space, read-only, or not writable); refusing to acquire
acquire rc=1 reason=unavailable held_pid=none
steal paths created: 0

$ # Scenario 3: bin/fm-watch.sh with an uncreatable watcher lock (merged retry/eviction loop)
fm_lock: /var/folders/0y/_6sdnhx150sbz5mvn5plrshm0000gn/T/tmp.JlzD2duiUO/wstate/.watch.lock: cannot create the lock and none exists to reclaim - the filesystem refused the operation (out of space, read-only, or not writable); refusing to acquire
watcher: cannot create /var/folders/0y/_6sdnhx150sbz5mvn5plrshm0000gn/T/tmp.JlzD2duiUO/wstate/.watch.lock - the filesystem refused the operation (out of space, read-only, or not writable); no watcher is running and none was started.
fm-watch.sh exit=1
Evidence: Test-run log for the PR's test files
FM_TEST_BEGIN 2026-09-25T08:44:33Z tests/fm-watcher-lock.test.sh family=watcher-wake-lock expected_gate_skip=none
FM_TEST_BEGIN 2026-09-25T08:44:33Z tests/fm-watch-arm.test.sh family=watcher-wake-lock expected_gate_skip=none
FM_TEST_BEGIN 2026-09-25T08:44:33Z tests/fm-turnend-guard.test.sh family=watcher-wake-lock expected_gate_skip=none
FM_TEST_BEGIN 2026-09-25T08:44:33Z tests/fm-supervision-events.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - handle_push_transition: a blocked crew enqueues a stale wake naming its window and wakes the supervisor
ok - handle_push_transition: enqueue failure cannot commit the Herdr dedupe marker
ok - handle_push_transition: a declared-pause crew is absorbed (no fast wake), left to the poll loop's long cadence
ok - handle_push_transition: a captain-held crew is absorbed (no fast wake), left to the poll loop's long cadence
ok - event_wait_or_sleep: herdr windows go on the event pane list, but kind=secondmate endpoints are excluded
ok - event_wait_or_sleep: one cached capability probe owns validation across bounded waits
ok - event_wait_or_sleep: a home with no push-capable window is inert (sleeps POLL, never touches the event path)
ok - event_wait_or_sleep: consecutive event-path failures disable the fast-path and revert to pure polling (fail-closed)
ok - watch_delivery_publish: a delivery lock the filesystem refuses is reported, never silently dropped
ok - watch_delivery_publish: an ordinary delivery record still publishes silently
# fm-supervision-events.test.sh: all assertions passed
FM_TEST_END 2026-09-25T08:44:34Z tests/fm-supervision-events.test.sh exit=0 duration_ms=1257 gate_skip=false
ok - watch-arm: an attached arm reports the wake its cycle delivered instead of a false failure
ok - watch-arm: a delivered wake consumed by the handling turn still closes the attached arm cleanly
ok - watch-arm: a cycle record the filesystem refused is reported without failing a delivered wake
ok - watch-arm: a predecessor successor link the filesystem refused is reported, not silent
ok - watch-arm: an unusable launch confirm window refuses to arm by name
ok - watch-arm: a disposable validation checkout refuses to arm
not ok - watcher pid 35915 outlived its deleted state directory
FM_TEST_END 2026-09-25T08:45:00Z tests/fm-watch-arm.test.sh exit=1 duration_ms=26944 gate_skip=false
ok - fm_supervision_unhealthy: false with no state/*.meta at all
ok - fm_supervision_unhealthy: true with in-flight task and no beacon ever
ok - fm_supervision_unhealthy: true with in-flight task and a beacon far outside the grace window
ok - fm_supervision_unhealthy: false with in-flight task and a fresh beacon
ok - fm_supervision_status: FM_SUP_QUEUE_PENDING tracks state/.wake-queue
ok - fm_supervision_needed: X-mode relay poll needs supervision
ok - fm_supervision_unhealthy: source-only home needs supervision
ok - fm_supervision_needed: a registered custom check needs supervision with no task in flight
ok - fm_supervision_needed: a registered check whose bytes drifted still needs supervision
ok - fm_supervision_needed: false for a check.sh with no registration binding
ok - fm_supervision_needed: a task PR poll without a trust binding is not a registered custom check
ok - fm_supervision_status: the relay shim is not counted as a registered custom check
ok - fm-turnend-guard: silent no-op with nothing in flight
ok - fm-turnend-guard: blocks when a fresh beacon has no live watcher lock
ok - fm-turnend-guard: non-Claude path blocks a source-only home
ok - fm-turnend-guard: blocks on a dead watcher lock even when the beacon is fresh
ok - fm-turnend-guard: silent no-op with a live watcher lock and fresh beacon
ok - fm-turnend-guard: healthy non-Claude harness paths ignore Claude episode contention
ok - fm-turnend-guard: blocks on a live watcher lock with an ancient beacon
ok - fm-turnend-guard: blocks with the exact required reason in the primary when unhealthy
ok - fm-turnend-guard: blocks from active FM_HOME state, not only repo-root state
ok - fm-turnend-guard: X-mode repair reason sources the cadence config
ok - fm-turnend-guard: X-mode-only supervision remains guarded in default mode
ok - fm-turnend-guard: registered-check-only supervision is named in the block banner
ok - fm-turnend-guard: ignores stale repo-root state when FM_HOME is set
ok - fm-turnend-guard: uses FM_STATE_OVERRIDE ahead of FM_HOME/state
ok - fm-turnend-guard: stop_hook_active=true always allows the stop (never blocks twice in one turn)
ok - fm-turnend-guard: blocks a blind turn end in a secondmate's own home (.fm-secondmate-home no longer excludes it)
ok - fm-turnend-guard: idle-by-default - silent in a secondmate home with nothing in flight
ok - fm-turnend-guard: stop_hook_active=true allows the stop in a secondmate home (never blocks twice in one turn)
ok - fm-turnend-guard: secondmate deferred-death recovery - silent while watched, forces re-arm once the watcher exits
ok - fm-turnend-guard: inert in a secondmate's own child worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: blocks a blind turn end in a treehouse-leased LINKED secondmate home (marker force-include)
ok - fm-turnend-guard: an invalid (empty) marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: a non-ASCII marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: inert in a crewmate/scout task worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: fails open (never blocks) when jq is missing
ok - fm-turnend-guard: silent no-op on empty stdin
ok - fm-turnend-guard: runs well under the generous timing margin (1s)
ok - fm-turnend-guard-grok: forces one explicitly marked same-session resume when the shared predicate blocks
ok - fm-turnend-guard-grok: legacy environment loop guard prevents a nested resume loop
ok - fm-turnend-guard-grok: native false delegates blocking feedback with zero resume processes
ok - fm-turnend-guard-grok: native true remains bounded and starts no resume process
ok - fm-turnend-guard-grok: both spellings are typed and camelCase has deterministic precedence
ok - fm-turnend-guard-grok: malformed, invalidly typed, and missing-prerequisite payloads start neither path
ok - fm-turnend-guard-grok: missing jq and no-supervision-needed stops stay silent and bounded
ok - tracked .claude/settings.json entries: 5 inert under grok, the documented subagent exception still armed, all live under Claude
ok - .codex/hooks.json: Stop hook uses hook process root when payload cwd is outside
ok - .codex/hooks.json: Stop hook ignores nested git root guard scripts
ok - .opencode primary plugin: guard path is anchored to worktree, not directory
ok - .pi primary extension: no-tool and multi-tool runs each inject exactly one guard follow-up
ok - .pi primary extension: delivery failure resets the logical-run latch
ok - fm-turnend-guard --claude: re-blocks a loop-guarded stop while unhealthy and unclaimed (incident regression)
ok - fm-turnend-guard --claude: X-mode-only homes re-block when auto-arm recovery is absent
ok - fm-turnend-guard --claude: a live arming epoch advances once and repeated observation is idempotent
ok - fm-turnend-guard --claude: repeated failed-to-arming races make bounded monotonic progress
ok - fm-turnend-guard --claude: terminal owner boundary excludes a concurrent start without deadlock
ok - fm-turnend-guard --claude: fresh rewake epoch prevents a duplicate continuation for the same event
ok - fm-turnend-guard --claude: an abandoned auto-arm claim no longer allows a blind stop (incident regression)
ok - fm-turnend-guard --claude: a claim whose pid was reused stops counting as recovery even while its entry reads arming
ok - fm-turnend-guard --claude: a hung owner frozen at arming with no watcher beat no longer allows a blind stop
ok - fm-turnend-guard --claude: a live open generation claim owns recovery with no lock held
ok - fm-turnend-guard --claude: a stuck generation claim no longer allows a blind stop
ok - fm-turnend-guard --claude: the terminal path clears an abandoned claim instead of stepping aside silently
ok - fm-turnend-guard --claude: fresh failed epochs preserv

... [6148 bytes truncated] ...

ing else.
ok - arm propagates an immediate watcher wake before confirmation
ok - arm attaches to a peer watcher after child stands down and surfaces a missing successor
watcher: lock held by live pid 74670 but heartbeat is stale for 843644775s (>300s); inspect or stop that watcher before re-arming.
ok - arm reports FAILED and exits non-zero when no fresh watcher can be confirmed
ok - cycle-exit ledger links a verified successor and remains size-capped
ok - SIGSTOP distinguishes live PID from stale beacon and termination records the exit class
FM_TEST_END 2026-09-25T08:46:37Z tests/fm-watcher-lock.test.sh exit=0 duration_ms=124039 gate_skip=false
FM_TEST_BEGIN 2026-09-25T08:46:37Z tests/fm-claude-stop-autoarm.test.sh family=standalone expected_gate_skip=none
ok - auto-arm: inert in a linked child worktree even when in-flight
ok - auto-arm: inert with no session lock
ok - auto-arm: a demonstrably dead recorded session owner is reclaimed through fm-lock.sh before arming
ok - auto-arm: inert without arm, rewake, or lock replacement when another live harness owns the home
ok - auto-arm: inert while AFK owns supervision
ok - auto-arm: stale-owner recovery leaves the AFK and supervision-need gates unchanged
ok - auto-arm: resolves the outermost pid of a nested contiguous claude ancestry (bg-spare chain)
ok - auto-arm: inert with nothing in flight and no X-mode need
ok - auto-arm: actionable close translates to exactly one exit-2 rewake with reason
ok - auto-arm: actionable close survives a healthy successor without duplicate delivery
ok - auto-arm: an attached cycle's end starts a handling successor named after the closed arm before the rewake
ok - auto-arm: an unconfirmed handling successor is reported in the rewake instead of blocking it
ok - auto-arm: bounded failure verification emits one automatic-mechanism alarm
ok - auto-arm: consecutive failures keep Stop-owned retry without repeating notice
ok - auto-arm: marker-write refusal defers delivery until one successor commits the notice
ok - auto-arm: unverified clean close exhausts retries and fails closed
ok - auto-arm: post-alarm actionable outcomes cannot continue or reset failure state
ok - auto-arm: benign cycle end with a live watcher and fresh beacon stays silent across the next cycle
ok - auto-arm: budget contention preserves the episode and forces a reset retry
ok - auto-arm: owner-mutex contention preserves successor episode state
ok - auto-arm: X-mode poll need arms the cycle even with no tasks in flight
ok - auto-arm: a registered custom check arms the cycle even with no tasks in flight
ok - auto-arm: concurrent firings admit one owner and one rewake translation
ok - auto-arm: TERM mid-arm commits a durable failure and exits 2 for rewake
ok - auto-arm: an abandoned owner claim is reclaimed so a lapsed cycle re-arms
ok - auto-arm: a legacy owner still arming is never reclaimed while its watcher keeps beating
ok - auto-arm: a fresh legacy arming claim is never reclaimed while its startup window is still open
ok - auto-arm: a live claim the ledger does not name is never reclaimed
ok - auto-arm: a claim whose pid was reused is reclaimed even while its ledger entry still reads arming
ok - auto-arm: a reused-pid claim is reclaimed even with no ledger entry to prove it
ok - auto-arm: an identity-matched owner still arming is never reclaimed
ok - auto-arm: the guard's terminal-check claim is never reclaimed
ok - auto-arm: a stuck live legacy owner is retired via TERM and its lock reclaimed
ok - auto-arm: a SIGSTOPped legacy owner is reclaimed with TERM pending and dies on continue
ok - auto-arm: a live open generation claim defers concurrent firings with no lock held
ok - auto-arm: a hung generation owner with no watcher beat is superseded so re-arming self-heals
ok - auto-arm: an identityless arming ledger never defers the gate (reused-pid loophole closed)
ok - auto-arm: a superseded owner never re-invokes the arm and leaves its successor's claim untouched
ok - auto-arm: a superseded owner goes silent - one supersession episode, one translation, no held mutex
ok - auto-arm: need vanishing mid-cycle closes without a rewake
ok - auto-arm: mid-cycle AFK hands triage to the daemon with no rewake
ok - auto-arm: active in a marked secondmate home
ok - auto-arm: refuses loudly when the owner lock cannot be created
ok - auto-arm: refuses loudly when an abandoned claim cannot be reclaimed
ok - auto-arm: a long FM_POLL with FM_GUARD_GRACE unset reaches fm-watch-arm.sh with the derived grace
ok - auto-arm: without config/supervision-host the hook runs the arm exactly as before
ok - auto-arm: an opted-in home runs the host bound to its generation, and a host line rewakes like a wake
ok - auto-arm: a wake the host hands back under the away record says it is automatic supervision, not a return
ok - auto-arm: without the host the rewake banner is unchanged, eight wake lines at most
ok - auto-arm: a host handback delivers every host line, while its wake lines keep their cap
ok - auto-arm: a host that stood down closes silently without a retry
ok - auto-arm: a host that died without a close is retried, then reported as a failure
ok - fm-lock: shared session-lock lib preserves the status path
FM_TEST_END 2026-09-25T08:48:07Z tests/fm-claude-stop-autoarm.test.sh exit=0 duration_ms=90035 gate_skip=false
FM_TEST_BEGIN 2026-09-25T08:48:08Z tests/fm-herdr-session-cleanup.test.sh family=backend-dispatch expected_gate_skip=none
ok - process proof reads Linux Herdr argv arrays and rejects malformed executable identities
ok - exact stale projection closes one exact pane under task then presentation locks
ok - successful cleanup is idempotent on repeat
ok - malformed title preserves the candidate
ok - missing token preserves the candidate
ok - malformed journal preserves the candidate
ok - duplicate token preserves the candidate
ok - duplicate title token preserves the candidate
ok - zero journal match preserves the candidate
ok - multiple journal matches preserves the candidate
ok - cross-home journal preserves the candidate
ok - v2 workspace binding mismatch preserves the candidate
ok - v2 tab binding mismatch preserves the candidate
ok - v2 pane binding mismatch preserves the candidate
ok - v2 cleanup requires and accepts the exact journal endpoint binding
ok - current task metadata preserves the candidate
ok - registered agent preserves the candidate
ok - unknown agent preserves the candidate
ok - multiple tabs preserves the candidate
ok - multiple panes preserves the candidate
ok - non-idle shell preserves the candidate
ok - child process or shell job preserves the candidate
ok - unreadable snapshot preserves the candidate
ok - unreadable topology check preserves the candidate
ok - revalidation race preserves the candidate
ok - active target preserves the candidate
ok - focus refusal preserves the candidate
ok - a task lock the filesystem refuses is named as a refusal, not as a busy peer
ok - a presentation lock the filesystem refuses is named as a refusal, not as a busy peer
ok - a task lock a live peer holds is still reported as busy
ok - standalone bootstrap cannot run lock-owned stale projection cleanup
ok - session start runs cleanup only after acquiring its home lock
all fm-herdr-session-cleanup tests passed
FM_TEST_END 2026-09-25T08:48:33Z tests/fm-herdr-session-cleanup.test.sh exit=0 duration_ms=25872 gate_skip=false
FM_TEST_SUMMARY total=6 failed=1 skipped_gate=0 duration_ms=241027
FM_TEST_SUMMARY_FAMILY family=backend-dispatch count=1 duration_ms=25872 failed=0
FM_TEST_SUMMARY_FAMILY family=standalone count=1 duration_ms=90035 failed=0
FM_TEST_SUMMARY_FAMILY family=watcher-wake-lock count=4 duration_ms=260165 failed=1
FM_TEST_SLOWEST rank=1 script=tests/fm-watcher-lock.test.sh duration_ms=124039
FM_TEST_SLOWEST rank=2 script=tests/fm-turnend-guard.test.sh duration_ms=107925
FM_TEST_SLOWEST rank=3 script=tests/fm-claude-stop-autoarm.test.sh duration_ms=90035
FM_TEST_SLOWEST rank=4 script=tests/fm-watch-arm.test.sh duration_ms=26944
FM_TEST_SLOWEST rank=5 script=tests/fm-herdr-session-cleanup.test.sh duration_ms=25872
FM_TEST_SLOWEST rank=6 script=tests/fm-supervision-events.test.sh duration_ms=1257
- Outcome: ⚠️ 1 info across 1 run (15m37s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ℹ️ bin/fm-watch.sh:2372 - The conflict-resolved hunk puts the unavailable-lock refusal at the top of main's new stalled-holder eviction retry loop, so it now runs before any held-lock or eviction handling. The ordering is correct: FM_LOCK_FAIL_REASON is reset on every fm_lock_try_acquire call, so a continue after an eviction cannot carry over a stale reason, and eviction only ever applies to a held lock. However, no test runs fm-watch.sh against an uncreatable .watch.lock and checks that it exits 1 with the 'no watcher is running and none was started' message. The only coverage is at the library level (fm-watcher-lock.test.sh reason=unavailable), so a later reordering of this loop could make it fall back to 'already running'/exit 0 without any test failing. Optional follow-up.
⚠️ **Test** - 1 info
  • ℹ️ tests/fm-watch-arm.test.sh:1143 - The test 'watcher pid … outlived its deleted state directory' (added on main by fix(bin): refuse watchers from disposable checkouts and exit when the home is gone #5552) fails intermittently. It failed in 3 of 4 runs on the merge commit and in 2 of 4 runs on an untouched copy of the base commit 1a814e4 (main). So the flakiness is already on main and wasn't introduced by this merge. The PR's own watch-arm cases, including the watcher's refusal when it can't create its lock, passed in every run.
  • bin/fm-test-run.sh tests/fm-watcher-lock.test.sh tests/fm-watch-arm.test.sh tests/fm-claude-stop-autoarm.test.sh tests/fm-herdr-session-cleanup.test.sh tests/fm-turnend-guard.test.sh tests/fm-supervision-events.test.sh on the merge commit (every file the PR touches): all pass except the one watch-arm flake
  • bin/fm-test-run.sh tests/fm-watch-arm.test.sh run 3 more times on the merge commit (1 pass, 2 hit the same flake)
  • bin/fm-test-run.sh tests/fm-watch-arm.test.sh run 4 times on a clean copy of base 1a814e4 (2 pass, 2 hit the same flake, so it is pre-existing)
  • Manual: fm_lock_try_acquire on a lock and .steal mutex both held by a dead pid (the #2787 setup): acquires, and no .steal.steal chain is created
  • Manual: fm_lock_try_acquire with a lock parent that isn't writable: rc=1, reason=unavailable, no held pid, no .steal paths created
  • Manual: bin/fm-watch.sh with a state directory that isn't writable: prints 'cannot create … no watcher is running and none was started.' and exits 1 through the merged retry and eviction loop
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 1)
✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "merge(main): resolve lock-steal-recursio..." | Re-trigger Greptile

@benlamlih

Copy link
Copy Markdown
Author

Reviewer note: which lock the race regression test drives, and why it matters

test_lock_stale_steal_mutex_reclaim_race_has_one_publisher deliberately drives $STATE/.watch.lock, not an arbitrary lock name.

The double-publish window opens between the primary reclaim's staleness re-proof and its publish.
For .watch.lock that gap contains _fm_recovery_marker_publish, a multi-fork write-and-rename, which widens the window from a couple of instructions to milliseconds.
On any other lock that gap is nearly empty, the interleaving almost never lands, and the test would pass without exercising the property it exists to protect.

This is worth stating because the first version of this fix was validated with a 40-racer hammer on a plain lock and passed, while the hole was real.
The bug was only caught by constructing the exact stall interleaving on the lock whose window is actually open.
A future change that "simplifies" this test onto a generic lock name, or replaces the deliberate stalls with more concurrency, would make it vacuous rather than stronger.

The test creates the stalls by copying the two real functions with declare -f and wrapping them in the test process only, so there is no test-only hook, sleep, or seam in bin/fm-wake-lib.sh itself.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Corrective for #2787: fm_lock_try_acquire no longer recurses into "$lockdir.steal" unbounded. Steal mutexes are a one-level leaf (fm_lock_try_acquire_leaf); an uncreatable lock is refused with FM_LOCK_FAIL_REASON=unavailable instead of being treated as a stale lock to recover; fm_lock_acquire_wait still never returns without the lock. Matches the filed lock-steal recursion failure.

VISION (per rule):

  • One captain, one interface — aligns. Operator gets a named refusal instead of megabytes of .steal.steal... until SIGSEGV.
  • Authority is explicit — aligns. Fail-closed; does not proceed without the lock.
  • Scripts own the mechanics — aligns. Lock identity stays in deterministic scripts.
  • A restart is a non-event — aligns. Session lock remains exclusive under disk pressure.
  • Delegation with a spine — aligns. Strengthens a refusal path.
  • The fleet outlives any vendor — n/a.
  • Scope — command-layer lock, not workshop validation.

Security: none. Workflows approved this pass after a clean diff review (CI 32573464807, Require no-mistakes 32573464806).

Class: corrective.

Overlap: docs/configuration.md also appears on hold-pair #2637 and #2768; this PR's lock change is otherwise distinct (bin/fm-wake-lib.sh, tests/fm-watcher-lock.test.sh). Not a spawn/teardown lifecycle hold.

CI: no structured no-mistakes-pipeline-attestation:v1 in the body (the "Updates from git push no-mistakes" prose and a git-push signature are not a substitute). Require no-mistakes FAILED (run 32573464806). CI 32573464807 in progress, not green. Greptile is not a merge gate.

Ahead 7, behind 0, mergeable, mergeStateStatus UNSTABLE.

Not merge-eligible. Waiting on the author for a green no-mistakes raise whose body attestation matches this HEAD (14442f00437200eac59cb3667a936605b77037fc) — not waiting on the captain.

…lock

fm_lock_try_acquire treated a lock it could not create as a stale lock to
recover, then serialized that recovery by calling itself on "<lock>.steal".
For a steal mutex that meant "<lock>.steal.steal", and so on with no base
case, so a filesystem that refused every create walked the name down a chain
of .steal suffixes until the path was rejected. Reproduced on a full
filesystem and on an unwritable lock parent: over 1400 suffixes, 6.3 MB of
stderr, and bash itself killed by SIGSEGV before the chain could stop.

A steal mutex is now a leaf: it reclaims its own stale holder directly and
never appends a second .steal, for internal callers and for
fm_autoarm_release_abandoned alike. The mutex is kept, because it is what
stops two processes both publishing the primary lock; the reclaim stays
exclusive because a live holder is never evicted, and two racers on a dead
holder are separated by the ownership rechecks the primary reclaim already
performs before it touches the lock.

Creation failure is also now separated from contention. A create that leaves
no lock behind means the filesystem refused, not that a holder exists, so
acquisition refuses there instead of entering recovery with nothing to
recover. FM_LOCK_FAIL_REASON reports which of the two happened, and the
refusal explains itself once to the operator rather than being silent until
the path grows too long to print. fm_lock_acquire_wait keeps blocking rather
than returning, so no caller can walk into its critical section believing it
holds a lock it never got.

Legacy .steal chains already on disk are swept when stale and left alone
when a holder is still live, so a rolling update cannot evict one.
BSD wc -l pads its count with leading blanks, so comparing an unstripped
"$(wc -l < ...)" against a bare 1 can never match on macOS and the three
one-line report assertions failed there while passing on GNU coreutils in CI.
One count in the same file already stripped; these three did not.
main rewrote the Claude Stop auto-arm single-flight from a held owner
lock to the generation ledger (fm_autoarm_claim_open/fm_autoarm_claim_next)
while this branch was bounding the .steal recursion and giving a
filesystem-refused lock a voice. Both survive:

- bin/fm-claude-stop-autoarm.sh keeps main's generation claim and the
  legacy shim, and reports FM_LOCK_FAIL_REASON=unavailable at each of the
  three points that used to exit silently - the claim itself, the legacy
  reclaim, and the retry after it.
- fm_autoarm_release_abandoned keeps main's grace argument, the TERM of a
  live identity-verified legacy owner and the ledger graft, and re-proves
  the steal mutex still points at this process immediately before removing
  the lock. That re-proof moved after the TERM wait and the graft, which
  are several forks wider than the window it originally guarded.
- fm_lock_try_acquire keeps its steal-mutex routing to the new leaf, and
  both it and fm_lock_try_acquire_leaf read their own pid through main's
  fm_current_pid rather than an inline ${BASHPID:-$$}, so the self-held
  reclaim check survives stock Bash 3.2.
- docs/configuration.md keeps main's FM_LOCK_STALE_AFTER wording beside
  this branch's two new lock tunables.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V8NBG3Uj6iwDBp7xJe9bSc
Keep both sides in every hunk. The two sides only collided because each
added material at the same spot, so no lock behaviour had to be chosen
over anything main does.

- docs/configuration.md: keep this branch's FM_LOCK_UNAVAILABLE_REPORT_EVERY
  and FM_LOCK_LEGACY_STEAL_SCAN_MAX entries, and take main's newer
  FM_GUARD_GRACE wording.
- tests/fm-claude-stop-autoarm.test.sh: keep the two uncreatable-lock
  refusal tests and main's long-poll grace and supervision-host tests, and
  call all of them.
- tests/fm-watch-arm.test.sh: keep the two refused cycle-ledger tests and
  main's launch-confirm-window refusal test, and call all of them.
- tests/fm-watcher-lock.test.sh: keep this branch's lock-refusal and
  steal-bound tests, and main's wait-deadline reap test call.
… eviction

Keep both sides.

- bin/fm-watch.sh: main turned the single watcher-lock acquire into a retry
  loop that can evict a holder whose beacon stalled past a hard bound. The
  branch's refusal for a lock the filesystem cannot create now runs first in
  that loop body, so an unavailable lock still exits 1 saying no watcher is
  running before any held-lock or eviction handling. Where the two could
  disagree, the lock-safety refusal wins: eviction only ever applies to a
  lock that is genuinely held.
- docs/watcher-continuity.md: take main's bulleted coverage list and new
  section heading, keep the branch's acquisition-primitive coverage
  paragraph, and keep the branch's unavailable-lock limits after main's
  reworded opening sentence.
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.

3 participants