Skip to content

fix(bin): bound watcher remote probes and clarify stalled-watcher eviction - #5907

Closed
timur wants to merge 4 commits into
kunchenguid:mainfrom
timur:fm/watcher-remote-timeouts
Closed

timur wants to merge 4 commits into
kunchenguid:mainfrom
timur:fm/watcher-remote-timeouts

Conversation

@timur

@timur timur commented Sep 27, 2026 •

Copy link
Copy Markdown

Intent

Beheben der zwei Watcher-Schwaechen aus dem Untersuchungsbericht data/watcher-remote-hang/report.md (Abschnitte 8.3 und 8.4), Variante (b): klein bauen und upstream an kunchenguid/firstmate beitragen.

Befund (Kurzfassung): Die Watcher-"Haenger" dieser Home waren macOS-Systemschlaf; zwei echte Schwaechen verschaerfen das Symptom: (1) Remote-Aufrufe im Watcher-Zyklus (Secondmate-Liveness-Probe, Pending-Reply-observe, optional Remote-crew-state) haben kein hartes Zeitlimit, und bin/fm-on.sh setzt kein ConnectTimeout/BatchMode - nach dem Aufwachen haengt der Zyklus bis ~1 min, bei echten Netzproblemen theoretisch viel laenger. (2) Die Abloesung eines festgefahrenen Watchers (evict_stalled_holder) wartet nach TERM nur 5 s; bash 3.2 stellt TERM zurueck, solange der Watcher in einer Kommandosubstitution $(...) steckt (so ist der Remote-Probe aufgerufen), daher scheitert die Abloesung sichtbar und der Arm meldet "inspect or stop".

Inhalt der referenzierten Berichtsabschnitte (Substanz des Auftrags):

Messdaten des Berichts: Ueber sieben Tage fielen 33 von 33 Watcher-Ereignissen mit Beacon-Alter >= 300 s in macOS-Schlafphasen (Wachanteil hoechstens 79 s). Ein Minimaltest mit /bin/bash 3.2.57 zeigte: TERM waehrend x=$(sleep 8) wirkt erst nach Rueckkehr der Substitution (t=8 s statt t=1 s), waehrend sleep 8 im Vordergrund und sleep 8 & wait $! das TERM sofort wirken lassen. Im beobachteten Fall kam das Ablöse-TERM an, wirkte aber erst ~20 s spaeter; der Arm hatte nach 5 s schon "inspect or stop" gemeldet. Ein lebender Server mit voller Remote-Job-Queue kann einen einzelnen Probe bis ~12,5 min festhalten, und vor der Authentifizierung greift ServerAlive gar nicht (ssh -G zeigt connecttimeout none).

8.3 Harte Zeitlimits fuer Remote-Aufrufe im Zyklus: (1) bin/fm-on.sh bekommt ConnectTimeout (FM_SSH_CONNECT_TIMEOUT, Default 15 s; deckt TCP-Connect und Banner/KEX ab, wo ServerAlive nicht greift) und BatchMode=yes (keine interaktive Rueckfrage in einem Hintergrundprozess), mit Validierung wie die vorhandenen FM_SSH_ALIVE_*-Werte. (2) Der Liveness-Probe (state, und route im Session-Start-Modus) laeuft mit hartem Zeitlimit (FM_SECONDMATE_PROBE_TIMEOUT, Default 45 s); eine Zeitueberschreitung ist wie ssh-Exit 255 "unbekannt, Route bleibt", niemals "tot" oder relaunch-berechtigt. (3) Pending-Reply-observe ebenso mit Zeitlimit (FM_PENDING_REPLY_OBSERVE_TIMEOUT, Default 20 s); Zeitueberschreitung ergibt "unknown". Das Zeitlimit laeuft ueber fm_run_timed, nicht ueber fm_exec_timed (das ist unter bash 3.2 wegen $BASHPID derzeit kaputt, Upstream-Issue #5847). Optional laut Bericht: (4) dasselbe fuer die Remote-state-Abfrage in fm-crew-state.sh und (5) ein Zyklus-Budget fuer Remote-Arbeit.

8.4 Abloesung korrigieren: (1) Im Watcher die Remote-Aufrufe nicht als $(...) ausfuehren, sondern im Hintergrund mit Ausgabe in eine Datei und wait, damit ein TERM sofort wirkt (bei nativem TERM-Verhalten beendet bash sofort und laeuft ueber den EXIT-Trap). (2) Optional laenger nach TERM warten. (3) Die Meldung nach bereits gesendetem TERM unterscheiden, statt dieselbe "inspect or stop"-Meldung wie ohne TERM zu drucken.

Schlafbewusstes Beacon-Alter (Berichtsabschnitt 8.2) gehoert nicht dazu; das deckt der offene Upstream-PR #5768 ab.

What Changed

  • bin/fm-on.sh now passes BatchMode=yes and ConnectTimeout to SSH. ConnectTimeout comes from FM_SSH_CONNECT_TIMEOUT, defaults to 15 s, and is validated like the existing FM_SSH_ALIVE_* values. A host that accepts the connection but never answers, or a login that would need a prompt, now fails quickly instead of hanging.
  • A new fm_run_timed_capture helper in bin/fm-timeout-lib.sh runs a command through fm_run_timed in the background and puts its stdout in FM_TIMED_CAPTURE. Because the watcher blocks in wait instead of inside $(...), a TERM takes effect at once, including under bash 3.2. The secondmate liveness probe uses it for its remote state/route calls, bounded by FM_SECONDMATE_PROBE_TIMEOUT (default 45 s). If the bound is hit, the state is treated as unknown and the route is kept, never dead. Pending-reply observe also uses it, bounded by FM_PENDING_REPLY_OBSERVE_TIMEOUT (default 20 s); hitting that bound gives unknown.
  • fm-watch.sh records which pid it sent TERM to while evicting a stalled holder. If that same pid still holds the lock after the short wait, the arm now prints "sent TERM to stalled pid … but it has not exited yet" instead of the generic "inspect or stop" message. docs/configuration.md, docs/remote-secondmates.md and docs/turnend-guard.md document the new settings and this behavior. Tests cover each change.

Risk Assessment

✅ Low: The fix-round change now gates the sent-TERM refusal on the exact pid that was TERMed. Any other live stale holder falls through to the prior 'inspect or stop' path. The rest of the change is bounded and covered by behavioral tests with no source-grep assertions: remote probe and observe timeouts that preserve the route and report unknown rather than dead, wait-based capture so TERM lands at once, and ConnectTimeout plus BatchMode in fm-on.sh with validation.

Testing

I ran the targeted test files for the changed libraries: fm-on, secondmate-liveness, pending-reply, the watcher-lock eviction cases, and the new fm_run_timed_capture cases. All pass under /bin/bash 3.2. The full fm-timeout-lib file still aborts on the known, already-failing fm_exec_timed case (#5847), which fails the same way on base. I then drove the product live in throwaway marked lab homes with real OpenSSH and a TCP peer that accepts but never answers: - fm-on ConnectTimeout: gives up after about 3.5s with exit 255. Base hangs until an outer 20s alarm kills it. - Effective ssh options: ssh -G shows batchmode yes and connecttimeout 15 (or the override). Base shows batchmode no and connecttimeout none. - Invalid values: bad FM_SSH_CONNECT_TIMEOUT values are refused before ssh starts. - Watcher-cycle liveness probe: returns unknown with the route preserved after 3s, and the route meta is unchanged. - Stalled watcher: a live watcher stuck inside a real ssh probe is evicted and replaced within 0.5s of the re-arm. On base the same regression test is refused with "inspect or stop". - Refusal messages: a holder that ignores TERM gets the new "sent TERM … not exited yet" refusal. A rival watcher that was never signalled gets the ordinary refusal on HEAD but the wrong "sent TERM" message on the pre-fix commit. The change has no UI, so the artifacts are CLI transcripts. Three scenarios were not driven live: the session-start route read timeout, TERM delivery during fm_run_timed_capture, and the pending-reply observe timeout. The last two have unit-test coverage only.

  • Live validation: ✅ go - 7 of 10 scenarios driven live against the product
Scenario Result Live Evidence
fm-on.sh against a host that accepts TCP but never sends an SSH banner gives up after FM_SSH_CONNECT_TIMEOUT with exit 255 instead of hanging ✅ pass live live-lab-transcript.txt S1: HEAD rc=255 after 3.5s with 'Connection timed out during banner exchange'; base fba81cb still hanging when an outer 20s alarm killed it (rc=142)
fm-on.sh passes BatchMode=yes and ConnectTimeout (default 15, overridable) to the real OpenSSH client ✅ pass live live-lab-transcript.txt S2: ssh -G on fm-on's real argv shows 'batchmode yes', 'connecttimeout 15'; with FM_SSH_CONNECT_TIMEOUT=7 it shows 'connecttimeout 7'; base shows 'batchmode no', 'connecttimeou…
Invalid FM_SSH_CONNECT_TIMEOUT (0, text, negative) is refused before ssh is launched ✅ pass live live-lab-transcript.txt S3: each value exits 1 with 'FM_SSH_CONNECT_TIMEOUT must be a positive integer', and the canary ssh never printed SSH-LAUNCHED
Watcher-cycle (poll) liveness probe through real ssh that hangs is cut at FM_SECONDMATE_PROBE_TIMEOUT and reads as unknown with the route preserved, never dead ✅ pass live live-lab-transcript.txt S4: 'mode=poll status=skipped state=unknown kill=0 reason=remote endpoint probe timed out after 3s on lab-host; route preserved'; meta unchanged; tests/fm-secondmate-liveness.t…
A watcher stuck inside a real remote ssh probe (bash 3.2) is evicted by the next arm, which reports 'replaced stalled pid' ✅ pass live live-lab-transcript.txt S5: holder evicted within 0.5s, lock moved to the new arm, stdout 'watcher: replaced stalled pid 46799 (...)'; the same regression test fails on base with 'inspect or stop'
A holder that is TERMed but has not exited gets the distinct 'sent TERM ... has not exited yet' refusal instead of 'inspect or stop' ✅ pass live live-lab-transcript.txt S7: arm rc=1 with 'watcher: sent TERM to stalled pid 48249 (...) but it has not exited yet'
Adversarial (review decision): after X evicts A, a rival B that X never signalled holds the lock with a stale beacon; X must not claim it sent TERM to B ✅ pass live live-lab-rival-after-evict-transcript.txt (HEAD): 'lock held by live pid <B> ... inspect or stop'; pre-review-fix-rival.txt (12e3ddc): wrongly 'sent TERM to stalled pid <B>'
A TERM to a supervisor blocked in fm_run_timed_capture under bash 3.2 lands at once and runs its EXIT trap, while status/output pass through and the bound holds ⏸️ untested no The prior payload did not establish a live result. The only support was the unit test log test-fm-timeout-lib-capture-cases.log, where 4 cases passed under /bin/bash 3.2. No run TERMed a real supervis…
Pending-reply remote observe that hangs past FM_PENDING_REPLY_OBSERVE_TIMEOUT reads as unknown ⏸️ untested no The prior payload did not establish a live result. The only support was the unit test log test-fm-pending-reply.log, which covered the observe timeout case at 2s. No run drove the pending-reply observ…
Session-start (full mode) remote route read is bounded by FM_SECONDMATE_PROBE_TIMEOUT ⏸️ untested no Reaching the route read needs a real remote secondmate whose fm-remote-doctor readiness check passes and whose state reads alive. No such remote host or SSH login is available in this gate. The live f…
Evidence: Live lab transcript (fm-on connect timeout HEAD vs base, ssh -G options, invalid values, probe timeout, live eviction, sent-TERM refusal)

Source: Live lab transcript (fm-on connect timeout HEAD vs base, ssh -G options, invalid values, probe timeout, live eviction, sent-TERM refusal)


=== S1 fm-on.sh (this change) vs silent peer, FM_SSH_CONNECT_TIMEOUT=3
Connection timed out during banner exchange
Connection to 127.0.0.1 port 52102 timed out
rc=255 elapsed=3.5s

=== S1-base fm-on.sh (base fba81cb) vs same silent peer, outer alarm 20s
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-drive.sh: line 58: 95804 Alarm clock: 14         "${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh" perl -e 'alarm 20; exec @ARGV' "$BASE/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 < /dev/null
rc=142 (142=killed by outer SIGALRM, i.e. still hanging) elapsed=20.1s

=== S2 effective OpenSSH options fm-on.sh passes (ssh -G on the real argv), default and override
batchmode yes
serveralivecountmax 3
serveraliveinterval 15
connecttimeout 15
-- FM_SSH_CONNECT_TIMEOUT=7:
connecttimeout 7
-- base fba81cb for comparison:
batchmode no
connecttimeout none

=== S3 invalid FM_SSH_CONNECT_TIMEOUT refused before ssh runs
error: FM_SSH_CONNECT_TIMEOUT must be a positive integer: 0
FM_SSH_CONNECT_TIMEOUT=0 -> rc=1
error: FM_SSH_CONNECT_TIMEOUT must be a positive integer: soon
FM_SSH_CONNECT_TIMEOUT=soon -> rc=1
error: FM_SSH_CONNECT_TIMEOUT must be a positive integer: -5
FM_SSH_CONNECT_TIMEOUT=-5 -> rc=1

=== S4 liveness probe through real ssh held past connect (ConnectTimeout=120), FM_SECONDMATE_PROBE_TIMEOUT=3
mode=poll status=skipped state=unknown kill=0 reason=remote endpoint probe timed out after 3s on lab-host; route preserved
mode=full status=skipped state=unknown kill=0 reason=remote host unavailable or endpoint state unknown; route preserved on lab-host
elapsed for both probes=123.6s
route meta unchanged: yes

=== S5 watcher stalled inside a real remote probe (real ssh, ConnectTimeout=120, probe timeout 120) is evicted by a re-arm
holder watcher pid=46799; lock pid=46799; ssh in flight: 47124 
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-drive.sh: line 100: 46799 Terminated: 15          "${WENV[@]}" FM_SECONDMATE_LIVENESS_SECS=1 FM_SECONDMATE_PROBE_TIMEOUT=120 "$W" > "$LAB/holder.out" 2>&1
after re-arm: lock pid=47390 (arm2=47390) elapsed=0.5s
holder alive: no (evicted)
arm2 stdout:
watcher: replaced stalled pid 46799 (beacon 843835398s past hard bound 3s)
arm2 stderr:

=== S6 adversarial: a third arm against healthy arm2 with a stale-but-under-hard-bound beacon is NOT told it sent TERM
arm3 rc=0

=== S7 holder that survives its TERM gets the distinct sent-TERM refusal
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-drive.sh: line 112: kill: (47390) - No such process
arm4 rc=1
watcher: sent TERM to stalled pid 48249 (beacon 843835400s past hard bound 3s) but it has not exited yet; it exits once its current command returns, so re-arm again shortly.

=== done; lab removed on exit
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-drive.sh: line 14: 95573 Terminated: 15          perl -MIO::Socket::INET -e '
  my $s = IO::Socket::INET->new(LocalAddr=>"127.0.0.1",LocalPort=>0,Listen=>16,ReuseAddr=>1) or die;
  open(my $f,">",$ARGV[0]) or die; print $f $s->sockport,"\n"; close $f;
  alarm 300; my @h; while (my $c=$s->accept) { push @h,$c }' "$LAB/port"
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-drive.sh: line 14: 48249 Killed: 9               /bin/bash -c 'trap "" TERM; exec sleep 300'
Evidence: Live lab driver script

Source: Live lab driver script

#!/bin/bash
# Live lab drive for fm/watcher-remote-timeouts: real OpenSSH, real /bin/bash 3.2,
# real bin/fm-on.sh, bin/fm-secondmate-liveness-lib.sh and bin/fm-watch.sh against
# a disposable marked lab home and a silent TCP peer (accepts, never sends a
# banner - what a just-woken or wedged remote looks like to ssh).
# Usage: live-lab-drive.sh <worktree> <base-checkout>
set -u
WT=$1 BASE=$2
LAB=$(mktemp -d "${TMPDIR:-/tmp}/fm-lab.XXXXXX")
rmdir "$LAB"; "$WT/bin/fm-lab-home.sh" create "$LAB" >/dev/null
mkdir -p "$LAB/tmux" "$LAB/bin"
export TMUX_TMPDIR="$LAB/tmux"; unset TMUX TMUX_PANE
PIDS=()
cleanup() { for p in "${PIDS[@]:-}"; do [ -n "$p" ] && kill "$p" 2>/dev/null; done; pkill -f "ssh -F $LAB/" 2>/dev/null; rm -rf "$LAB"; }
trap cleanup EXIT
say() { printf '\n=== %s\n' "$*"; }
now() { perl -MTime::HiRes=time -e 'printf "%.1f", time'; }

# silent peer
perl -MIO::Socket::INET -e '
  my $s = IO::Socket::INET->new(LocalAddr=>"127.0.0.1",LocalPort=>0,Listen=>16,ReuseAddr=>1) or die;
  open(my $f,">",$ARGV[0]) or die; print $f $s->sockport,"\n"; close $f;
  alarm 300; my @h; while (my $c=$s->accept) { push @h,$c }' "$LAB/port" &
PIDS+=($!)
while [ ! -s "$LAB/port" ]; do sleep 0.1; done
cat > "$LAB/ssh.config" <<EOF
Host lab-host
  HostName 127.0.0.1
  Port $(cat "$LAB/port")
  StrictHostKeyChecking yes
  UserKnownHostsFile /dev/null
EOF
printf '#!/bin/bash\nexec ssh -F %s/ssh.config "$@"\n' "$LAB" > "$LAB/bin/ssh"
printf '#!/bin/bash\nexec ssh -F %s/ssh.config -G "$@"\n' "$LAB" > "$LAB/bin/ssh-G"
chmod +x "$LAB/bin/ssh" "$LAB/bin/ssh-G"
printf -- '- rsm1 - Remote mate (host: lab-host; root: /remote/root; home: /remote/rsm1-home; scope: remote work; projects: alpha; added 2026-01-01)\n' > "$LAB/data/secondmates.md"
cat > "$LAB/state/rsm1.meta" <<EOF
window=remote:rsm1
kind=secondmate
harness=claude
remote_host=lab-host
remote_backend=herdr
remote_herdr_session=fm-remote
remote_target=fm-remote:w1:p1
home=/remote/rsm1-home
EOF
CLEAN=(env -u NO_MISTAKES_GATE -u FM_GATE_REFUSE_BYPASS -u FM_ROOT_OVERRIDE -u FM_STATE_OVERRIDE -u FM_DATA_OVERRIDE -u FM_CONFIG_OVERRIDE -u FM_PROJECTS_OVERRIDE FM_HOME="$LAB")

say "S1 fm-on.sh (this change) vs silent peer, FM_SSH_CONNECT_TIMEOUT=3"
t0=$(now)
"${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh" FM_SSH_CONNECT_TIMEOUT=3 perl -e 'alarm 40; exec @ARGV' \
  "$WT/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null; rc=$?
echo "rc=$rc elapsed=$(perl -e "printf '%.1f', $(now)-$t0")s"

say "S1-base fm-on.sh (base fba81cb) vs same silent peer, outer alarm 20s"
t0=$(now)
"${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh" perl -e 'alarm 20; exec @ARGV' \
  "$BASE/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null; rc=$?
echo "rc=$rc (142=killed by outer SIGALRM, i.e. still hanging) elapsed=$(perl -e "printf '%.1f', $(now)-$t0")s"

say "S2 effective OpenSSH options fm-on.sh passes (ssh -G on the real argv), default and override"
"${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh-G" "$WT/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null \
  | grep -E '^(batchmode|connecttimeout|serveraliveinterval|serveralivecountmax) '
echo "-- FM_SSH_CONNECT_TIMEOUT=7:"
"${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh-G" FM_SSH_CONNECT_TIMEOUT=7 "$WT/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null \
  | grep -E '^connecttimeout '
echo "-- base fba81cb for comparison:"
"${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh-G" "$BASE/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null \
  | grep -E '^(batchmode|connecttimeout) '

say "S3 invalid FM_SSH_CONNECT_TIMEOUT refused before ssh runs"
for bad in 0 soon -5; do
  printf '#!/bin/bash\necho SSH-LAUNCHED >&2\n' > "$LAB/bin/ssh-canary"; chmod +x "$LAB/bin/ssh-canary"
  "${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh-canary" FM_SSH_CONNECT_TIMEOUT=$bad "$WT/bin/fm-on.sh" rsm1 fm-remote-secondmate-control.sh state rsm1 </dev/null
  echo "FM_SSH_CONNECT_TIMEOUT=$bad -> rc=$?"
done

say "S4 liveness probe through real ssh held past connect (ConnectTimeout=120), FM_SECONDMATE_PROBE_TIMEOUT=3"
cp "$LAB/state/rsm1.meta" "$LAB/meta.before"
t0=$(now)
"${CLEAN[@]}" STATE="$LAB/state" FM_SSH_BIN="$LAB/bin/ssh" FM_SSH_CONNECT_TIMEOUT=120 FM_SECONDMATE_PROBE_TIMEOUT=3 \
  /bin/bash -c '. "$0/bin/fm-secondmate-liveness-lib.sh"; for m in poll full; do fm_secondmate_liveness_probe "$1" rsm1 $m;
    printf "mode=%s status=%s state=%s kill=%s reason=%s\n" $m "$FM_SM_LIVE_STATUS" "$FM_SM_LIVE_STATE" "$FM_SM_LIVE_KILL" "$FM_SM_LIVE_REASON"; done' \
  "$WT" "$LAB/state/rsm1.meta"
echo "elapsed for both probes=$(perl -e "printf '%.1f', $(now)-$t0")s"
cmp -s "$LAB/meta.before" "$LAB/state/rsm1.meta" && echo "route meta unchanged: yes" || echo "route meta unchanged: NO"

say "S5 watcher stalled inside a real remote probe (real ssh, ConnectTimeout=120, probe timeout 120) is evicted by a re-arm"
W="$WT/bin/fm-watch.sh"
WENV=("${CLEAN[@]}" FM_SSH_BIN="$LAB/bin/ssh" FM_SSH_CONNECT_TIMEOUT=120 FM_GUARD_GRACE=1 FM_POLL=5 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999)
"${WENV[@]}" FM_SECONDMATE_LIVENESS_SECS=1 FM_SECONDMATE_PROBE_TIMEOUT=120 "$W" > "$LAB/holder.out" 2>&1 &
HOLDER=$!; PIDS+=($HOLDER)
for i in $(seq 1 300); do pgrep -f "ssh -F $LAB/ssh.config" >/dev/null && break; sleep 0.1; done
echo "holder watcher pid=$HOLDER; lock pid=$(cat "$LAB/state/.watch.lock/pid" 2>/dev/null); ssh in flight: $(pgrep -f "ssh -F $LAB/ssh.config" | tr '\n' ' ')"
sleep 1
touch -t 200001010000 "$LAB/state/.last-watcher-beat"   # beacon as after a long sleep
t0=$(now)
"${WENV[@]}" FM_WATCHER_STALL_BOUND=3 FM_SECONDMATE_LIVENESS_SECS=999999 "$W" > "$LAB/arm2.out" 2> "$LAB/arm2.err" &
ARM2=$!; PIDS+=($ARM2)
for i in $(seq 1 150); do [ "$(cat "$LAB/state/.watch.lock/pid" 2>/dev/null)" = "$ARM2" ] && break; kill -0 $ARM2 2>/dev/null || break; sleep 0.1; done
echo "after re-arm: lock pid=$(cat "$LAB/state/.watch.lock/pid" 2>/dev/null) (arm2=$ARM2) elapsed=$(perl -e "printf '%.1f', $(now)-$t0")s"
kill -0 $HOLDER 2>/dev/null && echo "holder alive: YES" || echo "holder alive: no (evicted)"
sleep 1; echo "arm2 stdout:"; grep -E '^watcher:' "$LAB/arm2.out"; echo "arm2 stderr:"; cat "$LAB/arm2.err"

say "S6 adversarial: a third arm against healthy arm2 with a stale-but-under-hard-bound beacon is NOT told it sent TERM"
touch -t "$(date -v-40S +%Y%m%d%H%M.%S)" "$LAB/state/.last-watcher-beat"
"${WENV[@]}" FM_WATCHER_STALL_BOUND=999999 FM_WATCHER_STALE_GRACE=5 "$W" > "$LAB/arm3.out" 2> "$LAB/arm3.err"; echo "arm3 rc=$?"
cat "$LAB/arm3.err"
kill -0 $ARM2 2>/dev/null && echo "arm2 still alive and holding: $(cat "$LAB/state/.watch.lock/pid")"

say "S7 holder that survives its TERM gets the distinct sent-TERM refusal"
kill $ARM2; wait $ARM2 2>/dev/null
/bin/bash -c 'trap "" TERM; exec sleep 300' & STUB=$!; PIDS+=($STUB); sleep 0.2
ID=$(FM_STATE_OVERRIDE="$LAB/state" /bin/bash -c '. "$1"; fm_pid_identity "$2"' _ "$WT/bin/fm-wake-lib.sh" $STUB)
rm -rf "$LAB/state/.watch.lock"; mkdir -p "$LAB/state/.watch.lock"
printf '%s\n' $STUB > "$LAB/state/.watch.lock/pid"; printf '%s\n' "$LAB" > "$LAB/state/.watch.lock/fm-home"
printf '%s\n' "$W" > "$LAB/state/.watch.lock/watcher-path"; printf '%s\n' "$ID" > "$LAB/state/.watch.lock/pid-identity"
touch -t 200001010000 "$LAB/state/.last-watcher-beat"
"${WENV[@]}" FM_WATCHER_STALL_BOUND=3 "$W" > "$LAB/arm4.out" 2> "$LAB/arm4.err"; echo "arm4 rc=$?"; cat "$LAB/arm4.err"
kill -KILL $STUB 2>/dev/null
say "done; lab removed on exit"
Evidence: Rival-after-eviction adversarial run on HEAD (its pre-fix section is invalid due to a /var path mismatch; see the corrected pre-fix file)

Source: Rival-after-eviction adversarial run on HEAD (its pre-fix section is invalid due to a /var path mismatch; see the corrected pre-fix file)

[HEAD 3f80729] holder A=66048 holds the lock; beacon stale
[HEAD 3f80729] arm X rc=1; A alive: no; rival B=66233 alive: yes; lock pid now: 66233
[HEAD 3f80729] X stdout: 
[HEAD 3f80729] X stderr: watcher: lock held by live pid 66233 but heartbeat is stale for 843835457s (>1s); inspect or stop that watcher before re-arming.

[pre-review-fix 12e3ddc] holder A=66316 holds the lock; beacon stale
[pre-review-fix 12e3ddc] arm X rc=1; A alive: yes; rival B= alive: no; lock pid now: 66316
[pre-review-fix 12e3ddc] X stdout: 
[pre-review-fix 12e3ddc] X stderr: watcher: lock held by live pid 66316 but heartbeat is stale for 843835459s (>1s); inspect or stop that watcher before re-arming.
~/.no-mistakes/evidence/01M3HGS0EMAQYCNX2RZC92JK34/live-lab-rival-after-evict.sh: line 33: 66316 Killed: 9               /bin/bash -c 'trap '"'"'/bin/bash -c "trap \"\" TERM; exec sleep 120" & echo $! > "$LAB/B.pid"; write_lock $!; exit 0'"'"' TERM; while :; do sleep 0.05; done'
Evidence: Rival-after-eviction on pre-review-fix 12e3ddc (shows the wrong 'sent TERM' message to a rival never signalled)

Source: Rival-after-eviction on pre-review-fix 12e3ddc (shows the wrong 'sent TERM' message to a rival never signalled)

[pre-review-fix 12e3ddc] holder A=71776 holds the lock; beacon stale
[pre-review-fix 12e3ddc] arm X rc=1; A alive: no; rival B=71962 alive: yes; lock pid now: 71962
[pre-review-fix 12e3ddc] X stdout: 
[pre-review-fix 12e3ddc] X stderr: watcher: sent TERM to stalled pid 71962 (beacon 843835471s past hard bound 3s) but it has not exited yet; it exits once its current command returns, so re-arm again shortly.
Evidence: Rival-after-eviction driver script

Source: Rival-after-eviction driver script

#!/bin/bash
# Adversarial live drive of the review-round decision: arm X TERMs stalled
# holder A; A exits, but in the same instant a rival B (a live, TERM-ignoring
# process X never signalled) holds the lock with the beacon still stale.
# X must NOT claim it "sent TERM" to B; it must give the ordinary refusal.
# Usage: live-lab-rival-after-evict.sh <checkout-with-bin/fm-watch.sh> <label>
set -u
WT=$1 LABEL=$2
LAB=$(mktemp -d "${TMPDIR:-/tmp}/fm-lab.XXXXXX"); rmdir "$LAB"
"$WT/bin/fm-lab-home.sh" create "$LAB" >/dev/null 2>&1 || { mkdir -p "$LAB/state" "$LAB/data" "$LAB/config"; }
mkdir -p "$LAB/tmux"; export TMUX_TMPDIR="$LAB/tmux"; unset TMUX TMUX_PANE
W="$WT/bin/fm-watch.sh"; LIB="$WT/bin/fm-wake-lib.sh"; S="$LAB/state"
write_lock() {  # <pid>
  local id; id=$(FM_STATE_OVERRIDE="$S" /bin/bash -c '. "$1"; fm_pid_identity "$2"' _ "$LIB" "$1")
  rm -rf "$S/.watch.lock"; mkdir -p "$S/.watch.lock"
  printf '%s\n' "$1" > "$S/.watch.lock/pid"; printf '%s\n' "$LAB" > "$S/.watch.lock/fm-home"
  printf '%s\n' "$W" > "$S/.watch.lock/watcher-path"; printf '%s\n' "$id" > "$S/.watch.lock/pid-identity"
}
export -f write_lock; export S LAB W LIB
# Holder A: on TERM, starts rival B, hands B the lock, then exits.
/bin/bash -c 'trap '"'"'/bin/bash -c "trap \"\" TERM; exec sleep 120" & echo $! > "$LAB/B.pid"; write_lock $!; exit 0'"'"' TERM; while :; do sleep 0.05; done' &
A=$!; sleep 0.3; write_lock "$A"
touch -t 200001010000 "$S/.last-watcher-beat"
echo "[$LABEL] holder A=$A holds the lock; beacon stale"
env -u NO_MISTAKES_GATE -u FM_GATE_REFUSE_BYPASS -u FM_ROOT_OVERRIDE -u FM_STATE_OVERRIDE -u FM_DATA_OVERRIDE -u FM_CONFIG_OVERRIDE -u FM_PROJECTS_OVERRIDE \
  FM_HOME="$LAB" FM_GUARD_GRACE=1 FM_WATCHER_STALL_BOUND=3 FM_POLL=5 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 \
  "$W" > "$LAB/x.out" 2> "$LAB/x.err"; rc=$?
B=$(cat "$LAB/B.pid" 2>/dev/null)
echo "[$LABEL] arm X rc=$rc; A alive: $(kill -0 $A 2>/dev/null && echo yes || echo no); rival B=$B alive: $(kill -0 "$B" 2>/dev/null && echo yes || echo no); lock pid now: $(cat "$S/.watch.lock/pid")"
echo "[$LABEL] X stdout: $(cat "$LAB/x.out")"
echo "[$LABEL] X stderr: $(cat "$LAB/x.err")"
[ -n "$B" ] && kill -KILL "$B" 2>/dev/null; kill -KILL "$A" 2>/dev/null
rm -rf "$LAB"
Evidence: Base fba81cb fails the stalled-in-remote-probe eviction regression

Source: Base fba81cb fails the stalled-in-remote-probe eviction regression

not ok - a holder stalled in its remote probe was not replaced (holder=57546): watcher: lock held by live pid 57546 but heartbeat is stale for 843835158s (>1s); inspect or stop that watcher before re-arming.

not ok - a holder stalled in its remote probe was not replaced (holder=57546): watcher: lock held by live pid 57546 but heartbeat is stale for 843835158s (>1s); inspect or stop that watcher before re-arming.
Evidence: Watcher-lock eviction cases on HEAD

Source: Watcher-lock eviction cases on HEAD

ok - live watcher lock with stale heartbeat is actionable
ok - live watcher lock with a beacon past the hard bound is replaced, under it is still refused
ok - a holder stalled inside a remote probe is evicted and replaced
ok - a holder still finishing after its TERM is refused with its own message
Evidence: fm_run_timed_capture cases under /bin/bash 3.2

Source: fm_run_timed_capture cases under /bin/bash 3.2

ok - fm_run_timed_capture passes a command's status and stdout through
ok - fm_run_timed_capture reports 124 at the bound (2s against a 30s hang)
ok - fm_run_timed_capture keeps waiting for the call's own status through a trapped signal
ok - a TERM to a caller blocked in fm_run_timed_capture lands at once (0s) and leaves no capture file
Evidence: fm-on / liveness / pending-reply test logs

Source: fm-on / liveness / pending-reply test logs

ok - fm-on --stdin preserves argv, stdin, stdout, stderr, and exit status without shell interpretation
ok - fm-on defaults the remote command's stdin to /dev/null
ok - fm-on arms a bounded SSH dead-peer detection window by default (15s x 3 = 45s)
ok - fm-on's dead-peer detection window is env-overridable
ok - fm-on rejects invalid dead-peer settings before launching ssh
/private/var/folders/46/qpqgfq513dgf_579qvkwwpq40000gn/T/fm-on.PmH6pe/remote-root/bin/fm-remote-job-worker.sh: child setpgid (18217 to 18217): Operation not permitted
ok - fm-on bounds connection setup, runs ssh in batch mode, and validates FM_SSH_CONNECT_TIMEOUT
ok - fm-on gives up on a peer that never sends a banner after the connect timeout (2s, exit 255)
ok - the fixed entrypoint runs every command in the worker's explicit environment
ok - the entrypoint composes a deduplicated discovered child PATH (kept 16 existing, omitted 7 absent)
ok - read-only doctor inspects worker gaps over plain SSH without repair
ok - the remote doctor reports the same PATH the entrypoint hands its children
ok - the remote doctor derives tool readiness from the installed worker
ok - the remote doctor reports its required runtime tool set and optional tools
ok - multiple fm-*.sh executables work without a command table
ok - tracked-command authorization excludes checkout-local git
ok - doctor bootstrap remains authenticated when git is unavailable
ok - transport rejects shell escape, traversal, symlink, and option-injection surfaces
ok - the fixed entrypoint refuses incompatible protocols and unsafe roots
ok - ambiguous aliases refuse while exact secondmate ids remain routable
ok - unreachable and ambiguous transport failures are surfaced without retry
ALL TESTS PASSED
- Outcome: ⚠️ 2 infos across 1 run (11m50s)

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-watch.sh:2397 - The new "sent TERM to stalled pid ... but it has not exited yet" refusal is gated only on EVICT_TERM_SENT, which stays 1 after a successful eviction. Here is a sequence where it fires wrongly. Arm X TERMs stalled holder A, A exits, evict_stalled_holder succeeds (EVICTED_PID=A), and the loop continues. Meanwhile rival arm B takes the lock. B only touches .last-watcher-beat at line 2641, after its startup work, so X re-reads a live holder B with a beacon that is still stale. X skips eviction because EVICTED_PID is set, then prints "watcher: sent TERM to stalled pid B ... but it has not exited yet". X never signalled B, and B is a healthy new watcher. Two arms racing like this is plausible after a machine wakes from sleep, which is the scenario this change targets. Fix: record the pid that was TERMed (e.g. EVICT_TERM_PID=$pid inside evict_stalled_holder) and print this message only when it equals FM_LOCK_HELD_PID and EVICTED_PID is empty. Otherwise keep the old path, or treat B as an already-running watcher.

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Test** - 2 infos
  • ℹ️ bin/fm-secondmate-liveness-lib.sh:158 - In full (bootstrap) mode the probe first runs fm_remote_readiness_ensure: up to three fm-on.sh ... fm-remote-doctor.sh calls as plain $(...) substitutions with no FM_SECONDMATE_PROBE_TIMEOUT bound. Live, against a silent peer with FM_SSH_CONNECT_TIMEOUT=120, the full probe took about 120s. It is still bounded by the new ConnectTimeout (default 15s per call). The watcher cycle uses poll mode only, so this is outside the stated intent, which covers the watcher cycle.
  • ℹ️ tests/fm-timeout-lib.test.sh:52 - On macOS bash 3.2 the first case (fm_exec_timed status passthrough) fails and aborts the file before the new fm_run_timed_capture cases run. This is the known upstream fm-timeout-lib.sh: bare $BASHPID breaks fm-spawn on stock macOS Bash 3.2 #5847 ($BASHPID) and it fails the same way on base fba81cb. I ran the new capture cases on their own and they pass.
  • Live validation: ✅ go - 7 of 10 scenarios driven live against the product
Scenario Result Live Evidence
fm-on.sh against a host that accepts TCP but never sends an SSH banner gives up after FM_SSH_CONNECT_TIMEOUT with exit 255 instead of hanging ✅ pass live live-lab-transcript.txt S1: HEAD rc=255 after 3.5s with 'Connection timed out during banner exchange'; base fba81cb still hanging when an outer 20s alarm killed it (rc=142)
fm-on.sh passes BatchMode=yes and ConnectTimeout (default 15, overridable) to the real OpenSSH client ✅ pass live live-lab-transcript.txt S2: ssh -G on fm-on's real argv shows 'batchmode yes', 'connecttimeout 15'; with FM_SSH_CONNECT_TIMEOUT=7 it shows 'connecttimeout 7'; base shows 'batchmode no', 'connecttimeou…
Invalid FM_SSH_CONNECT_TIMEOUT (0, text, negative) is refused before ssh is launched ✅ pass live live-lab-transcript.txt S3: each value exits 1 with 'FM_SSH_CONNECT_TIMEOUT must be a positive integer', and the canary ssh never printed SSH-LAUNCHED
Watcher-cycle (poll) liveness probe through real ssh that hangs is cut at FM_SECONDMATE_PROBE_TIMEOUT and reads as unknown with the route preserved, never dead ✅ pass live live-lab-transcript.txt S4: 'mode=poll status=skipped state=unknown kill=0 reason=remote endpoint probe timed out after 3s on lab-host; route preserved'; meta unchanged; tests/fm-secondmate-liveness.t…
A watcher stuck inside a real remote ssh probe (bash 3.2) is evicted by the next arm, which reports 'replaced stalled pid' ✅ pass live live-lab-transcript.txt S5: holder evicted within 0.5s, lock moved to the new arm, stdout 'watcher: replaced stalled pid 46799 (...)'; the same regression test fails on base with 'inspect or stop'
A holder that is TERMed but has not exited gets the distinct 'sent TERM ... has not exited yet' refusal instead of 'inspect or stop' ✅ pass live live-lab-transcript.txt S7: arm rc=1 with 'watcher: sent TERM to stalled pid 48249 (...) but it has not exited yet'
Adversarial (review decision): after X evicts A, a rival B that X never signalled holds the lock with a stale beacon; X must not claim it sent TERM to B ✅ pass live live-lab-rival-after-evict-transcript.txt (HEAD): 'lock held by live pid <B> ... inspect or stop'; pre-review-fix-rival.txt (12e3ddc): wrongly 'sent TERM to stalled pid <B>'
A TERM to a supervisor blocked in fm_run_timed_capture under bash 3.2 lands at once and runs its EXIT trap, while status/output pass through and the bound holds ⏸️ untested no The prior payload did not establish a live result. The only support was the unit test log test-fm-timeout-lib-capture-cases.log, where 4 cases passed under /bin/bash 3.2. No run TERMed a real supervis…
Pending-reply remote observe that hangs past FM_PENDING_REPLY_OBSERVE_TIMEOUT reads as unknown ⏸️ untested no The prior payload did not establish a live result. The only support was the unit test log test-fm-pending-reply.log, which covered the observe timeout case at 2s. No run drove the pending-reply observ…
Session-start (full mode) remote route read is bounded by FM_SECONDMATE_PROBE_TIMEOUT ⏸️ untested no Reaching the route read needs a real remote secondmate whose fm-remote-doctor readiness check passes and whose state reads alive. No such remote host or SSH login is available in this gate. The live f…
  • /bin/bash live-lab-drive.sh &lt;worktree&gt; &lt;base&gt; (evidence dir): real ssh against a silent peer. Covers fm-on.sh ConnectTimeout (HEAD vs base), the effective options from ssh -G (BatchMode/ConnectTimeout), invalid FM_SSH_CONNECT_TIMEOUT values, the liveness probe with FM_SECONDMATE_PROBE_TIMEOUT=3, a live watcher stalled in a real ssh probe evicted by a re-arm, and the sent-TERM refusal for a holder that ignores TERM
  • /bin/bash live-lab-rival-after-evict.sh on HEAD and on 12e3ddc (pre-review-fix): arm X evicts holder A, rival B takes the lock, and X's refusal message is checked
  • bash tests/fm-watcher-lock.test.sh restricted to test_live_stale_watch_lock_is_actionable, test_live_stalled_watch_lock_is_replaced_past_hard_bound, test_stalled_holder_inside_remote_probe_is_replaced and test_holder_still_finishing_after_term_gets_its_own_refusal (HEAD)
  • the same test_stalled_holder_inside_remote_probe_is_replaced against a base fba81cb checkout (reproduces the reported failure)
  • bash tests/fm-on.test.sh
  • bash tests/fm-secondmate-liveness.test.sh
  • bash tests/fm-pending-reply.test.sh
  • bash tests/fm-timeout-lib.test.sh (aborts on the known #5847 case, which also fails on base), then the four new fm_run_timed_capture cases run on their own under /bin/bash 3.2
✅ **Document** - passed

✅ No issues found.

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

🔧 Fix applied.
1 warning still open:

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

✅ No issues found.

Pre-existing failures (unrelated to this change)

On macOS with the system /bin/bash 3.2.57 these tests fail identically on base fba81cb2 and on this branch, run one at a time:

  • tests/fm-watcher-lock.test.sh test_watch_restart_rejects_reused_pid: "restart did not surface recovery after replacing a reused-pid lock".
  • tests/fm-watch-arm.test.sh test_rearm_resurfaces_durable_queue_and_remote_open_decision: "re-arm stayed live instead of surfacing durable wakes and the still-open remote decision".
  • tests/fm-timeout-lib.test.sh first case, the fm_exec_timed status pass-through under bash 3.2 (fm-timeout-lib.sh: bare $BASHPID breaks fm-spawn on stock macOS Bash 3.2 #5847). The new fm_run_timed_capture cases in that file pass when run on their own.

This change does not touch any of those code paths, and it deliberately uses fm_run_timed, not fm_exec_timed.

Timur Yalcin added 4 commits September 27, 2026 15:25
…n land inside them

The watcher's remote secondmate liveness probe and pending-reply observation
called fm-on.sh with no hard time limit, and fm-on.sh set no ConnectTimeout,
so a peer that stopped answering (after host sleep, or accepting TCP but never
sending a banner) could hold the poll well past a minute. Both calls were also
captured with $(...), and bash 3.2 defers a fatal TERM while a command
substitution is being read, so evicting a holder stuck there failed after the
5 s wait and the re-arm reported "inspect or stop".

- fm-on.sh adds ConnectTimeout (FM_SSH_CONNECT_TIMEOUT, default 15) and
  BatchMode=yes, validated like FM_SSH_ALIVE_*.
- fm-timeout-lib.sh gains fm_run_timed_capture: fm_run_timed in the background
  with stdout captured through a file and an interruptible wait.
- Liveness state/route reads are bounded by FM_SECONDMATE_PROBE_TIMEOUT
  (default 45); hitting the bound is unknown state with the route preserved,
  never relaunchable.
- Pending-reply remote observe is bounded by FM_PENDING_REPLY_OBSERVE_TIMEOUT
  (default 20); hitting the bound observes unknown.
- A holder that has its TERM but has not exited yet is refused with its own
  message instead of "inspect or stop".
@mehulbhagwani

Copy link
Copy Markdown
Contributor

The current PR head is 0648c4f

The same remote-probe and eviction behaviour is integrated locally on branch fm/fm-pi-wake-connection-finish and was proven on three routes: a local isolated home, a TCP peer that accepts but never answers, and the real Tailscale SSH route named supercomputer.

Relevant recorded commands and results from the evidence:

  • bash tests/fm-on.test.sh passed, including default, override, invalid-setting, and unreachable-peer cases.
  • bash tests/fm-secondmate-liveness.test.sh passed the focused silent-peer case: with FM_SECONDMATE_PROBE_TIMEOUT=1, the fake peer slept for five seconds, the caller returned in about one second with remote endpoint probe timed out after 1s on lab-host; route preserved, and the route was not made relaunchable.
  • bash tests/fm-timeout-lib.test.sh passed.
  • The real Tailscale read-only command returned exit code 0 and reported backend=herdr, target=fm-remote:w4F:p2, herdr_session=fm-remote, harness=claude, model=claude-opus-5-5, and effort=medium.
  • A second real-alias read-only capture qc 200 call returned immediately with code -9 after only its SSH child was killed mid-call, with no write command issued to the remote home.

The integrated branch is available at https://github.com/mehulbhagwani/firstmate/tree/fm/fm-pi-wake-connection-finish

@mehulbhagwani

Copy link
Copy Markdown
Contributor

Suggested regression test for the timeout implementation, captured from the integrated fork branch (not proposed as a competing PR):

test_remote_poll_probe_timeout_preserves_route() {
  local w out started elapsed
  w=$(make_remote_probe_world probe-timeout)
  started=$(date +%s)
  out=$(probe_remote "$w" poll FM_SECONDMATE_PROBE_TIMEOUT=1 FM_FAKE_SLEEP=5)
  elapsed=$(( $(date +%s) - started ))
  [ "$out" = 'skipped|unknown|0|||remote endpoint probe timed out after 1s on lab-host; route preserved' ] \
    || fail "a bounded remote probe must preserve the route after timeout, got: $out"
  [ "$elapsed" -lt 4 ] || fail "a timed-out remote probe exceeded its bound: ${elapsed}s"
  pass "poll probe: a silent remote peer is bounded and never relaunchable"
}

On the integrated fork branch, bash tests/fm-secondmate-liveness.test.sh passed this case with the result ok - poll probe: a silent remote peer is bounded and never relaunchable.

Source branch: https://github.com/mehulbhagwani/firstmate/tree/fm/fm-pi-wake-connection-finish

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.

2 participants