detached-worker-pattern
Cron tick budget kill: detached worker + result sweep.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 4
- Forks
- 1
01 前言 Front Matter
- name
- detached-worker-pattern
- version
- 1.0.0
- category
- devops
- metadata
- { "hermes": { "tags": [ "cron", "background", "worker", "timeout", "at-least-once", "result-receipt", "deadlock", "decouple" ], "related_skills": [ "cron-job-management", "fleet-commands" ] } }
- description
- Cron tick budget kill: detached worker + result sweep.
03 SKILL.md 正文
Detached Worker Pattern — Surviving the Execution Budget
When to use
Any budgeted, at-least-once consumer (a cron tick, a message handler tick, a job queue worker) that must run work whose worst-case runtime can exceed the consumer's execution budget:
- Cron ticks with an execution timeout (
HERMES_CRON_TIMEOUT, no_agent script limits) running subprocess chains (pull + deploy + doctor ≈ 390s worst case inside a 300s budget) - Handlers that early-archive the request message then process it — a kill mid-processing loses the receipt forever (the message never re-processes)
- Any "send a result back" flow where silence is indistinguishable from success
The failure it prevents (verified 2026-08-18)
Fleet UPDATE_REQUEST dispatch: 5 hosts consumed the request and the updates
LANDED (verified via direct probes: repo + deploy sync at the target SHA), but
0/5 returned UPDATE_RESULTs. Root cause: the handler ran
pull+fleet-update+doctor synchronously (~390s worst case) inside a cron tick
budgeted at ~300s. The tick was killed mid-processing — after the early-archive
— so the request was never re-processed and the receipt was silently lost.
"Consumed but no result" looked like a bus failure; it was an execution-budget
kill.
The pattern (four pieces)
1. Detached worker
subprocess.Popen(
[sys.executable, "-c", WORKER_CODE, handler_path, json.dumps(msg_body), corr],
start_new_session=True, # survives the parent's budget kill
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
start_new_session=Truedetaches from the parent's process group so a kill aimed at the tick's process GROUP cannot take the worker down. It does NOT survive a systemd oneshot unit's cgroup teardown: withKillModeleft at its default (control-group), systemd kills every remaining process in the unit's cgroup the moment the tick'sExecStartexits, so the worker dies seconds after being spawned. Measured 2026-10-24 on the bridge-timer hosts: four UPDATE_REQUESTs were consumed, none updated, and all four answered only at the 30-minute sweep timeout (docs/evidence/cost4-host-cost-adapter/ update-worker-2026-10-24.txt) — while the identical worker run by hand (outside the unit) completed. A detached-worker consumer that is a systemd unit needsKillMode=processon that unit; verifying the pattern means checking the UNIT, not just the Popen flags.- The worker does the LONG work and writes its result to a state file:
state/pending-results/<corr>.json— never sends over the bus itself.
2. State-file result + in-flight marker
- Worker writes
<corr>.jsonwhen done (success OR crash — wrap in try/except so a crash still yields a structured error result). - Handler writes
<corr>.runningwhen spawning; worker deletes it on finish. The marker also tells concurrent readers "a deploy is mid-flight" — see #4.
3. Per-tick sweep (runs EVERY tick, even with no new work)
for f in sorted(PENDING_DIR.glob("*.json")):
result = json.loads(f.read_text())
send_result(corr, result) # bus / webhook / queue
f.unlink(missing_ok=True)
for m in sorted(PENDING_DIR.glob("*.running")):
if now - m.stat().st_mtime > TIMEOUT:
send_result(corr, {"success": False, "error": "worker died"})
m.unlink(missing_ok=True)
- A worker that finished while the spawning tick was killed is still delivered by the next tick — the guarantee that makes the pattern correct.
- Stale
.runningmarkers (worker died without writing) become explicit timeout error results — never permanent silence. - Duplicates on re-sweep are possible (kill between send and delete); make consumers idempotent by correlation id, not by hoping for exactly-once.
4. In-flight guard for concurrent health checks
A tick that ALSO runs its own health doctor will catch the worker's mid-deploy
state (checksum mismatches, files half-rewritten) and fire false FAIL alerts.
Skip the health check while any .running marker exists.
Key implementation notes
- The worker must insert its own
sys.pathbefore importing the parent module — cron children don't inherit PYTHONPATH. Insert every directory the parent imports from, not just the parent's own:agent-message-handler.pyimportshermes_pathsfrom its parent directory, so a worker that inserted only the handler's dir died atexec_module(2026-10-24). And put the LOAD inside the try, not just the work: a loader that raises outside it writes no result and leaves a stale.runningmarker, which is indistinguishable from a hung deploy and costs the requester the whole timeout. - Load the parent module by file path (
importlib.util.spec_from_file_location) and call its existing process function — don't duplicate the logic. - Spawn-failure fallback: if
Popenraises, fall through to the legacy synchronous path rather than dropping the request. - The tick itself now returns in seconds instead of minutes — a side benefit that also frees the tick budget for other work.
Verified reference implementation
agent-message-handler.py UPDATE_REQUEST branch (commit 282045ec,
2026-08-18): _spawn_update_worker() / _send_pending_update_results() /
_update_worker_code() in ops/scripts/agent/agent-message-handler.py,
state/pending-update-results/ under FLEET_DEPLOY_HOME. Tested end-to-end:
worker → sweep → result received; worker-death (stale marker) → timeout result;
mid-deploy health-doctor skip (killed a false 9-fail alert).
Pitfalls
- Don't keep the result send inside the worker — if the worker itself is killed (OOM, host restart) the result file never appears and the sweep's timeout path covers it; if the send were inside the worker, both die together.
- Budget math: sum ALL synchronous subprocess timeouts (pull 60s + update 300s + doctor 30s = 390s worst case) against the ACTUAL tick budget (HERMES_CRON_TIMEOUT, default 300s, fleet-wide env — not per-job). If worst-case > budget, this pattern is required, not optional.
- Early-archive makes kills fatal: if the consumer archives the request before processing, a kill mid-processing is unrecoverable without a pending-result file. The pattern is the recovery mechanism.
- Sweep must run before the "no work → return early" shortcut in the tick, or completed results wait for the next message to arrive.
04 同仓库更多 Skills
macbook-linux-maintenance
Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.
governance-regression-triage
Triage a host's governance issues: what changed.
enforcement-immutability
Use when enforcement files lose their immutable flag.
steadfaste-fleet-repo-deploy
Use when committing to the steadfaste-fleet repo.
steadfaste-fleet-maintenance
Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.
fleet-preflight
DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its "Repo-Specific Pre-Flight" section covers git search, Hermes boundary, and deployment verification.