Skip to content

fix(bin): bound teardown's leftover-process scan and fall back to /proc when lsof stalls - #29

Merged
alandomio merged 3 commits into
mainfrom
fm/teardown-lsof-timeout
Sep 12, 2026
Merged

alandomio merged 3 commits into
mainfrom
fm/teardown-lsof-timeout

Conversation

@alandomio

@alandomio alandomio commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner

Intent

Cleanup of a finished task could hang forever, silently, in bin/fm-teardown.sh, and every later attempt to clean up that task was then refused. Its check for leftover processes ran a system-wide lsof -a -d cwd scan that, on this host and especially under memory pressure, did not finish: one run passed 800 seconds before it was killed. Nothing was printed while it was stuck, and --force hung in the same place.

This change bounds that scan and keeps the leftover-process check trustworthy when lsof misbehaves:

  • The scan runs lsof -b under a time cap, FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS (default 30 seconds).
  • On Linux, when lsof fails or hits the cap, the rest of the run reads each process's working directory from /proc instead, under the same cap, so cleanup can still find and stop leftover processes rather than being blocked.
  • Cleanup refuses, --force included, whenever no scan gives a complete answer: there is no /proc (as on macOS), or the /proc read is capped, fails, or cannot read any process. Declaring a worktree free while a process still runs in it is the failure this check exists to prevent, so an incomplete scan never counts as "no leftover processes".
  • A switch to /proc, a skipped check, and a refusal are each announced on stdout with the consequence, so a slow scan can be told apart from a hang.

A killed cleanup was reported to leave its lifecycle lock held so that retries were refused. The existing lock code already reclaims a lock whose holder process is dead and refuses while the holder is alive, so the lock code is unchanged and a regression test now pins that behavior. What caused the earlier refusals is not established.

What Changed

  • bin/fm-teardown.sh now runs the leftover-process cwd scan as lsof -b -a -d cwd -Fpn through fm_run_timed. The cap comes from the new FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS (whole seconds, default 30; zero or an invalid value falls back to 30). Scan output goes to a temp file instead of a pipe. If lsof fails or hits the cap, that scan and every later rescan in the same run read each process's /proc/<pid>/cwd link directly, under the same cap. Link targets are kept byte-exact and embedded newlines become ?. Teardown refuses, --force included, and keeps the worktree and task records only when /proc is unavailable (as on macOS), or when the /proc read also hits the cap or fails.

  • Teardown now reports on stdout when it starts the check, when it switches from lsof to /proc (once per run, with the lsof reason) and when the check is skipped because lsof is not installed. It also reports any refusal: which check could not run, why, and what that means, plus a FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS hint when a cap was hit. The REFUSED: line still goes to stderr. Lifecycle-lock code is unchanged.

  • tests/fm-teardown.test.sh adds these cases:

    • a stalled lsof stub that is capped and refused visibly, with and without --force
    • a Linux-only real-/proc fallback where lsof fails or is capped and a live process in the worktree is still reaped
    • fake-/proc refusals where readlink stalls or fails
    • a regression test showing a SIGKILLed teardown's lifecycle lock turns away a rival while its holder is alive and is reclaimed after the holder dies

    Existing refusal tests set FM_PROC_ROOT_OVERRIDE to a missing directory. The lsof-error-index-lock case now answers the cwd scan, so it actually reaches the index.lock refusal. docs/configuration.md documents the new variable and notes that FM_PROC_ROOT_OVERRIDE also controls the fallback scan.

Risk Assessment

✅ Low: Both round-1 findings are correctly resolved. The /proc fallback now refuses when it could read no cwd link at all, and a new test fails against the old code. The cap wording is fixed in the header, the config comment and docs/configuration.md. Every other path either completes the check or refuses before any destructive step, --force included, and all the required behaviors in the intent are present.

Testing

I ran 16 teardown cases on HEAD: the five new ones, the repaired index-lock case t, and the neighbouring leftover-process cases. All passed in about 51s, with real teardown CLI transcripts captured. I also ran the new tests against older versions of bin/fm-teardown.sh. On the base commit the stalled-scan and fallback cases hang until the 40s guard kills them. On the refuse-only commit eb7bbfc both /proc-fallback cases fail. On 2616bcb, before the fail-closed fix, the unreadable-/proc case lets teardown finish instead of refusing. So each test catches the defect it was written for. Repaired case t also passes on the base script, which is expected: that change was to the test stub, not to product code. No stalled stubs were left behind, the worktree is clean, and there are no failures to report. This is a CLI change, so the evidence is terminal transcripts rather than screenshots.

Evidence: Teardown CLI stdout/stderr excerpts (capped lsof with no /proc: refusal with --force; /proc fallback announced once, then reap and completion; capped or unreadable /proc refusal)

Source: Teardown CLI stdout/stderr excerpts (capped lsof with no /proc: refusal with --force; /proc fallback announced once, then reap and completion; capped or unreadable /proc refusal)

\### stalled-cwd-scan-plain__stdout.txt
teardown: the leftover-process check under /tmp/fm-teardown-tests.EXMyip/stalled-cwd-scan-plain/wt could not run: lsof did not finish within 1s and /proc is not available to check directly. Cleanup refused, --force included, because a process may still be running in that copy; the worktree and task records are kept for a retry. FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS raises the cap.
\### stalled-cwd-scan-plain__stderr.txt
REFUSED: cannot determine leaked processes under /tmp/fm-teardown-tests.EXMyip/stalled-cwd-scan-plain/wt for task-x1 (lsof did not finish within 1s and /proc is not available to check directly); preserving the worktree/tasktmp for manual inspection or retry.

\### stalled-cwd-scan-force__stdout.txt
teardown: the leftover-process check under /tmp/fm-teardown-tests.EXMyip/stalled-cwd-scan-force/wt could not run: lsof did not finish within 1s and /proc is not available to check directly. Cleanup refused, --force included, because a process may still be running in that copy; the worktree and task records are kept for a retry. FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS raises the cap.
\### stalled-cwd-scan-force__stderr.txt
REFUSED: cannot determine leaked processes under /tmp/fm-teardown-tests.EXMyip/stalled-cwd-scan-force/wt for task-x1 (lsof did not finish within 1s and /proc is not available to check directly); preserving the worktree/tasktmp for manual inspection or retry.

\### lsof-capped-proc-fallback__stdout.txt
teardown: lsof did not finish within 1s, so the leftover-process check reads /proc directly instead.
teardown task-x1 complete (window firstmate:fm-task-x1, worktree /tmp/fm-teardown-tests.EXMyip/lsof-capped-proc-fallback/wt)
\### lsof-capped-proc-fallback__stderr.txt
teardown: reaping leaked worktree process(es) for task-x1: 3176293

\### lsof-failed-proc-fallback__stdout.txt
teardown: lsof failed, so the leftover-process check reads /proc directly instead.
teardown task-x1 complete (window firstmate:fm-task-x1, worktree /tmp/fm-teardown-tests.EXMyip/lsof-failed-proc-fallback/wt)
\### lsof-failed-proc-fallback__stderr.txt
teardown: reaping leaked worktree process(es) for task-x1: 3186671

\### capped-proc-fallback-force__stdout.txt
teardown: lsof did not finish within 1s, so the leftover-process check reads /tmp/fm-teardown-tests.EXMyip/capped-proc-fallback-force/fake-proc directly instead.
teardown: the leftover-process check under /tmp/fm-teardown-tests.EXMyip/capped-proc-fallback-force/wt could not run: lsof did not finish within 1s and reading /proc directly did not finish within 1s. Cleanup refused, --force included, because a process may still be running in that copy; the worktree and task records are kept for a retry. FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS raises the cap.
\### capped-proc-fallback-force__stderr.txt
REFUSED: cannot determine leaked processes under /tmp/fm-teardown-tests.EXMyip/capped-proc-fallback-force/wt for task-x1 (lsof did not finish within 1s and reading /proc directly did not finish within 1s); preserving the worktree/tasktmp for manual inspection or retry.

\### unreadable-proc-fallback-force__stdout.txt
teardown: lsof failed, so the leftover-process check reads /tmp/fm-teardown-tests.EXMyip/unreadable-proc-fallback-force/fake-proc directly instead.
teardown: the leftover-process check under /tmp/fm-teardown-tests.EXMyip/unreadable-proc-fallback-force/wt could not run: lsof failed and reading /proc directly failed. Cleanup refused, --force included, because a process may still be running in that copy; the worktree and task records are kept for a retry.
\### unreadable-proc-fallback-force__stderr.txt
REFUSED: cannot determine leaked processes under /tmp/fm-teardown-tests.EXMyip/unreadable-proc-fallback-force/wt for task-x1 (lsof failed and reading /proc directly failed); preserving the worktree/tasktmp for manual inspection or retry.

\### lsof-error-refusal__stdout.txt
teardown: the leftover-process check under /tmp/fm-teardown-tests.EXMyip/lsof-error-refusal/wt could not run: lsof failed and /proc is not available to check directly. Cleanup refused, --force included, because a process may still be running in that copy; the worktree and task records are kept for a retry.
\### lsof-error-refusal__stderr.txt
REFUSED: cannot determine leaked processes under /tmp/fm-teardown-tests.EXMyip/lsof-error-refusal/wt for task-x1 (lsof failed and /proc is not available to check directly); preserving the worktree/tasktmp for manual inspection or retry.
  • Evidence: Full per-case teardown stdout/stderr transcripts from the HEAD run (includes killed-teardown lock live refusal and reclaim, and retry-after-cap completion) (local file: ~/.no-mistakes/evidence/01M2874NA3VCR1N9M8J9EQ8C0C/transcripts-head)
Evidence: HEAD targeted test run (16 cases)

Source: HEAD targeted test run (16 cases)

ok - a stalled cwd scan is capped, refuses visibly on stdout, and releases the lifecycle lock (with and without --force)
ok - a failed or capped lsof scan falls back to /proc once, still reaps the leftover process, and completes
ok - a /proc read that stalls after a capped lsof refuses visibly within its caps (with and without --force)
ok - a /proc read that could not read any cwd link refuses visibly instead of reporting no processes (with and without --force)
ok - a killed teardown's lifecycle lock refuses a rival while the holder lives and is reclaimed once it dies
ok - lsof errors leave worktree index.lock in place and refuse teardown
ok - an erroring lsof scan with no /proc to fall back on refuses teardown and preserves the task
ok - missing lsof falls back to reaping the tmux pane process group
ok - a leaked descendant process rooted under the task's worktree is reaped by teardown, not left surviving
ok - a leaked descendant process rooted under the task's per-task tasktmp is reaped by teardown too
ok - a reused pid with a different start time is never force-killed
ok - an exec change preserves birth identity and the process is reaped
ok - a process spawned during grace is reaped on a later pass
ok - persistent leaked processes refuse teardown after bounded retries
ok - a process exiting during identity lookup does not block teardown
ok - the run abort and the leaked-process reap both complete before the destructive worktree return
runner finished in 51s; "ok" lines: 16, "not ok" lines: 0
Evidence: Red check against base 4a6429b: stalled-scan and fallback tests hang until the 40s guard

Source: Red check against base 4a6429b: stalled-scan and fallback tests hang until the 40s guard

not ok - stalled-cwd-scan-plain: teardown hung on a stalled cwd scan until the 40s test guard killed it not ok - lsof-capped-proc-fallback: teardown hung until the 40s test guard killed it

=== test_stalled_cwd_scan_is_bounded_and_refuses_visibly (bin/fm-teardown.sh @ 4a6429b, base) ===
not ok - stalled-cwd-scan-plain: teardown hung on a stalled cwd scan until the 40s test guard killed it
exit=1 elapsed=41s
=== test_failed_or_capped_lsof_scan_falls_back_to_proc (bin/fm-teardown.sh @ 4a6429b, base) ===
not ok - lsof-capped-proc-fallback: teardown hung until the 40s test guard killed it
exit=1 elapsed=40s
=== test_lsof_error_never_clears_index_lock (bin/fm-teardown.sh @ 4a6429b, base) ===
ok - lsof errors leave worktree index.lock in place and refuse teardown
exit=0 elapsed=1s
Evidence: Red check against refuse-only eb7bbfc: /proc fallback tests fail

Source: Red check against refuse-only eb7bbfc: /proc fallback tests fail

not ok - lsof-capped-proc-fallback: teardown should complete through the /proc fallback: expected exit 0, got 1 not ok - capped-proc-fallback-plain: stdout did not announce the switch to /proc

=== test_failed_or_capped_lsof_scan_falls_back_to_proc (bin/fm-teardown.sh @ eb7bbfc, refuse-only) ===
not ok - lsof-capped-proc-fallback: teardown should complete through the /proc fallback: expected exit 0, got 1
exit=1 elapsed=1s
=== test_capped_proc_fallback_refuses_visibly (bin/fm-teardown.sh @ eb7bbfc, refuse-only) ===
not ok - capped-proc-fallback-plain: stdout did not announce the switch to /proc
exit=1 elapsed=2s
Evidence: Red check against 2616bcb (before fail-closed): unreadable /proc was treated as no leftover processes

Source: Red check against 2616bcb (before fail-closed): unreadable /proc was treated as no leftover processes

not ok - unreadable-proc-fallback-plain: teardown should refuse when no /proc cwd link could be read: expected exit 1, got 0

=== test_unreadable_proc_fallback_refuses_visibly (bin/fm-teardown.sh @ 2616bcb, before fail-closed fix) ===
not ok - unreadable-proc-fallback-plain: teardown should refuse when no /proc cwd link could be read: expected exit 1, got 0
exit=1 elapsed=1s
Evidence: Filtered runner generator used for every run

Source: Filtered runner generator used for every run

#!/usr/bin/env bash
# Build a runner that executes only selected cases of tests/fm-teardown.test.sh
# from <tree-root>, and copies every case's stdout/stderr into <transcript-dir>
# before the fixture tmp root is cleaned up.
# Usage: make-runner.sh <tree-root> <runner-out> <transcript-dir> <test_fn>...
set -eu
tree=$1 out=$2 tdir=$3
shift 3
src="$tree/tests/fm-teardown.test.sh"
last=$(grep -n '^test_local_only_fork_remote_allows$' "$src" | cut -d: -f1)
{
  sed -n "1,$((last - 1))p" "$src" |
    sed "s#^\. \"\$(dirname \"\${BASH_SOURCE\[0\]}\")/lib.sh\"#. '$tree/tests/lib.sh'#"
  cat <<EOF
save_transcripts() {
  local d
  mkdir -p '$tdir'
  for d in "\$TMP_ROOT"/*/; do
    for f in "\$d"*stdout "\$d"*stderr; do
      [ -f "\$f" ] && cp "\$f" '$tdir'/"\$(basename "\$d")__\$(basename "\$f").txt"
    done
  done
  return 0
}
trap 'save_transcripts; fm_test_cleanup' EXIT
EOF
  printf '%s\n' "$@"
} > "$out"
chmod +x "$out"

Open threads

  • The scan cap bounds a scan that can be killed. An lsof stuck in uninterruptible kernel sleep can still hold cleanup past FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS, because the timeout runner waits for the killed scan to exit. No such stall has been observed: the stalls measured on this host were all ended by SIGKILL.
  • During earlier hangs, several long-lived treehouse get processes were alive while cleanup called treehouse return. Contention between them on the worktree pool was not measured and is not claimed as a cause.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed ✅
  • ⚠️ bin/fm-teardown.sh:1326 - If readlink fails for every process, the /proc fallback reports success with an empty result, and teardown carries on as if there are no leftover processes. In PROC_CWD_READER, each failed readlink is skipped with || continue, and the loop still exits 0. Examples: readlink is not on PATH (exit 127), or every read gets EACCES/ENOENT. process_cwd_scan then sets PROCESS_SCAN_PROC_STATE=used and returns 0 with an empty scan file. pids_with_cwd_under finds nothing, and teardown goes on to return the worktree even though a process may still be running in it. That is the false negative option B was chosen to avoid ('proceed only if that read completes'). The only availability check today, [ -L &#34;$proc_root/self/cwd&#34; ], confirms the link exists but never checks that it can be read. The trigger is unlikely, but the result is silent and destructive. Fix: make the reader fail closed. Either first run readlink &#34;$1/self/cwd&#34; and exit non-zero if that fails, or count successful reads and exit 1 when none succeeded. PROCESS_SCAN_PROC_STATE would then become failed and the existing refusal message applies. Keep a fake-root test such as test_capped_proc_fallback_refuses_visibly working: its stub stalls on every path under the fake root, self included, so it would still hit the cap.
  • ℹ️ bin/fm-teardown.sh:1330 - The scan cap only holds if the scan process can actually be killed. On the GNU timeout path, timeout -k 1 sends SIGKILL and then keeps waiting until the child has really exited, and fm_run_external_timeout waits on timeout. The bash fallback (fm_run_bash_timeout) also waits on the killed child. So an lsof stuck in uninterruptible (D-state) sleep would keep teardown blocked past FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS. Only the perl fallback returns without waiting. The measured stalls (one needed SIGKILL, one was killed after 800s) suggest the reported case is killable and therefore bounded, so this is not shown to be reachable. It is noted here only because the header comment and docs describe the cap as a hard bound. A fix would mean changing the shared fm-timeout-lib runner, or adding a way for teardown to abandon an unkillable scan. That goes beyond what this change set out to do, so it needs authorization before anyone implements it.

🔧 Fix: Fail closed on unreadable /proc cwd scan; clarify cap wording
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash make-runner.sh &lt;worktree&gt; ... builds a filtered runner of tests/fm-teardown.test.sh that executes only the selected cases and saves each case's teardown stdout/stderr (runner generator kept in the evidence dir)
  • HEAD: test_stalled_cwd_scan_is_bounded_and_refuses_visibly (plain and --force)
  • HEAD: test_failed_or_capped_lsof_scan_falls_back_to_proc (capped and failed lsof, real /proc, live sleeper in the worktree)
  • HEAD: test_capped_proc_fallback_refuses_visibly (plain and --force)
  • HEAD: test_unreadable_proc_fallback_refuses_visibly (plain and --force)
  • HEAD: test_killed_teardown_lock_is_reclaimed_only_after_holder_dies
  • HEAD: test_lsof_error_never_clears_index_lock (repaired matrix case t)
  • HEAD neighbouring Fix-2 cases: test_lsof_error_refuses_before_removal, test_lsof_absent_reaps_tmux_process_group, test_leaked_worktree_process_is_reaped, test_leaked_tasktmp_process_is_reaped, test_reused_pid_identity_is_not_force_killed, test_exec_changed_process_is_still_reaped, test_process_spawned_during_grace_is_reaped_on_later_pass, test_persistent_scan_refuses_after_bounded_retries, test_process_exit_during_identity_lookup_does_not_refuse, test_run_abort_precedes_process_reap_precedes_worktree_removal
  • Red check, bin/fm-teardown.sh @ 4a6429b (base): stalled-scan and /proc-fallback tests hang until the 40s guard kills them
  • Red check, bin/fm-teardown.sh @ eb7bbfc (refuse-only): test_failed_or_capped_lsof_scan_falls_back_to_proc and test_capped_proc_fallback_refuses_visibly fail
  • Red check, bin/fm-teardown.sh @ 2616bcb (pre fail-closed): test_unreadable_proc_fallback_refuses_visibly fails because teardown exits 0 instead of refusing
  • Extracted the real teardown stdout/stderr lines (progress line, /proc switch announcement, refusal with reason, consequence and cap hint, REFUSED line, reap and completion lines) into a transcript excerpt
  • git status --short (clean) and pgrep -af &#39;sleep 300&#39; (no stalled scan stubs left behind); removed the temporary /tmp runners and exported trees
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Alan Domio added 3 commits September 11, 2026 01:51
…nnot wedge cleanup

pids_with_cwd_under ran `lsof -a -d cwd` with no bound, so a scan stalled in
the kernel left fm-teardown.sh hanging forever and silently, with --force
hanging in the same place.

The scan now passes -b and runs under fm_run_timed with a hard cap
(FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS, whole seconds, default 30). It writes
to a file rather than a pipe so a stalled lsof cannot hold teardown open past
the cap. A capped scan refuses cleanup like any other scan failure, keeping the
worktree and task records, and says so on stdout with the consequence; a scan
skipped because lsof is missing is announced the same way.

The lifecycle lock needed no change: a new regression shows a SIGKILLed
teardown's lock is refused to a rival while the holder lives and reclaimed once
it dies.

Claude-Session: https://claude.ai/code/session_01FZwAEmVZYw5UbaSJvLi5FN
…an stalls or fails

With the scan capped, a stalled or failing lsof still refused every
teardown, so cleanup stayed blocked for as long as lsof misbehaved.

When lsof fails or hits FM_TEARDOWN_PROCESS_SCAN_TIMEOUT_SECS, the rest of
the run now reads each process's cwd link under /proc instead, under the
same cap. lsof is waited for once per run, not on every rescan, and the
switch is announced once on stdout. That read never stats other open files
and sees the cwd of the same processes lsof run as the same user can, so
the leak check keeps its coverage on Linux.

Teardown still refuses, --force included, when that read cannot answer:
no /proc (macOS), a capped read, or a failed one. The refusal names both
checks on stdout and stderr. The /proc reader keeps each link target
byte-exact and replaces embedded newlines, so a directory name can neither
forge a scan record nor pass for the worktree.

Tests pin the fallback on real /proc (reaps a live process and completes,
red against the refuse-only scan), the capped-/proc refusal with and
without --force, and the no-/proc refusals. The index-lock lsof-error case
now answers the cwd scan, so it reaches the lock check it is named for
instead of passing through the scan's own refusal.

Claude-Session: https://claude.ai/code/session_01Cb3aLr5C4sLrGr6Y6QFN7i
@alandomio
alandomio merged commit 75ee228 into main Sep 12, 2026
15 checks passed
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