Repository navigation
fix(bin): reclaim a status-presentation lock whose owner pid is dead or recycled - #3977
eduardstan wants to merge 8 commits into
Conversation
A stranded status-presentation lock made every wake drain burn its whole deadline and skip presentation, so queued wakes were re-announced on every turn with no way to acknowledge them. The recorded owner really was gone - the operating system had recycled its pid onto an unrelated live process, so `kill -0` answered forever and the stale-owner steal never fired. Lock owners now record the acquiring process's start token beside the pid, and the steal treats an owner as gone when the pid is dead or when the live pid started later than the recorded owner did. The recorded fact is the start token rather than the full process identity because a holder may legally replace its own image while holding - bash execs the last command of a subshell, so an ordinary `( take the lock; run one thing ) &` holder does exactly that - and only the start time proves reuse. `fm_pid_identity`'s recorded string is unchanged, so a watcher lock or auto-arm claim written by a running older build still verifies. An owner directory with no recorded start token keeps the weaker pid-only proof, which is the behavior it had before. The drain's existing bounded-wait advisory now also names the manual clear operators were left to work out themselves.
… recycled-owner reclaim
Confidence Score: 5/5The PR appears safe to merge, with no new actionable issue beyond the owner-directory leak already raised in an existing review thread. Token comparison fails closed when identity evidence is absent or incomparable, teardown refusal retains the durable task record for retry, and the remaining concrete cleanup concern is already under review. Reviews (1): Last reviewed commit: "no-mistakes(document): document shared p..." | Re-trigger Greptile |
… work is spent Refs kunchenguid#4018 Limits, stated as limits: - It closes nothing. Every forge call is a read, including in the opt-in --sweep mode: no issue is closed, labelled, or commented on, and no backlog is read or written. It is the evidence half of the claim problem, not the loop closure the triage also leaves open. - A fix that cites the issue number nowhere - no PR body, branch, or title, no commit message, and no --symbol the caller supplies - stays invisible to every check. bin/fm-issue-claim.sh runs five read-only checks per issue and prints an inspectable verdict (open, claimed, partially-covered, fixed-on-main, or unknown): timeline cross-references, maintainer triage stamps (OWNER, MEMBER, or COLLABORATOR only; the existing-pr target PR is read for its current state), the complete open-PR corpus fetched by paginated REST and checked against the search API total, the issue author's fork branches (resolved to the PR each heads), and main history since the issue opened (commit messages citing the issue, plus optional caller --symbol pickaxe searches). Issue numbers match only as whole numbers, so 4018 never matches 40181, and a foreign owner/repo#N is not a citation. A failed or rate-limited read, a short or unverified corpus, or a history ref that cannot be searched yields unknown or an explicit disclosure, never open. One corpus is shared across every issue in a run and can be saved and reused across runs with its completeness verdict and age. --sweep is opt-in and report-only: one disposition line per issue (close-candidate, leave-open, no-action, undetermined) with link candidates, judged only from durable evidence and never from titles, branches, PR checks, reviews, or mergeability. An issue with a live PR stamped existing-pr is always leave-open, and merged evidence with incomplete coverage is undetermined rather than a close candidate. Live proof against kunchenguid/firstmate, 2026-09-23, history ref origin/main@9296f9b9, open-PR corpus 1261/1261: - kunchenguid#4927 claimed, reproduced: PR kunchenguid#4943 and PR kunchenguid#4955 (timeline, corpus, fork, and the maintainer existing-pr stamp on kunchenguid#4955), plus kunchenguid#4026 named by the earlier stamp and still open. - kunchenguid#3370 fixed-on-main, reproduced: commit baede47 (kunchenguid#4656), found only by the history check with --symbol 3370:rerecord_device, issue still open. - kunchenguid#4412 partially-covered, reproduced: PR kunchenguid#4775 merged (landed as 9bc051f) and PR kunchenguid#4832 open. - kunchenguid#4466 open, reproduced, with every check complete. - Reporter's cases in one --sweep: kunchenguid#3966 claimed by PR kunchenguid#3977 and kunchenguid#3942 claimed by PR kunchenguid#3978 (leave-open); kunchenguid#3928 (PR kunchenguid#3946) and kunchenguid#3926 (PR kunchenguid#3944) show fixed-on-main and have since been closed on the forge (no-action).
|
Speaking as Kun's firstmate: a quick overlap note for you, @eduardstan. #7886 (for #7885) just merged as The rest of this PR (the status-presentation and drain handling for #3966, and the teardown changes) isn't covered by #7886. If you pick this back up, building on current main and dropping the parts #7886 now handles would make it a smaller review. Any merge conflict is ours to deal with, so you don't need to rebase for that. I'm not closing or changing anything here. This note is only so the overlap is on record in both places. |
Intent
Fix upstream firstmate issue #3966: "status-presentation lock: a dead owner is not reclaimed, so every wake drain blocks until its timeout". The captain's order (2026-09-08, while away): fix it upstream, through the no-mistakes pipeline as upstream requires, on Claude Opus 5.
The issue, condensed: every bin/fm-wake-drain.sh blocks for minutes and returns only the OPEN DECISIONS section plus a warning, no wake records and no WAKE_ACK_REQUIRED line, so queued wakes cannot be acknowledged and re-announce on every turn. Seen three times in four hours on one home (dead owner pids) and once on 2026-09-04. Manual fix each time: read state/.status-presentation-lock (a symlink), cat /pid, confirm with ps -p that the owner is gone, remove the symlink and the owner directory. The presentation lock is taken in bin/fm-wake-drain.sh (around lines 364 to 375) and bin/fm-classify-lib.sh (around line 774) through fm_lock_acquire_wait "$STATE/.status-presentation-lock"; fm_lock_acquire_wait (bin/fm-wake-lib.sh around 884 to 891) loops on fm_lock_try_acquire with a 0.1 second sleep, no bound, no stale-owner escape. The reclaim path exists (fm_pid_alive guarding a steal, around fm-wake-lib.sh 833) but the stranded owner directories contain only pid, no pid-identity, while the daemon lock's owner directory has both; fm_lock_points_to_owner reads pid-identity, so an owner written without it plausibly fails the identity comparison and the steal is abandoned. Second possibility to rule out: pid reuse making kill -0 succeed for an unrelated process, which is what pid-identity exists to prevent. Suggested direction from the reporter: (1) make the presentation-lock writer record pid-identity the way the auto-arm owner lock does (fm-wake-lib.sh around 1042 to 1063), so the existing steal path can prove the owner is gone; (2) give fm_lock_acquire_wait a bounded wait for this lock with a loud diagnostic naming the owner pid and the manual clear, instead of an unbounded spin. Reproduction is opportunistic (kill a drain mid-presentation); the stranded directories are the evidence.
What Changed
fm_lock_record_start, split out offm_pid_identityasfm_pid_start_token), and all steal paths inbin/fm-wake-lib.shroute their liveness check through a newfm_lock_owner_gone, which treats an owner as gone when the pid is dead or when the live pid's recomputed start token differs from the recorded one — only comparing tokens computed in the same format, and falling back to the previous pid-only proof when no token was recorded.fm_status_presentation_lock_timeouthelper, and the refused-wait message became a sharedfm_lock_live_holder_advisorythat names the holder pid, theps -pconfirmation, and a shell-quotedrm -rfclear covering both the lock symlink and its resolved owner directory.bin/fm-classify-lib.sh's status-row retire swapped its unboundedfm_lock_acquire_waitfor a newfm_lock_acquire_wait_retire, which waits a genuinely live holder out across 30 bounded windows (announcing the holder each window) before refusing with 124, and falls back to the unbounded wait if the bounding machinery itself fails.docs/configuration.mddocumentsFM_STATUS_PRESENTATION_LOCK_TIMEOUTanddocs/watcher-continuity.mddocuments the ownership contract.Risk Assessment
Testing
Ran the four changed test scripts through bin/fm-test-run.sh; fm-teardown, fm-wake-drain-unread-status and fm-watcher-lock all pass (the latter serially, 37 ok), and fm-wake-queue passes everything except one pre-existing case that fails identically on the base commit and aborts the suite before the new cases, so I ran those in isolation and with only that case excluded to prove them. Two failures seen in the first concurrent run were host-load flakes and passed isolated. Beyond the suites I reproduced the reported field condition against the real drain and the real teardown retire path on the base checkout and on the branch head: base skips the presentation on every drain after burning its full bound and its retire never returns at all under a 45-second external timeout, while the head reclaims the stranded owner and presents status content, retires cleanly, still refuses to steal a genuinely live holder while naming it every wait window, and hands an operator a paste-ready manual clear for an unprovable legacy owner directory that unwedges the drain and strands nothing. The before/after CLI transcript and the three repro scripts are in the evidence directory.
Evidence: Before/after CLI transcript: #3966 drain wedge, retire spin, and operator remedy
Source: Before/after CLI transcript: #3966 drain wedge, retire spin, and operator remedy
SCENARIO 1 - the reported wedge (owner gone, pid recycled onto a live process) ### [BEFORE-891dc51] drain exit=0 wall=12s STATUS PRESENTATION SKIPPED: lock remains held by live pid 1856275 after 10s; retry on the next drain. ### [AFTER-bbd4dcd] drain exit=0 wall=5s wake annotation: latest wake-EVENT observed at drain, not current state: task.status: needs-decision [key=fixture]: recycled owner must not wedge the drain OPEN DECISIONS (still open, folded from the durable status logs - not just the latest line): task [key=fixture] needs-decision: recycled owner must not wedge the drain SCENARIO 2 - the retire path (bin/fm-classify-lib.sh) ### [BEFORE-891dc51] retire NEVER RETURNED (killed by a 45s external timeout) - unbounded spin ### held.status still present after retire? YES-not-retired ### [AFTER-bbd4dcd] retire exit=0 wall=1s ### held.status still present after retire? no-retired SCENARIO 3 - owner directory from an OLDER build (pid only, unprovable) ### [BEFORE-891dc51] STATUS PRESENTATION SKIPPED: lock remains held by live pid 1882667 after 1s; retry on the next drain. ### advisory printed NO manual clear command ### [AFTER-bbd4dcd] STATUS PRESENTATION SKIPPED: lock remains held by live pid 1883938 after 1s. If ps -p 1883938 shows no firstmate process, clear it with rm -rf <state>/.status-presentation-lock.owner.legacy <state>/.status-presentation-lock. Retry on the next drain. $ rm -rf <state>/.status-presentation-lock.owner.legacy <state>/.status-presentation-lock ### exit=0 ### lock symlink left behind? no ### owner directory stranded in state/? none ### re-drain after the printed clear: OPEN DECISIONS ... needs-decision [key=fixture]: manual clear must strand nothing SCENARIO 4 - a GENUINELY live presentation holder ### retire exit=0 wall=13s (holder exits on its own after ~12s); held.status retired? yes STATUS PRESENTATION RETIRE WAITING: lock remains held by live pid 1897527 after 2s. If ps -p 1897527 shows no firstmate process, clear it with rm -rf ... (x5, one per wait window)Evidence: Repro harness: drain against a stranded recycled-pid presentation lock
Source: Repro harness: drain against a stranded recycled-pid presentation lock
Evidence: Repro harness: status_retire_presentation_task against the same stranded lock
Source: Repro harness: status_retire_presentation_task against the same stranded lock
Evidence: Repro harness: legacy pid-only owner dir and the printed manual clear
Source: Repro harness: legacy pid-only owner dir and the printed manual clear
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-wake-drain.sh:589- The new advisory tells the operatorclear it with rm -f <lock>, but<lock>is the symlink only. The documented manual procedure (andfm_lock_remove_path's own symlink branch) removes the symlink AND the owner directory it points at. An operator who follows the printed command unwedges the drain but leaves an orphanstate/.status-presentation-lock.owner.XXXXXXdirectory behind on every clear, which accumulates instate/. Consider naming both, e.g.rm -rf "$(readlink <lock>)" <lock>, or printing the resolved owner directory alongside it.bin/fm-wake-drain.sh:634- Only the presentation-lock advisory gained the manual-clear hint. The queue-lock advisory (WAKE DRAIN SKIPPED: queue lock remains held by live pid %s) is the path thatexit 0s before any wake record or WAKE_ACK_REQUIRED line is emitted — i.e. the exact operator symptom the issue describes ("no wake records and no WAKE_ACK_REQUIRED line, so queued wakes cannot be acknowledged"). An operator hitting a wedged.wake-queue.lockstill gets a pid and nothing to act on. Root cause is fixed for both locks; this is only about diagnostic parity.bin/fm-wake-lib.sh:1097-_fm_lock_acquire_wait_handoffrunsrm -f "$ownerdir/pid-start"before the[ "$back" != "$current" ]ownership check two lines below. If the helper is not in fact the recorded owner at that instant, it has just stripped a third party's start token; that lock then permanently falls back to pid-only proof and silently re-becomes unreclaimable on pid reuse — the exact bug this commit fixes. The window is not reachable today (a live helper with a matching token cannot be stolen, sobackalways equalscurrent), so this is defensive ordering only: verifyback = currentfirst, then delete the token, then write the caller pid.tests/fm-wake-queue.test.sh:1882-test_live_presentation_holder_advisory_names_the_manual_clearre-stages ~35 lines of live-presentation-holder setup (seed status, seed wake, backgroundfm_lock_acquire_wait+exec sleep 30holder, ready-file poll, bounded drain) thattest_live_presentation_holder_is_deadlined_without_weakening_ack(same file, ~line 1752) already stages and already greps forSTATUS PRESENTATION SKIPPED: lock remains held by live pid $presentation_holder. The only new assertion is onegrep -Ffor the manual-clear sentence; adding that single grep to the existing case removes the duplicated scenario. The recycled-pid test at line 1841 is genuinely new and should stay.docs/watcher-continuity.md:72- Acknowledging the documented tradeoff, not asking for a change: owner directories already stranded in the field carry nopid-start, sofm_lock_owner_gonekeeps the weaker pid-only proof for them and a home currently wedged on a recycled pid still needs one manual clear after upgrade. This is stated explicitly in the doc and thebin/fm-wake-lib.shheader, and the improved advisory is what covers it — correct and honest, worth noting only so the operator expectation on rollout is explicit.🔧 Fix: check handoff ownership before dropping start token
3 infos still open:
bin/fm-wake-lib.sh:1102-_fm_lock_acquire_wait_handoffdropspid-startand hands the pid to the caller, but nothing rewrites the token inside the helper; the invariant is only restored by the parent atfm_lock_acquire_wait_boundedline 1144. If the parent is killed between the helper's exit and that line, the lock is left with a live pid and no start token, i.e. back on the weaker pid-only proof - the exact state that wedges every later drain once the operating system recycles that pid (issue status-presentation lock: a dead owner is not reclaimed, so every wake drain blocks until its timeout #3966). The delete-first ordering is right (a caller pid beside the helper's token would read as reuse), but the helper can close the window itself: after the pid write succeeds,fm_pid_start_token "$caller_pid" > "$ownerdir/pid-start". The caller is already proven live above and the parent's laterfm_lock_record_startwrites the identical value, so this is idempotent and removes the dependency on a second process surviving.bin/fm-wake-drain.sh:589- The advisory tells the operatorclear it with rm -f <lock>, naming only the symlink.fm_lock_remove_path's own symlink branch removes the symlink ANDfm_lock_discard_owners the target, and the issue's documented manual procedure does the same. An operator who runs exactly the printed command unwedges the drain but leaves an orphanstate/.status-presentation-lock.owner.XXXXXXdirectory behind; nothing in bin/ sweeps those, so they accumulate instate/once per clear. This was raised in round 1 and is now additionally pinned by the new assertion in tests/fm-wake-queue.test.sh:1779, so the incomplete instruction is locked in. Print the resolved owner directory too, e.g.rm -rf "$(readlink <lock>)" <lock>.bin/fm-classify-lib.sh:1189-status_retire_presentation_taskstill takes the status-presentation lock with unboundedfm_lock_acquire_wait. The intent's suggested direction (2) - "give fm_lock_acquire_wait a bounded wait for this lock with a loud diagnostic naming the owner pid and the manual clear, instead of an unbounded spin" - names this lock, and the intent names bin/fm-classify-lib.sh as one of its two takers. Only bin/fm-wake-drain.sh got a bound (pre-existing). With the start-token reclaim in place this is now only reachable against an owner directory written by an older build (docs/watcher-continuity.md:74 acknowledges those keep pid-only proof and still need one manual clear), but in that case a teardown/retire hangs forever with no pid-naming diagnostic at all, unlike the drain. Flagging because it is a source-verifiable gap against a suggested direction rather than a hard requirement - the reported symptom (the drain) is fixed.🔧 Fix: record caller start token inside the lock handoff
4 infos still open:
bin/fm-wake-lib.sh:124- The extraction of_fm_proc_start_tokensilently changedfm_pid_identity's failure semantics. The old code entered the /proc branch on[ -r stat ] && [ -r cmdline ]and hard-return 1ed on any parse failure inside it (short stat_fields, non-numeric starttime) - it never fell through to the ps fallback. Nowif start=$(_fm_proc_start_token "$pid"); then ... fitreats a parse failure exactly like an absent /proc, so execution continues tops -p -o lstart= -o command=and returns an identity in the OTHER format. A caller holding a recordedlinux-starttime=...identity then sees a mismatch rather than a compute failure, and those are not equivalent:fm-watch-arm.sh:229andfm_watcher_lock_stale_clear(bin/fm-wake-lib.sh:1660) evict on mismatch, while a compute failure is conservative.fm_pid_start_tokeninherits the same drift and feedsfm_lock_owner_gone, where a format flip means a live holder reads as gone and its lock is stolen. Reachability on real Linux is essentially nil (stat field 22 always parses), so this is defensive only. Restore the old shape: gate on[ -r "$proc_root/$pid/stat" ] && [ -r "$proc_root/$pid/cmdline" ]and hard-fail when_fm_proc_start_tokenfails inside that gate, in bothfm_pid_start_tokenandfm_pid_identity.bin/fm-wake-lib.sh:490-fm_lock_record_startmemoizes by pid and caches the FAILURE too:FM_LOCK_SELF_START=$(fm_pid_start_token "$pid" 2>/dev/null || true)stores an empty string, and every later call for that same pid hits[ "$pid" != "$FM_LOCK_SELF_START_PID" ]as false and returns at the[ -n "$FM_LOCK_SELF_START" ] || return 0guard without retrying. One transient failure (apsfork that hits EAGAIN under load on the non-/proc fallback path, a momentary /proc read error) therefore poisons that process for its whole lifetime: every lock it acquires from then on records pid with nopid-start, which is precisely the pid-only proof this change exists to remove, so issue status-presentation lock: a dead owner is not reclaimed, so every wake drain blocks until its timeout #3966's wedge silently returns for that long-lived process's locks. Cache only a successful computation - keep the memo when the token is non-empty and let an empty result fall through to a recompute on the next acquire.bin/fm-wake-drain.sh:589- The advisory tells the operator toclear it with rm -f <lock>, naming only the symlink.fm_lock_remove_path's own symlink branch (bin/fm-wake-lib.sh:614-620) removes the symlink ANDfm_lock_discard_owners the target, and the issue's documented manual procedure removes both as well. An operator who runs exactly the printed command unwedges the drain but strands astate/.status-presentation-lock.owner.XXXXXXdirectory; grep confirms nothing under bin/ ever sweeps*.owner.*for wake locks, so one accumulates instate/per clear. The new assertion at tests/fm-wake-queue.test.sh:1779 pins the incomplete sentence. Print the resolved owner directory too, e.g.rm -rf "$(readlink <lock>)" <lock>.bin/fm-classify-lib.sh:1189-status_retire_presentation_taskstill takes$state/.status-presentation-lockwith unboundedfm_lock_acquire_wait. The intent's suggested direction (2) - "give fm_lock_acquire_wait a bounded wait for this lock with a loud diagnostic naming the owner pid and the manual clear, instead of an unbounded spin" - names this lock, and the intent names bin/fm-classify-lib.sh as one of its two takers; only bin/fm-wake-drain.sh has a bound, and that bound pre-dates this change. With the start-token reclaim in place the remaining reachable path is an owner directory written by an older build, which docs/watcher-continuity.md:74 acknowledges keeps pid-only proof; against such a directory a teardown/retire hangs forever with no pid-naming diagnostic at all, unlike the drain. Flagged as a gap against a suggested direction, not a hard requirement - the reported symptom (the drain) is fixed and this line is unchanged by the diff.🔧 Fix: share the presentation-lock advisory and bound the retire path
3 issues (1 warning, 2 infos) still open:
bin/fm-wake-lib.sh:1147-fm_lock_live_holder_advisorybuilds a copy-pasteable destructive command by bare string concatenation:clear="rm -rf $ownerdir $lockdir"(line 1147, andrm -rf $lockdirat line 1144). The paths come from$STATE, which is unconstrained - nothing in bin/ rejects whitespace or glob characters in a firstmate home path. With a home at/home/u/My Projects/fm, the advisory printsclear it with rm -rf /home/u/My Projects/fm/state/.status-presentation-lock.owner.ab12 /home/u/My Projects/fm/state/.status-presentation-lock, and an operator who runs exactly what the advisory told them to run deletes/home/u/MyandProjectsrelative to the cwd instead of the lock. This is newly introduced text (the base advisory at bin/fm-wake-drain.sh printed no command at all), and tests/fm-wake-queue.test.sh:1879 actually executes the extracted string withbash -c, so the suite would execute the mis-split command too. Fix: emit shell-quoted paths, e.g.printf -v clear "rm -rf %q %q" "$ownerdir" "$lockdir", and update the two advisory assertions (tests/fm-wake-queue.test.sh:1781, tests/fm-wake-drain-unread-status.test.sh:73) to match.bin/fm-wake-lib.sh:520-fm_lock_owner_gonereplaced a fork-freefm_pid_alive(builtinkill -0) inside the hot path offm_lock_acquire_wait, which polls every 0.1s with no bound. Per poll against a live holder it now forks for$(cat "$lockdir/pid-start")(line 520), for$(fm_pid_start_token ...)(line 522), and inside that for$(_fm_proc_start_token ...)plus$(cat "$proc_root/$pid/stat")- roughly 4x the forks per poll on Linux, and on a host with no readable /proc an additionalpsexec plus aprintf | sedpipeline (two more processes) every 100ms.fm_lock_acquire_waitis still unbounded on the mutation-critical acknowledgement path, so a contended ack can sustain ~60 forks/sec for as long as it waits. The reads are all single-line and can be done with builtins:read -r recorded < "$lockdir/pid-start"infm_lock_owner_goneandread -r stat_line < "$proc_root/$pid/stat"in_fm_proc_start_token(line 82) remove three of the four Linux forks with no behavior change.bin/fm-wake-lib.sh:513- The comment abovefm_lock_owner_gonestates the owner is gone "when the live pid started later than the recorded owner did (pid reuse)", but line 524 is[ "$current" != "$recorded" ]- any difference, in either direction, evicts. That distinction is load-bearing for the safety argument the change rests on, because this file's own comment at line 68 records that theps -o lstart=fallback's rendered date is not stable ("the wall-clock steps that re-render the ps lstart fallback's date (observed as WSL2 btime drift) and would evict a live watcher"). On a host that takes that fallback, a re-rendered lstart for an unchanged live holder reads as a mismatch and its lock is stolen, whereas an ordering comparison would not. Reachability is narrow in practice (Linux hosts take the /proc branch, and macOS lstart derives from a stored absolute p_starttime rather than boot time), so this is a comment-accuracy issue rather than a demonstrated defect - but state what the code does ("differs from") so the next reader does not rely on an ordering guarantee that is not implemented.🔧 Fix: shell-quote the advisory clear and drop hot-path forks
3 issues (1 warning, 2 infos) still open:
bin/fm-wake-lib.sh:527-read -r recorded < "$lockdir/pid-start" 2>/dev/null || truedoes not suppress the failure it is guarding. Bash applies redirections left to right and reports a failed input open on the stderr in effect at that moment, which is still the caller's - the later2>/dev/nullnever covers it. Reproduced directly against this worktree:fm_lock_owner_goneon a lock whose owner has a live pid and nopid-startprintsbin/fm-wake-lib.sh: line 527: <state>/.l/pid-start: No such file or directoryand then returns PRESENT. That is exactly an owner directory written by an older build (docs/watcher-continuity.md:76 documents those as supported and pid-only), plus the handoff window at line 1126, andfm_lock_owner_goneruns on every 0.1s poll of the unboundedfm_lock_acquire_wait, so a contended legacy lock emits ~10 raw bash errors per second into the drain's stderr. tests/fm-wake-queue.test.sh'stest_live_presentation_holder_is_deadlined_without_weakening_ackalready asserts that channel carries nothing but WAKE_ACK_REQUIRED ("presentation deadline leaked helper-process diagnostics"); it passes only because its holder is a real acquirer that does record a token, andtests/fm-watcher-lock.test.sh:511(which does stage a tokenless live owner) captures stdout only, so the noise is invisible to the suite. Fix with the brace-group idiom this file already uses atfm_lock_claimline 586:{ read -r recorded < "$lockdir/pid-start"; } 2>/dev/null || true. Same defect at line 85 (read -r stat_line < "$proc_root/$pid/stat", narrower - only a TOCTOU race past the-rguard) and line 512 (printf ... > "$dir/pid-start" 2>/dev/null, when the owner directory is unwritable).bin/fm-wake-lib.sh:528- Round 4 removed the /proc-path forks but the non-/proc path is untouched, and that is where the cost is highest. On a host with no readable /proc (macOS, which this file supports explicitly via_FM_UNAME/fm_path_mtime), onefm_lock_owner_gonepoll costs: the$(fm_pid_start_token ...)subshell at line 528, the$(LC_ALL=C ps ...)subshell pluspsexec at line 119, and theprintf | sedpipeline at line 121 - roughly five processes where the base code used thekill -0builtin and forked nothing.fm_lock_acquire_waitpolls every 0.1s with no bound on the mutation-critical acknowledgement path, so a contended ack sustains ~50 processes/sec for the length of the wait. The cheap win with no behavior change is dropping the sed:out=${out#"${out%%[![:space:]]*}"}strips the same leading whitespace with no fork, infm_pid_start_token(line 121) and identically infm_pid_identity(line 145).bin/fm-wake-lib.sh:530- Noting a deferred consequence, not asking for a change now: the author explicitly scoped round 4 to "comment and documentation only; do not change the predicate's logic in this round", and the comment at lines 514-521 is now accurate. The residual is that[ "$current" != "$recorded" ]compares tokens across formats. A token recorded aslinux-starttime=Nwhile /proc was readable, recomputed later through the ps fallback (_fm_proc_start_tokenreturns 1 whenever/proc/<pid>/stator/proc/<pid>/cmdlinestops being readable for that pid - hidepid, ProtectProc, a cross-user contender), yields an lstart date string, which differs, so a LIVE holder is evicted. Blast radius includes$STATE/.watch.lock, wherefm_lock_try_acquireline 1064 also publishes a false downtime episode on the steal. The base code could never steal a live holder, so this is new asymmetry: a false "present" is harmless, a false "gone" is not. Narrow in practice on same-user Linux and macOS. When it is picked up, the minimal guard is to compare only when both tokens carry the same<key>=prefix and treat a format change as "present".🔧 Fix: silence guarded reads and refuse cross-format token eviction
3 issues (1 warning, 2 infos) still open:
bin/fm-classify-lib.sh:1194-status_retire_presentation_tasktraded an unbounded wait for a hard failure, and teardown has no retry to absorb it. Concrete sequence: a watcher drain holds$state/.status-presentation-lockacrossstatus_presentation_snapshot+fm_wake_print_annotations+print_status_sectionsfor longer than the 10s default (large fleet, loaded host), a teardown runs concurrently,fm_lock_acquire_wait_boundedreturns 124, andbin/fm-teardown.sh:3339doesstatus_retire_presentation_task "$STATE" "$ID" || exit 1. By that pointremove_grok_turnend_auth,remove_kimi_turnend_auth,rm -rf $TASK_TMP,remove_pr_poll_artifactsandretire_busy_statehave all already run, so the teardown aborts half-done with the status file and its presentation-cursor row still present. The same applies at fm-teardown.sh:863 and :2933 (|| return 1). The non-124 branch widens it further: any_fm_wake_require_timeout,fm_current_pid, or helper-exec failure returns rc=1 and printsstatus retire: status presentation lock could not be acquired safely, where the old unboundedfm_lock_acquire_waitwould simply have kept trying. The drain's own bound is safe precisely because presentation is retriable on the next drain; a retire is not. Note the start-token reclaim already removes the wedge this bound was added for on every owner directory written by this build - what the bound now catches is a genuinely live holder. Worth confirming the intended semantics: a longer bound for the retire path, or a bounded retry loop, would keep the loud refusal for a truly wedged legacy owner without turning ordinary drain contention into a partial teardown.tests/fm-wake-queue.test.sh:1880- The "strands nothing" assertion scans every.status-presentation-lock.owner.*under$state, but the drain's own bounded acquire manufactures those names on the same path. WithFM_STATUS_PRESENTATION_LOCK_TIMEOUT=1the helper spun byfm_lock_acquire_wait_boundedpollsfm_lock_try_acquireevery 0.1s, andfm_lock_try_create(bin/fm-wake-lib.sh:622-626) runsmktemp -d "${lock_abs}.owner.XXXXXX"BEFORE it tests[ -e "$lockdir" ]and discards.fm_run_timedterminates the whole process group at the deadline, andfm_lock_discard_ownerreaches the mktemp'd directory through two external commands (rm -finfm_lock_clean_known_files, thenrmdir), so a TERM landing in that window leaks one.status-presentation-lock.owner.XXXXXXthat has nothing to do with the printed clear - andfindreports it as a stranded owner directory. The window is small next to the 0.1s sleep the helper spends most of its life in, but it is hit on ~10 poll cycles per run and by bothtest_printed_manual_clear_unwedges_and_strands_nothingandtest_printed_manual_clear_is_safe_on_a_home_path_with_a_space. Anchor the check to the directory the fixture actually staged ([ ! -e "$owner" ]), or snapshot the matching directories beforebash -c "$clear_cmd"and assert the delta, so the assertion tests the advisory rather than helper cleanup timing.bin/fm-wake-lib.sh:535- Acknowledging a tradeoff, not asking for a change: round 5 removed thecatandsedforks, butfm_lock_owner_gonestill pays two subshells per poll on Linux against a live holder that recorded a token -$(fm_pid_start_token ...)at line 535 and$(_fm_proc_start_token ...)inside it - where the base code used thekill -0builtin and forked nothing.fm_lock_acquire_waitstill polls every 0.1s with no bound on the mutation-critical acknowledgement path, so a contended ack sustains ~20 forks/sec; on a host with no readable /proc it is ~30/sec including thepsexec. That is the cost of the reclaim proof and it is bounded and modest, but it is a real regression from zero, so it is worth having stated rather than rediscovered under load.🔧 Fix: wait out live presentation holders on the retire path
3 infos still open:
bin/fm-wake-lib.sh:622-fm_lock_try_createrunsownerdir=$(fm_lock_owner_dir "$lockdir")(mktemp -d) BEFORE it tests[ -e "$lockdir" ], then discards through two external commands (rm -finfm_lock_clean_known_files, thenrmdir). Everyfm_lock_acquire_wait_boundedwindow ends withfm_run_timedTERMing the whole process group while the helper is insidefm_lock_acquire_wait's 0.1s poll, so a TERM landing in that ~3ms exec window strands astate/.status-presentation-lock.owner.XXXXXXdirectory; grep confirms nothing under bin/ sweeps*.owner.*. The newfm_lock_acquire_wait_retireloop (line 1246) runs up to_FM_LOCK_RETIRE_INTERVALS=30 such kill windows per contended teardown where the base code's unboundedfm_lock_acquire_waitspawned no helper at all, so the expected leak per contended retire goes from 0 to roughly one directory. That this window is real is already conceded by this same fix round:exercise_printed_manual_clearin tests/fm-wake-queue.test.sh:1880 had to stop scanning.owner.*and anchor to the staged directory precisely because the bounded acquire manufactures these orphans. Fix at the shared boundary: test[ -e "$lockdir" ] || [ -L "$lockdir" ]beforefm_lock_owner_dir, keeping the existing post-mktemp check for the genuine race.bin/fm-wake-lib.sh:1147-FM_STATUS_PRESENTATION_LOCK_TIMEOUTis now the unit of two very different budgets: the drain's single bound, and the retire path's_FM_LOCK_RETIRE_INTERVALSx seconds total (300s at the default). Nothing that documents the knob says so - bin/fm-wake-drain.sh:11 still describes it only as "the positive whole-second wait for presentation-path locks (default 10)", and docs/watcher-continuity.md:74 says the retire waits "across many of those bounds" without naming the multiplier or the variable. An operator who sets FM_STATUS_PRESENTATION_LOCK_TIMEOUT=1 to make drains snappy silently cuts a teardown's tolerance for a genuinely live presentation holder from five minutes to thirty seconds, and a teardown that then refuses aborts afterremove_grok_turnend_auth, the TASK_TMP removal andretire_busy_statehave already run (bin/fm-teardown.sh:3339). State the multiplier where the knob is documented, in the one owner (fm_status_presentation_lock_timeout's comment plus the drain header line it duplicates).bin/fm-wake-lib.sh:540- Acknowledging the accepted residual, not asking for a change. Round 5 closed the cross-format hole (a format change now reads as PRESENT, covered by test_cross_format_start_token_does_not_evict_a_live_holder), but two tokens in the SAME ps-lstart format that differ only because the date re-rendered still fail[ "$current" != "$recorded" ]and evict a LIVE holder - on$STATE/.watch.lockthat also publishes a false downtime episode via fm_lock_try_acquire line 1075. The base code could never steal a live holder, so this direction of asymmetry is new. Reachability is very narrow and the code says so honestly: the comment at line 68 records that the /proc branch exists precisely because lstart re-renders under wall-clock steps, and the hosts that actually take the ps fallback (macOS, whose lstart derives from a stored absolute p_starttime) do not re-render. Worth having stated rather than rediscovered.tests/fm-wake-queue.test.sh:294- tests/fm-wake-queue.test.sh:294test_secondmate_foreign_queue_stall_tracks_progress_and_alerts_oncefails on this host ("a foreign queue with no progress did not alert"). It fails IDENTICALLY on the base commit 891dc51 with the same fixture, so it is pre-existing and not a regression from this change - but because the suite exits on first failure, it prevents a plainbin/fm-test-run.sh tests/fm-wake-queue.test.shfrom ever reaching the three new status-presentation lock: a dead owner is not reclaimed, so every wake drain blocks until its timeout #3966 cases. I proved those pass by running the suite with only that one case excluded (43 ok, exit 0) and by running the three new cases in isolation. No fix attempted: it is outside this change's scope and touches secondmate wake-stall detection, not the presentation lock.bin/fm-test-run.sh tests/fm-watcher-lock.test.sh tests/fm-wake-queue.test.sh tests/fm-wake-drain-unread-status.test.sh tests/fm-teardown.test.sh(first pass, 4-way bounded concurrency)bin/fm-test-run.sh --jobs 1 tests/fm-watcher-lock.test.sh— 37 ok, exit 0bin/fm-test-run.sh --jobs 1 tests/fm-wake-queue.test.sh— aborts at the pre-existingtest_secondmate_foreign_queue_stall_tracks_progress_and_alerts_oncetests/fm-wake-queue.test.sh with only that pre-existing case excluded — 43 ok, exit 0New cases in isolation:test_recycled_pid_presentation_lock_does_not_wedge_the_drain,test_printed_manual_clear_unwedges_and_strands_nothing,test_printed_manual_clear_is_safe_on_a_home_path_with_a_spaceNew cases in isolation:test_lock_records_owner_start_and_refuses_that_holder,test_lock_steals_reused_pid_lock,test_handoff_records_the_receiving_caller_start,test_unparseable_proc_entry_fails_instead_of_answering_in_ps_format,test_transient_start_token_failure_does_not_poison_later_locks,test_cross_format_start_token_does_not_evict_a_live_holder,test_lock_does_not_steal_live_locktest_arm_hup_cleans_child_and_temp_outputin isolation on BOTH head and base — passes on both, confirming the concurrent-run failure was host loadtest_secondmate_foreign_queue_stall_tracks_progress_and_alerts_onceon base 891dc51 (git archive 891dc51into a temp tree) — fails identically, confirming pre-existingManual A/B repro:FM_STATE_OVERRIDE=<state> FM_STATUS_PRESENTATION_LOCK_TIMEOUT=10 bin/fm-wake-drain.shover a staged.status-presentation-locksymlink whose owner dir records a gone owner on a recycled live pid — base 891dc51 vs head bbd4dcdManual A/B repro:status_retire_presentation_task "$STATE" heldundertimeout 45against the same stranded lock — base spins unbounded, head completesManual operator remedy: legacy pid-only owner dir, then executing verbatim therm -rf ...command the drain advisory printed, then re-drainingManual live-holder case: a realfm_lock_acquire_waitholder held for 12s whilestatus_retire_presentation_taskran withFM_STATUS_PRESENTATION_LOCK_TIMEOUT=2✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.