Skip to content

fix(watcher): publish watch lock identity atomically to close turnend-guard race - #19

Merged
Bre77 merged 1 commit into
mainfrom
fm/fm-turnend-guard-race
Jul 15, 2026
Merged

Bre77 merged 1 commit into
mainfrom
fm/fm-turnend-guard-race

Conversation

@Bre77

@Bre77 Bre77 commented Jul 15, 2026

Copy link
Copy Markdown
Owner

Intent

Fix the fm-turnend-guard.sh false-positive race: the guard was blocking turn ends immediately after bin/fm-watch-arm.sh, reporting no live watcher holds the home lock, even though the watcher was genuinely alive (live pid in state/.watch.lock/pid, beacon touched seconds ago). Root cause verified by reading fm-watch.sh's startup sequence: it published the watch lock's pid file (making fm_pid_alive succeed) before writing the fm-home/watcher-path/pid-identity files that fm_watcher_lock_matches_pid needs to confirm a match, and the gap widened under load because identity computation shells out to ps. Chosen fix (deliberately, over the guard-side bounded-retry alternative mentioned in the task): make the watcher's lock+identity write atomic by threading an optional prep_fn hook through fm_lock_try_create/fm_lock_try_acquire in bin/fm-wake-lib.sh that runs inside the not-yet-published lock owner directory before the ln -s that makes the lock discoverable, so pid and identity become visible to any reader in one atomic step. bin/fm-watch.sh now writes its identity through that hook instead of after the lock is already published. This closes the race at the source rather than papering over it with a guard-side timing retry, and the guard's real purpose (catching a genuinely dead/missing watcher, including the stale-beacon case) is unchanged - only the internal write ordering of fm-watch.sh's own lock claim changed. Added tests/fm-watcher-lock.test.sh::test_lock_prep_fn_publishes_atomically_before_ln, which reproduces the race window deterministically using a slow prep_fn (a controlled 1.5s sleep before the identity write) and asserts the lock stays entirely undiscoverable (no lockdir symlink at all) until the write completes, then asserts pid and identity content both exist once published. Documented the symptom, root cause, and fix in docs/turnend-guard.md (the doc that owns the guard contract, per the repo's one-owner rule for contracts) as a new dated section, following the existing dated-update pattern already used in that file. Verified manually before committing: bin/fm-lint.sh clean on the full repo, and the full existing test suite in tests/fm-watcher-lock.test.sh plus the related suites tests/fm-turnend-guard.test.sh, fm-wake-queue.test.sh, fm-watch-triage.test.sh, fm-watch-checkpoint.test.sh, fm-clickstack.test.sh, fm-tangle-guard.test.sh, fm-daemon.test.sh, fm-supervision-events.test.sh, fm-session-start.test.sh, and fm-pi-watch-extension.test.sh all pass.

What Changed

  • Added an optional prep_fn hook to fm_lock_try_create/fm_lock_try_acquire in bin/fm-wake-lib.sh that runs inside the lock's owner directory before the ln -s publish step, so hook-written content becomes visible atomically with the lock itself.
  • Updated bin/fm-watch.sh to write its identity files (fm-home, watcher-path, pid-identity) through that hook instead of after the lock was already published, eliminating the window where a live pid was visible without a matching identity.
  • Documented the symptom, root cause, and fix in docs/turnend-guard.md, and added tests/fm-watcher-lock.test.sh coverage asserting the lock stays entirely undiscoverable until the prep_fn write completes.

Risk Assessment

✅ Low: Small, well-contained change that threads an optional prep_fn hook through existing lock primitives to make pid+identity publication atomic; the fix is verified against the exact race described (pid visible via ln -s before identity files existed), covered by a deterministic regression test, and both call sites of fm_lock_try_create (normal and steal paths) correctly propagate prep_fn.</risk_rationale>
[]

Testing

The configured baseline test command (all 74 tests/*.test.sh) already passed on the target commit before this session. Beyond that, I built and ran a manual end-to-end repro that starts the real watcher process the way an end user's fm-watch-arm.sh would, and directly confirmed the described race: on the base commit the guard's exact failure precondition (live pid, no matching identity) reproduced in every one of 3 runs with a ~0.4s window; on the target commit the same repro showed pid and identity appearing atomically in all 3 runs, with zero race samples. The new regression test in tests/fm-watcher-lock.test.sh stayed green across 5 repeated runs (no flakiness), and all suites the author listed as manually verified passed. No issues found.

Evidence: E2E race repro script (used against both base and target commits)
#!/usr/bin/env bash
# Manual E2E repro: launches the real bin/fm-watch.sh from a given checkout,
# with `ps` slowed down on PATH (mimicking load, since fm_pid_identity shells
# out to ps), and samples the watch lock at high frequency during startup to
# detect the window where the pid file is live but the identity files
# (fm-home / watcher-path / pid-identity) are not yet present or don't match.
# That window is exactly what caused fm-turnend-guard.sh's false positive.
set -u
REPO_ROOT=$1   # checkout to run bin/fm-watch.sh from
LABEL=$2

WATCH="$REPO_ROOT/bin/fm-watch.sh"
DIR=$(mktemp -d "/tmp/fm-race-repro.$LABEL.XXXXXX")
STATE="$DIR/state"
FAKEBIN="$DIR/fakebin"
mkdir -p "$STATE" "$FAKEBIN"

# fake tmux (fm-watch.sh needs this present, per tests/wake-helpers.sh make_case)
cat > "$FAKEBIN/tmux" <<'SH'
#!/usr/bin/env bash
set -u
if [ "${1:-}" = "list-windows" ]; then
  [ -n "${FM_FAKE_TMUX_WINDOW:-}" ] && printf '%s\n' "$FM_FAKE_TMUX_WINDOW"
  exit 0
fi
if [ "${1:-}" = "capture-pane" ]; then
  [ -n "${FM_FAKE_TMUX_CAPTURE:-}" ] && cat "$FM_FAKE_TMUX_CAPTURE"
  exit 0
fi
exit 1
SH
chmod +x "$FAKEBIN/tmux"

cat > "$FAKEBIN/fm-crew-state.sh" <<'SH'
#!/usr/bin/env bash
set -u
printf 'state: unknown . source: none . fake default\n'
exit 0
SH
chmod +x "$FAKEBIN/fm-crew-state.sh"

# Slow `ps` shim: adds latency to fm_pid_identity's `ps -p ... -o lstart= -o
# command=` call, widening the pid-publish -> identity-write gap the way real
# fleet load does (per the documented root cause).
REAL_PS=$(command -v ps)
cat > "$FAKEBIN/ps" <<SH
#!/usr/bin/env bash
sleep 0.4
exec "$REAL_PS" "\$@"
SH
chmod +x "$FAKEBIN/ps"

out="$DIR/watch.out"
PATH="$FAKEBIN:$PATH" FM_STATE_OVERRIDE="$STATE" FM_POLL=0.2 FM_SIGNAL_GRACE=1 \
  FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 "$WATCH" > "$out" 2>&1 &
wpid=$!

lockdir="$STATE/.watch.lock"
samples=0
bad=0
first_pid_live_at=""
first_identity_ok_at=""
start_ts=$(date +%s.%N 2>/dev/null || date +%s)

for i in $(seq 1 400); do
  now=$(date +%s.%N 2>/dev/null || date +%s)
  pidval=$(cat "$lockdir/pid" 2>/dev/null || true)
  live=no
  if [ -n "$pidval" ] && kill -0 "$pidval" 2>/dev/null; then
    live=yes
    [ -z "$first_pid_live_at" ] && first_pid_live_at=$now
  fi
  idfile_present=no
  [ -s "$lockdir/pid-identity" ] && [ -s "$lockdir/fm-home" ] && [ -s "$lockdir/watcher-path" ] && idfile_present=yes
  if [ "$idfile_present" = yes ] && [ -z "$first_identity_ok_at" ]; then
    first_identity_ok_at=$now
  fi
  if [ "$live" = yes ] && [ "$idfile_present" = no ]; then
    bad=$((bad + 1))
  fi
  samples=$((samples + 1))
  [ "$idfile_present" = yes ] && [ "$live" = yes ] && break
  sleep 0.01
done

kill "$wpid" 2>/dev/null || true
wait "$wpid" 2>/dev/null || true

echo "== $LABEL =="
echo "samples taken: $samples"
echo "samples with LIVE pid but NO/incomplete identity files: $bad"
echo "first pid-live timestamp:      ${first_pid_live_at:-never}"
echo "first identity-complete ts:    ${first_identity_ok_at:-never}"
if [ "$bad" -gt 0 ]; then
  echo "RESULT: race window OBSERVED (guard would false-positive here)"
else
  echo "RESULT: no race window observed"
fi
rm -rf "$DIR"
Evidence: Base commit (c8c9089): real fm-watch.sh startup, slow-ps shim, 3 runs - race window observed every time
== base-run1 ==
samples with LIVE pid but NO/incomplete identity files: 27
first pid-live ts: 1784080810.4426 first identity-complete ts: 1784080810.8641
RESULT: race window OBSERVED
== base-run2 ==
samples with LIVE pid but NO/incomplete identity files: 26
RESULT: race window OBSERVED
== base-run3 ==
samples with LIVE pid but NO/incomplete identity files: 27
RESULT: race window OBSERVED
Evidence: Target commit (b5c6dd1): identical repro, 3 runs - pid and identity always appear atomically, zero race samples
== target-run1 ==
samples with LIVE pid but NO/incomplete identity files: 0
first pid-live ts == first identity-complete ts (same instant)
RESULT: no race window observed
== target-run2 == RESULT: no race window observed
== target-run3 == RESULT: no race window observed

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **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-watcher-lock.test.sh (5x, checking for flakiness in the new prep_fn atomicity test)
  • bash tests/fm-turnend-guard.test.sh
  • bash tests/fm-wake-queue.test.sh
  • bash tests/fm-watch-triage.test.sh
  • bash tests/fm-watch-checkpoint.test.sh
  • bash tests/fm-clickstack.test.sh
  • bash tests/fm-tangle-guard.test.sh
  • bash tests/fm-daemon.test.sh
  • bash tests/fm-supervision-events.test.sh
  • bash tests/fm-session-start.test.sh
  • bash tests/fm-pi-watch-extension.test.sh
  • Manual E2E repro: real bin/fm-watch.sh launched from a temporary worktree of the base commit (c8c9089) and from the target commit, with a slow ps shim on PATH, sampling state/.watch.lock/{pid,pid-identity,fm-home,watcher-path} every 10ms during startup to detect a live-pid-without-identity window (3 runs each commit)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…end-guard.sh

fm-watch.sh published the watch lock's pid file (making the process look
alive) before writing the fm-home/watcher-path/pid-identity files
fm_watcher_lock_matches_pid needs to confirm it. A guard read landing in
that gap saw a live pid with no matching identity yet and misreported "no
live watcher holds this home lock", even though the watcher was mid-startup
and about to finish. The gap widened under load because identity
computation shells out to ps.

fm_lock_try_create/fm_lock_try_acquire now take an optional prep_fn hook
that writes into the lock's owner dir before it is published via ln -s, so
pid and identity become visible to any reader atomically. fm-watch.sh uses
it to write its identity, closing the race at the source.
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