Repository navigation
fix(bin): throttle idle heartbeat and reap cadence in the remote job worker - #22
Merged
Merged
Conversation
added 6 commits
September 9, 2026 22:17
…worker The serve loop wrote a heartbeat (mktemp+chmod+mv) and rescanned the job queue for reaping on every 50ms tick even when idle, while the only heartbeat reader tolerates 10s of staleness and the reap throttle was already dead code (reset and tested in the same iteration). Gate both to their own SECONDS-based cadence (default 3s heartbeat, 60s reap) and leave job pickup on the unchanged fast poll tick.
…h was caused by this PR. Root cause: commit 20584a0 edited bin/fm-remote-doctor.sh (replacing the hardcoded 10s freshness literal with FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS) but did not update the pinned DOCTOR_SHA256 bootstrap identity in bin/fm-remote-entrypoint.sh:25. When git is unavailable on the remote operator PATH, the entrypoint authorizes fm-remote-doctor.sh by comparing its sha256 against that pin; the stale pin made it die with "required tool git is unavailable and the doctor does not match the trusted bootstrap identity" — exactly the tests/fm-on.test.sh assertion (`mode=check`, "the trusted doctor could not bootstrap while git was unavailable") that failed in CI. Fix (1 line): repinned DOCTOR_SHA256 from 7bb13d9f... to f0e9c423a1deeb1a6bfcbc5f595e958b9d6fb620606f3804dafdc3d837f088c6, the sha256 of bin/fm-remote-doctor.sh at HEAD. No behavior change, no new machinery. Verification (local macOS): - tests/fm-on.test.sh: the previously failing case now passes ("ok - doctor bootstrap remains authenticated when git is unavailable") and the suite reaches ALL TESTS PASSED. Two assertions in that suite fail only on this machine — the test builds its expected child PATH with a sorted shell glob over ~/.asdf/installs/*/*/bin while the implementation emits readdir order; the CI runner has no asdf installs and both passed there. Verified via a scratch copy of the suite with only those two local-ordering assertions neutralized, deleted afterwards. Untouched (unrelated to this PR). - tests/fm-remote-entrypoint.test.sh, tests/fm-remote-doctor.test.sh: exit 0. - tests/fm-remote-job.test.sh: passes, but intermittently flaky here on two pre-existing timing assertions ("the blocking job did not begin running", "queue time consumed the second job's execution timeout"). Reproduced the same flake with the base commit's lib/worker/test files checked out, so it predates this change and is not the reported failure. - bin/fm-lint.sh: clean (ShellCheck 0.11.0, actionlint 1.7.12). Changed file: bin/fm-remote-entrypoint.sh (working tree; not committed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Stop bin/fm-remote-job-worker.sh's --serve loop burning ~11% of a CPU core while idle on the remote second-mate host, without slowing down how fast a dispatched remote command is picked up. Two confirmed defects: (1) every 50ms tick unconditionally wrote a heartbeat (mktemp+chmod+mv, 3 forks) and rescanned the job queue for reaping, even though the only heartbeat reader (fm_remote_job_probe) tolerates 10s of staleness; (2) the reap throttle was dead code - a local variable reset to 0 and tested in the same iteration, so it could never suppress anything, meaning fm_remote_job_reap_stale ran on every single tick. Fix: gate both the heartbeat write and the reap sweep to their own SECONDS-based cadence (FM_REMOTE_JOB_HEARTBEAT_INTERVAL_SECONDS default 3s, FM_REMOTE_JOB_REAP_INTERVAL_SECONDS default 60s, both in fm-remote-job-lib.sh, validated in fm_remote_job_validate_settings), while worker_process_once (job pickup) stays on the unchanged fast FM_REMOTE_JOB_POLL_SECONDS tick so pickup latency is unaffected. Introduced FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS=10 as the single owner of the probe's freshness window (was a bare literal), with the heartbeat interval validated strictly less than it. Preserved the safety property that a healthy worker never reads as unready: heartbeat force-writes immediately before the rare multi-second abandoned-root grace check, gated behind the cheap fm_remote_job_root_is_live pre-check. This session's own review pass (already applied and committed: 20584a0, e114497, 2621c0f) found and fixed three follow-on issues I accept as part of this same change: (a) bin/fm-remote-doctor.sh had its own hardcoded freshness literal '10' - now shares FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS; (b) decoupling reap from every tick meant fm_remote_job_reap_stale's prepare_state call could resurrect a deleted FM_REMOTE_JOB_STATE state-root directory before the throttled heartbeat's own mktemp write would fail-fast and exit the worker for its supervisor to restart - fixed by force-refreshing the heartbeat (extracted into worker_refresh_heartbeat) immediately before every reap sweep, so a deleted state root is still caught within one tick, never silently recreated behind an unowned worker; a new regression test 'a deleted state root fails the worker fast instead of being recreated by the reap sweep' proves this; (c) the idle-cadence test was rescaled to assert the fork-to-poll-tick ratio (via a sleep shim counting real ticks) rather than an absolute fork count in a fixed wall-clock window, so it stays meaningful on a loaded/slow runner instead of being tuned to this machine's speed. Deliberately untouched: the mktemp+chmod+mv heartbeat mechanism itself (atomic-rename preserved), worker ownership/lock acquisition, quarantine handling, identity publishing, shutdown semantics, and the remote job transport/protocol - all out of scope. Measured before/after on macOS (only environment available; must not touch/restart the actual Linux host): shimmed mktemp/chmod/mv/date invocation counts over the same idle window dropped from 411 to 35 (10s window: date/reap calls 56->1, chmod 231->14, mktemp/mv 62->10 each); a clean unshimmed 20s idle CPU-time comparison via ps -o time= showed old=0.98s (4.9% of one core) vs new=0.47s (2.35%) - noted in the MR that macOS's much higher per-exec overhead (Gatekeeper/codesigning on every fork+exec) dominates and understates the improvement on the Linux target, where the call-frequency cut itself (heartbeat ~60x, reap ~1200x fewer calls/sec) is the more meaningful, environment-independent evidence and should land well under 1% idle CPU on Linux given the captain's original 10.9%-sustained baseline was itself dominated by this same per-tick forking. All existing tests (fm-remote-job.test.sh, fm-remote-job-orphan-reap.test.sh, fm-remote-doctor.test.sh, fm-on/fm-remote-entrypoint/fm-remote-backlog-handoff/fm-remote-reply suites) pass unchanged; a prior test-step 'failed' outcome on this same run was an infra timeout in the pipeline's own agent (context deadline exceeded), not a real test failure - I recovered custody, re-verified every listed suite green locally (bin/fm-lint.sh clean; each suite exits 0), and am re-running now with no further code changes. Comments kept to a 3-line max per firstmate house style; this changes firstmate's own shared tracked code under bin/, so firstmate-coding-guidelines applies.
What Changed
bin/fm-remote-job-worker.sh's--serveloop no longer writes a heartbeat and rescans the job queue on everyFM_REMOTE_JOB_POLL_SECONDStick. The heartbeat write and thefm_remote_job_reap_stalesweep each run on their ownSECONDS-based cadence (newFM_REMOTE_JOB_HEARTBEAT_INTERVAL_SECONDS, default 3s, andFM_REMOTE_JOB_REAP_INTERVAL_SECONDS, default 60s, both defined and validated inbin/fm-remote-job-lib.sh), whileworker_process_oncejob pickup stays on the unchanged fast tick. This also replaces the previous reap throttle, a local variable reset to0and tested in the same iteration, which could never suppress a sweep.FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS=10as the single owner of the probe freshness window, replacing the bare literal in bothfm_remote_job_probeandbin/fm-remote-doctor.sh'sremote_job_probe_ok; settings validation now requires the heartbeat interval to be strictly less than it.worker_refresh_heartbeatand force-refreshed the heartbeat immediately before the reap sweep and before the abandoned-root grace check (the latter now gated behind a cheapfm_remote_job_root_is_livepre-check), so a healthy worker never reads as unready and a deleted state root still fails the worker fast instead of being recreated by the sweep.tests/fm-remote-job.test.shgained coverage for the idle fork-to-poll-tick ratio (via a sleep shim counting real ticks), the deleted-state-root tripwire, and rejection of out-of-bounds heartbeat and reap intervals.Risk Assessment
✅ Low: The change is well-bounded and behavior-preserving on every path I traced: the probe freshness contract now has a single owner shared by both readers, the heartbeat/probe-window invariant is enforced at startup validation, job pickup latency is untouched, the deleted-state-root tripwire is genuinely restored ahead of the only reachable prepare_state call, and both new tests exercise the real worker's observable behavior; the only findings are informational and neither indicates a reachable defect.
Testing
Ran the three suites that cover this change (fm-remote-job, fm-remote-job-orphan-reap, fm-remote-doctor) — all green — then demonstrated the intent product-level rather than relying on pass/fail: a base-vs-fixed idle comparison showing forks over a 30s idle window dropping 683→37 and idle CPU 3.67%→0.77% of a core, with dispatch pickup latency unchanged within noise across 10 dispatches per variant. Both review-round regressions were reproduced on their pre-fix commits and shown fixed here, and the doctor/probe freshness drift was exercised as a real CLI divergence under a widened probe window. I added the one missing test — the new cadence bounds in fm_remote_job_validate_settings had no coverage — and mutation-checked it. No UI surface is involved, so evidence is CLI transcripts and measurement tables. The only note is a pre-existing load-sensitive timing test that failed only when I deliberately ran two suites in parallel; it passed on every serial run of this branch.
Evidence: Idle CPU and fork-count comparison (base vs fixed)
Source: Idle CPU and fork-count comparison (base vs fixed)
window=30s defaults: poll=0.05s heartbeat=3s reap=60s === fork counts over a 30s idle window (shimmed mktemp/chmod/mv/date) === tool base fixed reduction mktemp 98 11 9x chmod 389 14 28x mv 98 11 9x date 98 1 98x TOTAL 683 37 18x === idle CPU time over a 30s window (no shims, ps -o time=) === base : 1.10s CPU over 30s wall = 3.67% of one core fixed : 0.23s CPU over 30s wall = 0.77% of one coreEvidence: Dispatch pickup latency unchanged
Source: Dispatch pickup latency unchanged
dispatch pickup latency, 10 trivial jobs per variant (defaults: poll=0.05s) base n=10 pickup(queued->running) mean 511.9ms min 280.5 max 972.7 | end-to-end(stage->done) mean 1371.2ms new n=10 pickup(queued->running) mean 482.0ms min 270.2 max 1678.3 | end-to-end(stage->done) mean 1179.2msEvidence: Deleted state root: pre-fix resurrects an unowned tree, fixed fails fast
Source: Deleted state root: pre-fix resurrects an unowned tree, fixed fails fast
heartbeat=9s reap=1s; state root deleted right after the worker reports ready pre-fix(d5062fc) worker still serving: yes | state root recreated: yes | recreated tree owned (lock/pid): no | exit: killed fixed(2621c0f) worker still serving: no | state root recreated: no | recreated tree owned (lock/pid): no | exit: 1 worker stderr: remote-job-worker: cannot update worker heartbeatEvidence: fm-remote-doctor and fm_remote_job_probe agree on the freshness window
Source: fm-remote-doctor and fm_remote_job_probe agree on the freshness window
worker.ready heartbeat aged 15s; FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS reconfigured to 30 base-doctor(55db226) fm_remote_job_probe: READY | doctor: fixable: the remote job worker has not reported a fresh probe fixed-doctor(2621c0f) fm_remote_job_probe: READY | doctor: ok: the remote job worker completed the required-tool probeEvidence: Cadence + tripwire tests: fail before, pass after (plus mutation check)
Source: Cadence + tripwire tests: fail before, pass after (plus mutation check)
# HEAD tests against the PRE-FIX worker (55db226) not ok - idle reap forked date 24 times across 24 poll ticks; the dead reap throttle regressed to running every poll tick # HEAD tests against the round-2 PRE-FIX worker (d5062fc) not ok - the worker kept serving after its state root was deleted # this branch ok - idle heartbeat and reap run on their own cadence, not on every poll tick ok - a deleted state root fails the worker fast instead of being recreated by the reap sweep ok - a heartbeat cadence outside the probe freshness window is refused before the worker serves ALL TESTS PASSED # Mutation check (heartbeat<freshness bound removed from the lib) not ok - a heartbeat interval of '10' was acceptedEvidence: Reproduction harnesses (idle cost, pickup latency, tripwire, doctor drift)
Source: Reproduction harnesses (idle cost, pickup latency, tripwire, doctor drift)
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
tests/fm-remote-job.test.sh:759- TheTICK_CALLS -ge 20guard exists so an under-sampled window fails as 'the cadence window is too short to measure' rather than as a cadence regression, but it is set below what the ratio assertions on lines 761 and 763 actually require, so a band of slow-runner outcomes still fails with the wrong message. Concrete trace: the launch sets FM_REMOTE_JOB_HEARTBEAT_INTERVAL_SECONDS=2 and FM_REMOTE_JOB_REAP_INTERVAL_SECONDS=2, and main() starts with next_heartbeat=t0+2 / next_reap=t0, so both gates land on the same second boundary - the heartbeat gate writes (mktemp contract: direct-PR ship tasks get one independent review before merge #1, next_heartbeat=t+2) and the reap branch's forced worker_refresh_heartbeat writes again (mktemp feat(skills): add per-project skill pointer inventories #2, next_heartbeat reset to t+2). The measurement window (log truncation at 746-748 tokill -TERMat 750) spanssleep 6plus scheduling, crossing 3 or 4 boundaries, and the TERM path adds one more mktemp via worker_publish_quarantine (bin/fm-remote-job-worker.sh:179). So MKTEMP_CALLS is 7 (3 boundaries) or 9 (4 boundaries), and line 763 requires TICK_CALLS >= 21 or >= 27 respectively. With TICK_CALLS in [20,26] the run passes the 'too short' guard and then fails as 'idle heartbeat forked mktemp 9 times across 22 poll ticks; expected the write gated to its own cadence' - a cadence regression that did not occur. Reaching that band needs roughly 250ms per idle poll iteration (normal is 2-5ms, so hundreds to thousands of ticks), which makes this narrow rather than routine, but the guard's whole purpose is to cover exactly that regime. Mechanical remedy: raise the guard to cover the worst-case requirement (e.g.-ge 40), which still leaves the every-poll-tick regression (MKTEMP == TICK_CALLS) far outside the ratio bound.bin/fm-remote-job-worker.sh:78- worker_refresh_heartbeat writesnext_heartbeatwithout declaring it, relying on bash dynamic scoping to hit main's local (line 685). worker_run_with_timeout independently declareslocal ... next_heartbeat(line 413) for the in-job 1s heartbeat cadence. Today the helper is only ever called from main's loop body (lines 703, 707, 713, 720) and never with worker_run_with_timeout on the stack, so there is no reachable defect and the current code is correct. Recording it because the failure mode is silent rather than loud: a future call to worker_refresh_heartbeat from anywhere inside worker_run_with_timeout would update that function's local instead of main's, leaving main's deadline permanently in the past so the top gate fires on every poll tick - restoring exactly the ~11% idle CPU burn this change removes, with every test still green. No action needed now; if the helper ever grows a second caller, give it a distinct variable name or set it explicitly in main.tests/fm-remote-job.test.sh:342- Pre-existing timing testqueue time consumed the second job's execution timeout(tests/fm-remote-job.test.sh:342) is load-sensitive: it failed twice when I ran two full suites concurrently on this machine, and passed on every serial run. It is untouched by this change and passed on all three serial runs of this branch, so it is not a blocker — noting it because it is the suite's thinnest timing margin and could surface as a spurious CI failure under a loaded runner.bash tests/fm-remote-job.test.sh(3 serial runs on this branch, ALL TESTS PASSED, including the two new cadence/tripwire tests)bash tests/fm-remote-job-orphan-reap.test.shbash tests/fm-remote-doctor.test.shAdded and ran a new focused test:a heartbeat cadence outside the probe freshness window is refused before the worker serves— exercises fm_remote_job_validate_settings for bad/boundary heartbeat and reap intervals, then launches the real worker with FM_REMOTE_JOB_HEARTBEAT_INTERVAL_SECONDS=10 and asserts non-zero exit, an invalid-bounds stderr line, and no worker.readyMutation check: removed[ "$FM_REMOTE_JOB_HEARTBEAT_INTERVAL_SECONDS" -lt "$FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS" ]from a scratch copy of the lib and reran the suite →not ok - a heartbeat interval of '10' was acceptedFail-before: ran the current tests against the pre-fix worker (55db226bin in a scratch tree) →not ok - idle reap forked date 24 times across 24 poll ticksFail-before: ran the current tests against the round-2 pre-fix worker (d5062fcbin) →not ok - the worker kept serving after its state root was deletedManual idle-cost measurement, base vs fixed worker under shipped defaults (poll 0.05s, heartbeat 3s, reap 60s): shimmed mktemp/chmod/mv/date call counts andps -o time=CPU time over a 30s idle window (harness: evidence/fm-idle-harness.sh)Manual dispatch-latency measurement: 10fm-touch-job.shdispatches per variant, timing stage→running and stage→done with Time::HiRes (harness: evidence/fm-pickup-harness.sh)Manual deleted-state-root check againstd5062fcvs this branch, heartbeat=9s reap=1s (harness: evidence/fm-tripwire-harness.sh)Manual doctor/probe agreement check with FM_REMOTE_JOB_PROBE_FRESHNESS_SECONDS reconfigured to 30 and a live worker's heartbeat backdated 15s, base doctor vs fixed doctor (harness: evidence/fm-doctor-drift.sh)✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.