Skip to content

test: stop the remote secondmate e2e watcher before temp-root cleanup - #5845

Merged
kunchenguid merged 3 commits into
kunchenguid:mainfrom
aminry:fm/fm-remote-secondmate-e2e-cleanup-race-q3
Sep 26, 2026
Merged

kunchenguid merged 3 commits into
kunchenguid:mainfrom
aminry:fm/fm-remote-secondmate-e2e-cleanup-race-q3

Conversation

@aminry

@aminry aminry commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fix the flaky cleanup in tests/fm-remote-secondmate-lifecycle-e2e.test.sh, filed upstream as #5836.

The test passes every assertion, then exits 1 because its EXIT-trap cleanup rm -rf -- "$TMP_ROOT" fails with 'Directory not empty': a fixture-owned background process is still writing into the temp root while it is removed. It failed this way in 4 of 217 main CI runs since 2026-09-10 (runs 36211248815, 36196302018, 36105826991, 35139828921) and on PR 4380 (run 36189713738). The issue proposes quiescing the fixture's background writers (stop and wait them) before removing the temp root, keeping the change inside this test's fixture with no behavior change outside tests.

What Changed

  • tests/fm-remote-secondmate-lifecycle-e2e.test.sh now starts both fm-watch.sh legs through remote_env exec. That makes $! the watcher process itself rather than a wrapping subshell, so kill reaches the process that writes into the fixture root.
  • The EXIT-trap cleanup kills and waits for any watcher still recorded in watch_pid before it runs rm -rf on $TMP_ROOT. This covers a watcher leg that a failed assertion cut short. Each leg clears watch_pid once its watcher has been reaped.
  • After the unreachable-remote watcher is stopped, the test waits a moment for any in-flight probe to finish. It then asserts that the SSH probe count stays the same and that nothing in the watcher's state dir changes over the next few seconds. A watcher that survives the stop now fails with a clear message instead of racing the temp-root removal (issue fm-remote-secondmate-lifecycle-e2e cleanup races a late fixture write after all assertions pass #5836).

Risk Assessment

✅ Low: The change only touches one test fixture. It makes $! point at the watcher itself by exec-ing it through remote_env, which still passes the prefix env vars through exec. It clears the reaped watcher PIDs, lets an in-flight probe settle before taking the baseline, and stops a watcher that a failed assertion left running before the original rm -rf. The unreachable leg starts no detached home-summary or reconcile children, because home-summary.json is pre-touched and no requests are queued, so the new stopped-watcher checks have no other writer to race against.

Testing

I ran the real e2e test four times under isolated TMPDIRs, each followed by a check for leaked processes and leftover temp roots. The fixed test passed twice with exit 0, no leftover temp root, and zero leaked processes. The injected-failure variant exited 1 as intended with zero leaked processes, which shows the EXIT trap stopped the live watcher. Its temp root was not removed because the read-only spawn hooks dir blocked rm, which is the out-of-scope case the user chose to leave alone. The base copy happened to pass once, which fits the ~2% flake rate. The no-exec variant exited 1, but my log keeps only the last 8 lines, so the failing assertion was not captured and that scenario is untested. No Herdr lab or harness primary was needed because this change is test-only. All temporary test copies and temp dirs were removed.

  • Live validation: ✅ go - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Running the fixed remote secondmate lifecycle e2e passes every assertion and exits 0 with its temp root removed ✅ pass live fixed-run-1.log and fixed-run-2.log: ALL TESTS PASSED, exit=0, no fixture temp root under TMPDIR
After the fixed test exits, no fixture-owned watcher keeps running or recreates the temp root ✅ pass live fixed-run-2.log: leaked_process_count=0 and no temp root 5s after exit
Adversarial: an assertion fails while the unreachable watcher is live, and the EXIT trap stops that watcher ✅ pass live injected-failure-cleanup.log: exit=1 as injected, leaked_process_count=0 5s after exit. The temp root stayed only because of the read-only spawn hooks dir, which the user excluded from scope.
Adversarial: with exec reverted, the new stopped-watcher guard fails the run ⏸️ untested no The prior payload did not establish a live result: the driver kept only the last 8 lines of output, so the exit=1 cannot be attributed to the new guard. To confirm, re-run the exec-reverted copy (~6 m…
Reproduce the original 'Directory not empty' flake on the base commit ⏸️ untested no The prior payload did not establish a live reproduction: the single base run passed. The race hits about 2% of CI runs (4 of 217), so reproducing it would take many repeated base runs.
Evidence: Fixed test run 1 transcript

Source: Fixed test run 1 transcript

ok - overlapping remote home provisioning serializes through publication and rollback
ok - competing cleanup of the public home cannot reach a live provisioning clone
ok - a home that appears mid-provision makes the provision die without touching it
ok - remote seed rollback preserves serialized competing routes
ok - unknown readiness preserves its route and brief for reconciliation
ok - remote seeding checks, repairs, and re-checks readiness, then stops on a remaining gap
ok - remote seeding proceeds once the repair closes every gap
ok - remote seeding provisions a supplied origin without touching the primary project tree
ok - remote provisioning re-validates a supplied origin at the receiving host
ok - seeding carries bitbucket, self-hosted, and scp-like origins through to the remote clone
ok - remote seed registers the route and provisions the whole home and project clone on that host
ok - remote inheritance rejects incomplete and superseded payload generations
ok - mixed local and remote routes validate without migration
ok - remote spawn launches on the remote-local backend and records a host-qualified route
ok - legacy and mismatched remote endpoints fail closed before backend access
ok - non-herdr remote endpoints are refused without changing either route
ok - remote spawn serializes inheritance through launch publication
cannot retire terminal source; it remains registered: remote-reply-ios
ok - marked send and routed reply complete through the existing parent correlation owner
cannot retire terminal source; it remains registered: remote-reply-ios
ok - partial remote inheritance retains reread intent through bootstrap convergence
ok - config push and bootstrap serialize remote inheritance convergence
cannot retire terminal source; it remains registered: remote-reply-ios
ok - remote inherited config retains and retries a failed live reread nudge
cannot retire terminal source; it remains registered: remote-reply-ios
cannot retire terminal source; it remains registered: remote-reply-ios
cannot retire terminal source; it remains registered: remote-reply-ios
ok - fleet snapshot projects mixed local and remote structured state
ok - remote update imports and fast-forwards the persistent home on its configured host
ok - the remote restart verb delegates to the host-local control plane and refuses before stopping anything
ok - startup repairs remote readiness before probing without relaunching
ok - watch liveness: a dead remote secondmate is auto-relaunched on its own host with one wake
ok - watch liveness: an unreachable remote secondmate is probed, preserved, and never failed over
ok - the host-local state read steps around a stale shadowing herdr client
ok - startup reports alive legacy backends without changing their routes
ok - unreachable no-ledger remote state remains explicit with no local respawn or failover
cannot retire terminal source; it remains registered: remote-reply-ios
ok - remote retirement refuses child work, then removes only its own endpoint while a shared-session sibling survives
ALL TESTS PASSED
exit=0
Evidence: Fixed test run 2 with post-exit leak check

Source: Fixed test run 2 with post-exit leak check

== variant fixed: tests/fm-remote-secondmate-lifecycle-e2e.test.sh (TMPDIR=/tmp/nm-td-fixed.IfeR)
ok - watch liveness: a dead remote secondmate is auto-relaunched on its own host with one wake
ok - watch liveness: an unreachable remote secondmate is probed, preserved, and never failed over
ok - the host-local state read steps around a stale shadowing herdr client
ok - startup reports alive legacy backends without changing their routes
ok - unreachable no-ledger remote state remains explicit with no local respawn or failover
cannot retire terminal source; it remains registered: remote-reply-ios
ok - remote retirement refuses child work, then removes only its own endpoint while a shared-session sibling survives
ALL TESTS PASSED
exit=0
-- fixture temp roots left under TMPDIR immediately after exit:
(none)
-- processes still carrying this run's fixture root 5s after exit:
leaked_process_count=0
-- fixture temp roots under TMPDIR 5s after exit (recreated by a leaked writer?):
(none)
Evidence: Injected mid-watcher failure: cleanup stops watcher (0 leaked processes)

Source: Injected mid-watcher failure: cleanup stops watcher (0 leaked processes)

== variant inject: tests/zz-nm-inject.sh (TMPDIR=/tmp/nm-td-inject.znpu)
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state/parent-route/ios.git-hooks/pre-push: Permission denied
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state/parent-route/ios.git-hooks/post-merge: Permission denied
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state/parent-route/ios.git-hooks/pre-commit: Permission denied
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state/parent-route/ios.git-hooks: Directory not empty
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state/parent-route: Directory not empty
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home/state: Directory not empty
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c/remote-home: Directory not empty
rm: /private/tmp/nm-td-inject.znpu/fm-remote-secondmate-e2e.Rw5S6c: Directory not empty
exit=1
-- fixture temp roots left under TMPDIR immediately after exit:
fm-remote-secondmate-e2e.Rw5S6c
-- processes still carrying this run's fixture root 5s after exit:
leaked_process_count=0
-- fixture temp roots under TMPDIR 5s after exit (recreated by a leaked writer?):
fm-remote-secondmate-e2e.Rw5S6c
Evidence: Base (pre-fix) run with leak check

Source: Base (pre-fix) run with leak check

== variant base: tests/zz-nm-base.sh (TMPDIR=/tmp/nm-td-base.I8Xn)
ok - watch liveness: a dead remote secondmate is auto-relaunched on its own host with one wake
ok - watch liveness: an unreachable remote secondmate is probed, preserved, and never failed over
ok - the host-local state read steps around a stale shadowing herdr client
ok - startup reports alive legacy backends without changing their routes
ok - unreachable no-ledger remote state remains explicit with no local respawn or failover
cannot retire terminal source; it remains registered: remote-reply-ios
ok - remote retirement refuses child work, then removes only its own endpoint while a shared-session sibling survives
ALL TESTS PASSED
exit=0
-- fixture temp roots left under TMPDIR immediately after exit:
(none)
-- processes still carrying this run's fixture root 5s after exit:
leaked_process_count=0
-- fixture temp roots under TMPDIR 5s after exit (recreated by a leaked writer?):
(none)
Evidence: Fixed test with exec reverted (failing assertion truncated)

Source: Fixed test with exec reverted (failing assertion truncated)

== variant noexec: tests/zz-nm-noexec.sh (TMPDIR=/tmp/nm-td-noexec.Ypo4)
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state/parent-route/ios.git-hooks/pre-push: Permission denied
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state/parent-route/ios.git-hooks/post-merge: Permission denied
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state/parent-route/ios.git-hooks/pre-commit: Permission denied
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state/parent-route/ios.git-hooks: Directory not empty
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state/parent-route: Directory not empty
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home/state: Directory not empty
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a/remote-home: Directory not empty
rm: /private/tmp/nm-td-noexec.Ypo4/fm-remote-secondmate-e2e.wc665a: Directory not empty
exit=1
-- fixture temp roots left under TMPDIR immediately after exit:
fm-remote-secondmate-e2e.wc665a
-- processes still carrying this run's fixture root 5s after exit:
leaked_process_count=0
-- fixture temp roots under TMPDIR 5s after exit (recreated by a leaked writer?):
fm-remote-secondmate-e2e.wc665a

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (2) ✅
  • ⚠️ tests/fm-remote-secondmate-lifecycle-e2e.test.sh:38 - The new cleanup block kills $watch_pid whenever it is set, but neither watcher leg clears it after its own wait (lines ~1265 and ~1311). On a normal passing run, watch_pid still holds the unreachable watcher's PID, which was already reaped. When the EXIT trap runs, it sends SIGTERM to that stale PID. If the PID has been recycled in the meantime (the suite spawns many processes, and macOS wraps at 99999), the signal hits an unrelated process owned by the same user. Fix: run watch_pid='' right after each leg's successful wait. The cleanup block then only fires for a watcher that a failed assertion left running.
  • ⚠️ tests/fm-remote-secondmate-lifecycle-e2e.test.sh:52 - The cleanup now calls fm_test_remove_tree (chmod every directory, then rm -rf) instead of rm -rf -- "$TMP_ROOT". The stated reason is a read-only spawn hooks dir left by runs that fail before retirement. That is a separate failure mode from the issue's 'Directory not empty' race, which comes from a background writer. The race is fixed by exec-ing the watcher and stopping/waiting it. No requirement in the intent needs this swap. Recommend removing it from this change, or confirm that it is intentionally in scope.

🔧 Fix applied.
1 warning still open:

  • ⚠️ tests/fm-remote-secondmate-lifecycle-e2e.test.sh:1318 - The new check that the stopped watcher does no more probing captures its baseline (ssh_after) right after wait returns. That baseline can be off by one. fm-watch.sh runs secondmate_liveness_tick -> fm_secondmate_liveness_probe in its main shell, and TERM keeps bash's default disposition (watcher_stop_signals). So a SIGTERM that arrives after the watcher forks fake-ssh, but before fake-ssh runs its first two lines (count=$(cat ...), printf ... > $FM_FAKE_SSH_COUNT), kills the watcher and leaves that child running. The child then bumps ssh.count after ssh_after is read, and the check [ "$(cat "$SSH_COUNT")" = "$ssh_after" ] fails with 'the stopped unreachable watcher kept probing' on an otherwise correct run. The watcher probes once per 1s cycle with FM_POLL=1, and each probe opens a window of a few milliseconds (bash startup plus a cat fork), so this adds a new low-rate flake of the same kind the change is meant to remove. Fix: let the leftover child settle before taking the baseline. For example, after watch_pid='', sleep 1, then read the baseline count and touch the .stopped marker, then sleep 3 and compare. A real surviving watcher still keeps probing and fails the check.

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

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Running the fixed remote secondmate lifecycle e2e passes every assertion and exits 0 with its temp root removed ✅ pass live fixed-run-1.log and fixed-run-2.log: ALL TESTS PASSED, exit=0, no fixture temp root under TMPDIR
After the fixed test exits, no fixture-owned watcher keeps running or recreates the temp root ✅ pass live fixed-run-2.log: leaked_process_count=0 and no temp root 5s after exit
Adversarial: an assertion fails while the unreachable watcher is live, and the EXIT trap stops that watcher ✅ pass live injected-failure-cleanup.log: exit=1 as injected, leaked_process_count=0 5s after exit. The temp root stayed only because of the read-only spawn hooks dir, which the user excluded from scope.
Adversarial: with exec reverted, the new stopped-watcher guard fails the run ⏸️ untested no The prior payload did not establish a live result: the driver kept only the last 8 lines of output, so the exit=1 cannot be attributed to the new guard. To confirm, re-run the exec-reverted copy (~6 m…
Reproduce the original 'Directory not empty' flake on the base commit ⏸️ untested no The prior payload did not establish a live reproduction: the single base run passed. The race hits about 2% of CI runs (4 of 217), so reproducing it would take many repeated base runs.
  • bash tests/fm-remote-secondmate-lifecycle-e2e.test.sh (fixed, run 1, ~6 min): ALL TESTS PASSED, exit 0, no fm-remote-secondmate-e2e temp root left
  • TMPDIR=<isolated> bash tests/fm-remote-secondmate-lifecycle-e2e.test.sh (fixed, run 2, parallel under load), then 5s later ps -E for processes carrying the fixture root and ls of TMPDIR
  • Base-commit copy of the test (git show 503ba82:tests/fm-remote-secondmate-lifecycle-e2e.test.sh) run under an isolated TMPDIR with the same leak checks
  • Temporary copy of the fixed test with fail injected 3s after the unreachable watcher starts, run under an isolated TMPDIR with the same leak checks
  • Temporary copy of the fixed test with only exec reverted, to check that the new stopped-watcher guard catches a surviving watcher
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Closes #5836

The remote secondmate lifecycle e2e backgrounded fm-watch.sh through the
remote_env shell function, so $! named the function's subshell rather than
the watcher. Killing that subshell left the unreachable-leg watcher running,
and its one-second liveness probe kept invoking the fake ssh, which rewrites
ssh.count in the temp root. When a probe landed while the EXIT trap was
removing the root, rm failed with "Directory not empty" after every
assertion had passed.

Exec the watcher from the backgrounded function so the recorded pid is the
watcher itself, and assert the stopped watcher stops probing and writing its
state. Cleanup also stops a watcher left running by a failed assertion and
removes the root through fm_test_remove_tree, so a run that fails before
retirement does not strand the read-only spawn hooks directory.

Closes kunchenguid#5836
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Verdict: Whole thread + tip vs main 5700baaa + linked #5836 reviewed. Author body Closes #5836 verified (yes).

Tip vs main: Only tests/fm-remote-secondmate-lifecycle-e2e.test.sh changes. Main fixture starts fm-watch.sh via remote_env without exec, so $! is a wrapping subshell and kill/wait miss the writer; EXIT rm -rf then races late fixture writes (Directory not empty after ALL TESTS PASSED — same flake on main CI). Tip execs the watcher, clears reaped watch_pid, stops leftover watchers in cleanup, and asserts the unreachable watcher stayed stopped. Test-only; no product default path change.

contract-class: restore — concrete existing e2e cleanup path was broken/flaky; tip restores reliable fixture teardown.

VISION.md (each rule)

  • One captain, one interface: aligns / orthogonal (test flake, not captain surface).
  • Authority explicit: aligns — no autonomy change.
  • Scripts own mechanics: aligns — fixture mechanics stay in the test script.
  • Restart is a non-event: aligns / orthogonal.
  • Delegation with a spine: aligns / orthogonal.
  • Fleet outlives vendor: aligns.
  • Scope: aligns — workshop test hygiene for the forge; no command-layer behavior change.

Attestation: MATCH. CI: CLEAN SUCCESS (36274250453). NM: SUCCESS. mergeable: MERGEABLE/CLEAN. Squash-merging. Firstmate flag: no. Security tip: none.

@kunchenguid
kunchenguid merged commit 62d643c into kunchenguid:main Sep 26, 2026
20 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @aminry — really appreciate you taking the time on this.

mehulbhagwani pushed a commit to mehulbhagwani/firstmate that referenced this pull request Sep 27, 2026
…kunchenguid#5845)

* test: stop the leaked unreachable watcher before remote e2e cleanup

The remote secondmate lifecycle e2e backgrounded fm-watch.sh through the
remote_env shell function, so $! named the function's subshell rather than
the watcher. Killing that subshell left the unreachable-leg watcher running,
and its one-second liveness probe kept invoking the fake ssh, which rewrites
ssh.count in the temp root. When a probe landed while the EXIT trap was
removing the root, rm failed with "Directory not empty" after every
assertion had passed.

Exec the watcher from the backgrounded function so the recorded pid is the
watcher itself, and assert the stopped watcher stops probing and writing its
state. Cleanup also stops a watcher left running by a failed assertion and
removes the root through fm_test_remove_tree, so a run that fails before
retirement does not strand the read-only spawn hooks directory.

Closes kunchenguid#5836

* no-mistakes(review): Clear reaped watcher PIDs and restore plain temp-root removal

* no-mistakes(review): Let in-flight probe settle before stopped-watcher baseline
mehulbhagwani pushed a commit to mehulbhagwani/firstmate that referenced this pull request Sep 27, 2026
…kunchenguid#5845)

* test: stop the leaked unreachable watcher before remote e2e cleanup

The remote secondmate lifecycle e2e backgrounded fm-watch.sh through the
remote_env shell function, so $! named the function's subshell rather than
the watcher. Killing that subshell left the unreachable-leg watcher running,
and its one-second liveness probe kept invoking the fake ssh, which rewrites
ssh.count in the temp root. When a probe landed while the EXIT trap was
removing the root, rm failed with "Directory not empty" after every
assertion had passed.

Exec the watcher from the backgrounded function so the recorded pid is the
watcher itself, and assert the stopped watcher stops probing and writing its
state. Cleanup also stops a watcher left running by a failed assertion and
removes the root through fm_test_remove_tree, so a run that fails before
retirement does not strand the read-only spawn hooks directory.

Closes kunchenguid#5836

* no-mistakes(review): Clear reaped watcher PIDs and restore plain temp-root removal

* no-mistakes(review): Let in-flight probe settle before stopped-watcher baseline
mehulbhagwani pushed a commit to mehulbhagwani/firstmate that referenced this pull request Sep 27, 2026
…kunchenguid#5845)

* test: stop the leaked unreachable watcher before remote e2e cleanup

The remote secondmate lifecycle e2e backgrounded fm-watch.sh through the
remote_env shell function, so $! named the function's subshell rather than
the watcher. Killing that subshell left the unreachable-leg watcher running,
and its one-second liveness probe kept invoking the fake ssh, which rewrites
ssh.count in the temp root. When a probe landed while the EXIT trap was
removing the root, rm failed with "Directory not empty" after every
assertion had passed.

Exec the watcher from the backgrounded function so the recorded pid is the
watcher itself, and assert the stopped watcher stops probing and writing its
state. Cleanup also stops a watcher left running by a failed assertion and
removes the root through fm_test_remove_tree, so a run that fails before
retirement does not strand the read-only spawn hooks directory.

Closes kunchenguid#5836

* no-mistakes(review): Clear reaped watcher PIDs and restore plain temp-root removal

* no-mistakes(review): Let in-flight probe settle before stopped-watcher baseline
knowttl pushed a commit to knowttl/firstmate that referenced this pull request Sep 29, 2026
…kunchenguid#5845)

* test: stop the leaked unreachable watcher before remote e2e cleanup

The remote secondmate lifecycle e2e backgrounded fm-watch.sh through the
remote_env shell function, so $! named the function's subshell rather than
the watcher. Killing that subshell left the unreachable-leg watcher running,
and its one-second liveness probe kept invoking the fake ssh, which rewrites
ssh.count in the temp root. When a probe landed while the EXIT trap was
removing the root, rm failed with "Directory not empty" after every
assertion had passed.

Exec the watcher from the backgrounded function so the recorded pid is the
watcher itself, and assert the stopped watcher stops probing and writing its
state. Cleanup also stops a watcher left running by a failed assertion and
removes the root through fm_test_remove_tree, so a run that fails before
retirement does not strand the read-only spawn hooks directory.

Closes kunchenguid#5836

* no-mistakes(review): Clear reaped watcher PIDs and restore plain temp-root removal

* no-mistakes(review): Let in-flight probe settle before stopped-watcher baseline
jredgard added a commit to jredgard/firstmate that referenced this pull request Sep 29, 2026