Skip to content

fix(afk): release the away-mode launcher lock on a signal during acquisition - #5

Merged
SchokoShake merged 2 commits into
mainfrom
fm/afk-lock-trap-race-q7
Jul 17, 2026
Merged

SchokoShake merged 2 commits into
mainfrom
fm/afk-lock-trap-race-q7

Conversation

@SchokoShake

Copy link
Copy Markdown
Owner

Intent

Fix a lock-leak trap race in firstmate's away-mode launcher bin/fm-afk-launch.sh that made tests/fm-afk-launch.test.sh flaky and could strand a later away-mode start on a leaked lock. This is firstmate's own shared, tracked material, shipped through the no-mistakes gate.

Root cause: fm_afk_launch_main acquired the launcher lock and only THEN armed the EXIT/INT/TERM traps. A SIGTERM or SIGINT landing in that window terminated the process under the default signal disposition, which skips the not-yet-armed EXIT trap, so the lock directory was never released (leaked).

Deliberate fix decisions in bin/fm-afk-launch.sh:

  • Arm the EXIT/INT/TERM traps BEFORE calling fm_afk_launch_lock_acquire. This is intentional and safe because fm_afk_launch_lock_release only removes a lock this process owns (pid file equals $$) or created but had not yet published; it never touches another launcher's lock. So arming the release trap early cannot wrongly delete a peer's lock, and it guarantees ours is released no matter when a signal lands.
  • Added a new module-level marker FM_AFK_LAUNCH_LOCK_MINE, set to 1 the instant this process's own mkdir creates the lock directory and reset to 0 on release or on any acquire rollback. This is a deliberate new variable plus a new clause in fm_afk_launch_lock_release so that release also cleans up the directory if a signal fires in the tiny window between mkdir and stamping the pid file (an unpublished, self-owned lock). It is guarded so release only removes an unpublished dir when this process created it and no other pid is present.
  • On the acquire-failure path, clear the traps (|| { trap - EXIT INT TERM; return 1; }) so a failed acquisition leaves no trap armed, preserving the original semantics where acquire failure returned with no cleanup trap installed.
  • Reset FM_AFK_LAUNCH_LOCK_MINE=0 on the three in-acquire rollback paths (pid-write, identity-compute, identity-write failures) so the marker never lingers after acquire cleans up its own partial lock.
    The normal-path cleanup (release then trap - EXIT INT TERM at the end of fm_afk_launch_main) is intentionally unchanged.

Deliberate test decisions in tests/fm-afk-launch.test.sh (unit_signal_exits_with_lock_cleanup):

  • Rewrote the signal case to deliver TERM deterministically while the launcher is provably INSIDE fm_afk_launch_lock_acquire holding the lock, using an fm_pid_identity override as a synchronization seam (the same override pattern unit_lock_requires_complete_metadata already uses). The override announces readiness, waits for the test's go-ahead file, then returns a valid identity. This deliberately replaces the old timing-dependent "poll for the lock dir, then kill," which only landed the signal in the vulnerable window on some machines (it failed 6/6 for the reporting crew but 0/6 in this environment), i.e. it was an unreliable detector.
  • Changed the keep-alive stub fm_afk_launch_start from a single foreground "sleep 30" to an interruptible short-sleep loop, because bash defers a caught trap until the current foreground command returns; a 30s sleep therefore delayed the release path by ~30s (the reported ~18-minute hang symptom). Short sleeps let the trap fire promptly. This stub is not on the critical path of the rewritten test but is kept interruptible defensively.
  • Added a deliberate short sleep between the kill and writing the go-ahead file so the buggy launcher dies from the untrapped TERM before the go-ahead lands, keeping the detector deterministic on the old ordering.

Verification performed before committing: the rewritten unit fails 15/15 on the old ordering and passes 15/15 on the new ordering; the full tests/fm-afk-launch.test.sh passes 10/10 in a loop; and bin/fm-lint.sh (the full canonical shellcheck set both gates run) is clean with exit 0 and zero findings. No Markdown was changed. No project files outside firstmate were touched.

What Changed

  • Arm the EXIT/INT/TERM cleanup traps before fm_afk_launch_lock_acquire instead of after, and clear them on the acquire-failure path (trap - EXIT INT TERM), so a signal landing while the lock is held now releases it; the old arm-after-acquire ordering let the default INT/TERM disposition kill the process before any trap was installed, leaking the lock directory and potentially stranding a later away-mode start.
  • Add an FM_AFK_LAUNCH_LOCK_MINE module marker, set the instant this process's own mkdir creates the lock directory and reset on release or on each acquire rollback path, plus a new clause in fm_afk_launch_lock_release so it also reclaims a self-created-but-not-yet-pid-stamped lock while never touching a peer launcher's lock; the trap-guarantee comments were corrected to acknowledge the residual mkdir-call window that acquire's initialization-grace path reaps on the next start.
  • Rewrite the unit_signal_exits_with_lock_cleanup test to deliver TERM deterministically while the launcher is provably inside acquisition — using an fm_pid_identity override as a synchronization seam in place of the flaky poll-the-lock-dir-then-kill approach — and switch the keep-alive stub from a single sleep 30 to an interruptible short-sleep loop so the deferred trap fires promptly.

Risk Assessment

✅ Low: A tightly-scoped, well-reasoned trap-ordering fix plus an accuracy-only comment correction; the release guard provably never touches a peer's lock, all failure/rollback paths reset the new marker and clear traps, and the previously-flagged comment overclaim is now corrected to match the real guarantee.

Testing

Baseline test command and the full tests/fm-afk-launch.test.sh suite both pass (exit 0). I then isolated the fixed test into a focused runner and ran paired controls: 15/15 passes against the fixed launcher (confirming the previously-flaky signal case is now deterministic) and 14/14 deterministic failures against a faithful copy of the pre-fix launcher (confirming the rewritten test actually detects the leak rather than passing vacuously). A CLI transcript artifact demonstrates the real end-user consequence — a SIGTERM while the launcher holds its lifecycle lock leaves the lock directory leaked on the old ordering (would strand a later away-mode start) and released on the fix. This is a shell/CLI-only change with no UI surface, so no visual artifact applies; the CLI transcript is the appropriate end-user-visible evidence. Worktree left clean, all scratch under the evidence dir.

Evidence: Lock leaked (pre-fix) vs released (fixed) after SIGTERM — product demo transcript

== PRE-FIX launcher (28b741d, arm-after-acquire) == lock held before signal? YES (pid=2472601) RESULT: lock directory STILL PRESENT after TERM -> LEAKED (next away-mode start would be stranded) == FIXED launcher (d7a50ba, arm-before-acquire) == lock held before signal? YES (pid=2472640) RESULT: lock directory gone after TERM -> RELEASED (clean; next start unblocked)

Away-mode launcher: SIGTERM while holding the lifecycle lock
Comparing pre-fix (arm-after-acquire) vs fixed (arm-before-acquire)
Date: 2026-07-15T17:20:56Z
========================================================================

== PRE-FIX launcher (28b741d, arm-after-acquire) ==
  lock held before signal? YES (pid=2472601)
  RESULT: lock directory STILL PRESENT after TERM  ->  LEAKED (next away-mode start would be stranded)

== FIXED launcher (d7a50ba, arm-before-acquire) ==
  lock held before signal? YES (pid=2472640)
  RESULT: lock directory gone after TERM            ->  RELEASED (clean; next start unblocked)
Evidence: Paired-control loop results (flakiness fix + detector validity)
POSITIVE (fixed launcher, arm-before-acquire): 15 runs -> PASS=15 FAIL=0
NEGATIVE (pre-fix launcher, arm-after-acquire): 14 runs -> PASS=0 FAIL=14 (deterministic 'interrupted lifecycle resumed or retained its lock')
Evidence: Reproducible leak-demo script
#!/usr/bin/env bash
# Demonstrate the real end-user consequence: a TERM landing while the away-mode
# launcher holds its lifecycle lock. Old ordering LEAKS the lock directory (would
# strand the next away-mode start); fixed ordering RELEASES it.
set -u
launch="$1"; label="$2"
st=$(mktemp -d "${TMPDIR:-/tmp}/leak-demo.XXXXXX")
ready="$st/acquiring"; go="$st/go"; marker="$st/resumed"
lock="$st/state/.afk-launch.lock"

FM_HOME="$st" FM_STATE_OVERRIDE="$st/state" \
  R="$ready" G="$go" M="$marker" bash -c '
    . "$1"
    fm_pid_identity() { local n; touch "$R"; for n in $(seq 1 500); do [ -e "$G" ] && break; sleep 0.02; done; printf "test-identity"; }
    fm_afk_launch_start() { local i; for i in $(seq 1 600); do sleep 0.05; done; }
    fm_afk_launch_main start
    : > "$M"
  ' _ "$launch" &
child=$!
for _ in $(seq 1 250); do [ -e "$ready" ] && [ -s "$lock/pid" ] && break; sleep 0.02; done

echo "== $label =="
echo "  lock held before signal? $( [ -d "$lock" ] && echo YES || echo no ) (pid=$(cat "$lock/pid" 2>/dev/null))"
kill -TERM "$child" 2>/dev/null || true
sleep 0.05
: > "$go"
# bound the wait so a resuming buggy launcher can't hang the demo
( sleep 6; kill -KILL "$child" 2>/dev/null ) & killer=$!
wait "$child" 2>/dev/null || true
kill "$killer" 2>/dev/null || true

if [ -d "$lock" ]; then
  echo "  RESULT: lock directory STILL PRESENT after TERM  ->  LEAKED (next away-mode start would be stranded)"
else
  echo "  RESULT: lock directory gone after TERM            ->  RELEASED (clean; next start unblocked)"
fi
[ -e "$marker" ] && echo "  note: lifecycle also resumed past the signal (marker written)"
rm -rf "$st" 2>/dev/null || true
echo

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • ⚠️ bin/fm-afk-launch.sh:93 - The FM_AFK_LAUNCH_LOCK_MINE marker is set on line 93, the statement immediately AFTER mkdir succeeds (line 92) - but bash runs a caught signal's trap that arrives while mkdir is the foreground command only after mkdir returns, and it runs the deferred trap BEFORE executing line 93. So a TERM/INT landing during the mkdir at line 92 fires the EXIT trap -> fm_afk_launch_lock_release with FM_AFK_LAUNCH_LOCK_MINE still 0 and the just-created (un-stamped) lock directory present; the release guard ([ pid = $$ ] false, [ MINE = 1 ] false) declines to remove it, leaking the lock. I reproduced this 3/3 with a faithful model of the mkdir->MINE=1 sequence (leaked dirs, has-pid=no). This is the exact leak class the change set out to eliminate, so the code comments' guarantee ('released no matter when a signal lands', line 619; 'set to 1 the instant this process's own mkdir creates the lock directory', line 70) is not literally true - the mkdir command's own execution remains uncovered. It is a large improvement and not a regression (the old code leaked this window and much more), and the rewritten test can't observe it because it synchronizes via fm_pid_identity, which runs after the pid stamp. To fully close it: set FM_AFK_LAUNCH_LOCK_MINE=1 on the line BEFORE mkdir and reset it to 0 in the mkdir-failure/else path (release would then reclaim our own just-created empty dir; weigh the narrower, session-lock-mitigated peer-dir race this introduces), or otherwise soften the comment's guarantee to acknowledge the residual mkdir window rather than assert full closure.

🔧 Fix: correct fm-afk-launch lock trap comments to match real guarantee
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
  • bash tests/fm-afk-launch.test.sh (full suite, exit 0; includes 'launcher signal: TERM during lock acquisition releases the held lock')
  • Positive control: focused unit_signal_exits_with_lock_cleanup runner against the fixed launcher x15 -> 15/15 PASS deterministically
  • Negative control: same runner against git show 28b741d:bin/fm-afk-launch.sh (real pre-fix arm-after-acquire ordering) x14 (9 + bounded 5) -> 14/14 FAIL deterministically
  • Product demo: launched fm_afk_launch_main via the fm_pid_identity sync seam, sent SIGTERM while the lock was held, and inspected the .afk-launch.lock directory afterward for pre-fix (leaked) vs fixed (released)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

fm_afk_launch_main acquired the launcher lock and only then armed the
EXIT/INT/TERM traps. A SIGTERM or SIGINT landing in that window killed
the process with the lock held but no cleanup trap installed, leaking
the lock: the default signal disposition terminates without running the
not-yet-armed EXIT trap. This made the signal case in
tests/fm-afk-launch.test.sh flaky and could strand a later away-mode
start on the stale lock.

Arm the EXIT/INT/TERM traps before acquisition. fm_afk_launch_lock_release
only removes a lock this process owns (pid stamped) or created but had
not yet published, so arming it early never touches another launcher's
lock and always releases ours. A new FM_AFK_LAUNCH_LOCK_MINE marker lets
release clean up the directory even if a signal fires in the tiny
mkdir-then-stamp-pid gap.

Rewrite the signal unit to deliver TERM deterministically while the
launcher is inside acquire (an fm_pid_identity synchronization seam)
instead of racing a poll-then-kill, so it fails on the old ordering and
passes on the new one regardless of machine timing.
@SchokoShake
SchokoShake merged commit 528801d into main Jul 17, 2026
@SchokoShake
SchokoShake deleted the fm/afk-lock-trap-race-q7 branch July 17, 2026 06:15
SchokoShake added a commit that referenced this pull request Jul 21, 2026
…awn reuse

Address the review on PR #7:

- treehouse_reservation replaces the boolean holds-check and captures the
  `treehouse status` exit code separately, so a treehouse outage reports
  could-not-ask instead of a false "no longer reserves" on every respawn (#1).
- Match the leased `(held by <holder>)` against this task's fm-<id>, so a
  worktree treehouse re-leased to a different task is caught, not silently
  adopted; an in-use row carries no holder, so the gate only strengthens (#3).
- Cover the lease-release trap for a turn-end hook-block failure between the
  lease and the meta write, the leak class new to this change (#2).
- Record the deliberate readiness-barrier trade at the cd site, marking the
  brief's isolation assertion load-bearing and forbidding a re-added pane probe (#4).
- Make the two treehouse human-text couplings a conscious v2.0.0 assumption;
  v2.0.0 has no --json/--porcelain and both fail loud-but-wrong (#5).

The test treehouse stub now records the real --lease-holder so status renders
the caller's fm-<id>, exercising the holder match faithfully.
SchokoShake added a commit that referenced this pull request Jul 22, 2026
…ane-cwd discovery (#7)

* fix(spawn): capture crew worktree via treehouse get --lease; guard against $FM_HOME

Every projects/* spawn recorded worktree=$FM_HOME (the primary checkout) in
state/<id>.meta instead of the crew's real ~/.treehouse/... worktree, forcing a
manual repair each time and risking teardown/review on the wrong path. The crew
itself was always fine; firstmate-self spawns were immune.

Root cause: worktree discovery sent `treehouse get` into the pane and polled
#{pane_current_path} until it differed from the project dir, taking that as the
worktree. Right after `tmux new-window -c <project>`, the pane process is still
the forked tmux-server child (the shell has not yet exec'd and chdir'd), so
#{pane_current_path} transiently reports the tmux SERVER's own cwd - $FM_HOME
(the server was started there) - before settling on the -c dir a moment later.
The poll's "any path != project dir" exit latched that transient $FM_HOME on the
first iteration of a projects/* spawn ($FM_HOME != $FM_HOME/projects/<repo>),
before `treehouse get` even ran; a firstmate-self spawn ($FM_HOME == project dir)
kept polling to the real worktree - the exact projects/*-only signature. kunchenguid#134's
stable-window-id targeting could not help: the correctly-targeted pane
transiently reports the server cwd.

Fix (bin/fm-spawn.sh):
- Capture authoritatively: lease from fm-spawn itself with `treehouse get
  --lease` (prints only the ~/.treehouse/... path to stdout, banners to stderr)
  and cd the pane into that exact path. No poll, no startup-transient race.
  worktree= and the turn-end hook use the leased path; fm-teardown's existing
  `treehouse return --force <worktree=>` releases it, same as before. Consistent
  with fm-home-seed.sh's existing lease pattern. Applies to every non-orca
  backend and to batch (which re-execs the single path per pair).
- Loud backstop in validate_spawn_worktree: assert the worktree is not the
  primary checkout ($FM_HOME/$FM_ROOT). Because firstmate is a git repo of
  itself, $FM_HOME is a valid git toplevel that cleared every prior clause
  silently; now a regression aborts loudly instead of corrupting meta.

Tests updated to the lease-based capture; new cases pin real-worktree capture
(never $FM_HOME) and the $FM_HOME abort. Docs: tmux-backend.md gains a
root-cause/verification section; architecture.md and herdr-backend.md corrected.
Root cause reproduced with tmux 3.6; fix verified end-to-end against real
treehouse (worktree= records a real .treehouse/... path, pane cd's into it).

Refs fm-spawn-wt-batch-x5.

* test(spawn): strengthen symlinked-prefix test with a tangle case guarding PROJ_ABS_REAL

Review (decision A, captain rule: fix the root cause, do not soften) found the
reframed test_spawn_symlinked_project_prefix_avoids_false_refusal no longer
exercised the PROJ_ABS_REAL canonicalization its comment claimed to guard: its
leased worktree was entirely distinct from the project, so validate_spawn_worktree's
only project-dependent clause (wt_real == proj_real) was never near-triggered and
the test would pass even if PROJ_ABS_REAL regressed to a logical PROJ_ABS.

Add a tangle case: the treehouse stub leases the PROJECT ITSELF reached back
through the symlinked prefix (physical path equal to the project), and the spawn
must be REFUSED with "did not yield an isolated worktree". That refusal holds
ONLY because validate_spawn_worktree resolves both sides with pwd -P; were
PROJ_ABS_REAL the logical PROJ_ABS the physical worktree path would compare
unequal and the tangle would be wrongly allowed. Test-only; bin/fm-spawn.sh
unchanged.

Refs fm-spawn-wt-batch-x5.

* no-mistakes(review): fix(spawn): release treehouse lease on abort; drop dead current_path ops

* no-mistakes(review): fix(spawn): reuse recorded worktree on respawn; refresh stale adapter docs

* no-mistakes(review): fix(spawn): gate respawn reuse on meta identity and lease reservation

* no-mistakes(review): extend respawn identity gate to recorded backend

* no-mistakes(review): scope respawn backend refusal to orca; derive --help range

* no-mistakes(document): sync backend docs with treehouse-lease worktree capture and respawn

* fix(spawn): distinguish treehouse-status failure and re-lease on respawn reuse

Address the review on PR #7:

- treehouse_reservation replaces the boolean holds-check and captures the
  `treehouse status` exit code separately, so a treehouse outage reports
  could-not-ask instead of a false "no longer reserves" on every respawn (#1).
- Match the leased `(held by <holder>)` against this task's fm-<id>, so a
  worktree treehouse re-leased to a different task is caught, not silently
  adopted; an in-use row carries no holder, so the gate only strengthens (#3).
- Cover the lease-release trap for a turn-end hook-block failure between the
  lease and the meta write, the leak class new to this change (#2).
- Record the deliberate readiness-barrier trade at the cd site, marking the
  brief's isolation assertion load-bearing and forbidding a re-added pane probe (#4).
- Make the two treehouse human-text couplings a conscious v2.0.0 assumption;
  v2.0.0 has no --json/--porcelain and both fail loud-but-wrong (#5).

The test treehouse stub now records the real --lease-holder so status renders
the caller's fm-<id>, exercising the holder match faithfully.

* no-mistakes(document): sync tmux worktree-capture doc with --lease-holder flag

---------

Co-authored-by: SchokoShake <[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