[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7584A9EPC3C6C4YD4Q3F5EZ":3,"skill-same:01M7584A9EPC3C6C4YD4Q3F5EZ":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M7584A9EPC3C6C4YD4Q3F5EZ","detached-worker-pattern",null,"Cron tick budget kill: detached worker + result sweep.","lukemcqueen\u002Fsteadfaste-fleet","lukemcqueen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F405240?v=4","01M757MHPAGRXTJAT46SKZP98R","Luke McQueen","01M757MHPZ573KP8DT9GB8SBQ7",4,"MIT","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdetached-worker-pattern\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: detached-worker-pattern\ndescription: \"Cron tick budget kill: detached worker + result sweep.\"\nversion: 1.0.0\ncategory: devops\nmetadata:\n  hermes:\n    tags: [cron, background, worker, timeout, at-least-once, result-receipt, deadlock, decouple]\n    related_skills: [cron-job-management, fleet-commands]\n---\n\n# Detached Worker Pattern — Surviving the Execution Budget\n\n## When to use\n\nAny **budgeted, at-least-once consumer** (a cron tick, a message handler tick,\na job queue worker) that must run work whose worst-case runtime can exceed the\nconsumer's execution budget:\n\n- Cron ticks with an execution timeout (`HERMES_CRON_TIMEOUT`, no_agent script\n  limits) running subprocess chains (pull + deploy + doctor ≈ 390s worst case\n  inside a 300s budget)\n- Handlers that early-archive the request message then process it — a kill\n  mid-processing loses the receipt forever (the message never re-processes)\n- Any \"send a result back\" flow where silence is indistinguishable from success\n\n## The failure it prevents (verified 2026-08-18)\n\nFleet `UPDATE_REQUEST` dispatch: 5 hosts consumed the request and the updates\nLANDED (verified via direct probes: repo + deploy sync at the target SHA), but\n**0\u002F5 returned UPDATE_RESULTs**. Root cause: the handler ran\npull+fleet-update+doctor synchronously (~390s worst case) inside a cron tick\nbudgeted at ~300s. The tick was killed mid-processing — after the early-archive\n— so the request was never re-processed and the receipt was silently lost.\n\"Consumed but no result\" looked like a bus failure; it was an execution-budget\nkill.\n\n## The pattern (four pieces)\n\n### 1. Detached worker\n\n```python\nsubprocess.Popen(\n    [sys.executable, \"-c\", WORKER_CODE, handler_path, json.dumps(msg_body), corr],\n    start_new_session=True,          # survives the parent's budget kill\n    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,\n)\n```\n- `start_new_session=True` detaches from the parent's process group so a kill\n  aimed at the tick's process GROUP cannot take the worker down. It does NOT\n  survive a **systemd oneshot unit's cgroup teardown**: with `KillMode` left at\n  its default (`control-group`), systemd kills every remaining process in the\n  unit's cgroup the moment the tick's `ExecStart` exits, so the worker dies\n  seconds after being spawned. Measured 2026-10-24 on the bridge-timer hosts:\n  four UPDATE_REQUESTs were consumed, none updated, and all four answered only\n  at the 30-minute sweep timeout (`docs\u002Fevidence\u002Fcost4-host-cost-adapter\u002F\n  update-worker-2026-10-24.txt`) — while the identical worker run by hand\n  (outside the unit) completed. A detached-worker consumer that is a systemd\n  unit needs `KillMode=process` on that unit; verifying the pattern means\n  checking the UNIT, not just the Popen flags.\n- The worker does the LONG work and writes its result to a state file:\n  `state\u002Fpending-results\u002F\u003Ccorr>.json` — never sends over the bus itself.\n\n### 2. State-file result + in-flight marker\n\n- Worker writes `\u003Ccorr>.json` when done (success OR crash — wrap in try\u002Fexcept\n  so a crash still yields a structured error result).\n- Handler writes `\u003Ccorr>.running` when spawning; worker deletes it on finish.\n  The marker also tells concurrent readers \"a deploy is mid-flight\" — see #4.\n\n### 3. Per-tick sweep (runs EVERY tick, even with no new work)\n\n```python\nfor f in sorted(PENDING_DIR.glob(\"*.json\")):\n    result = json.loads(f.read_text())\n    send_result(corr, result)          # bus \u002F webhook \u002F queue\n    f.unlink(missing_ok=True)\nfor m in sorted(PENDING_DIR.glob(\"*.running\")):\n    if now - m.stat().st_mtime > TIMEOUT:\n        send_result(corr, {\"success\": False, \"error\": \"worker died\"})\n        m.unlink(missing_ok=True)\n```\n- A worker that finished while the spawning tick was killed is still delivered\n  by the next tick — the guarantee that makes the pattern correct.\n- Stale `.running` markers (worker died without writing) become explicit\n  timeout error results — never permanent silence.\n- Duplicates on re-sweep are possible (kill between send and delete); make\n  consumers idempotent by correlation id, not by hoping for exactly-once.\n\n### 4. In-flight guard for concurrent health checks\n\nA tick that ALSO runs its own health doctor will catch the worker's mid-deploy\nstate (checksum mismatches, files half-rewritten) and fire false FAIL alerts.\nSkip the health check while any `.running` marker exists.\n\n## Key implementation notes\n\n- The worker must insert its own `sys.path` before importing the parent module —\n  cron children don't inherit PYTHONPATH. Insert **every directory the parent\n  imports from, not just the parent's own**: `agent-message-handler.py` imports\n  `hermes_paths` from its parent directory, so a worker that inserted only the\n  handler's dir died at `exec_module` (2026-10-24). And put the LOAD inside the\n  try, not just the work: a loader that raises outside it writes no result and\n  leaves a stale `.running` marker, which is indistinguishable from a hung\n  deploy and costs the requester the whole timeout.\n- Load the parent module by file path (`importlib.util.spec_from_file_location`)\n  and call its existing process function — don't duplicate the logic.\n- Spawn-failure fallback: if `Popen` raises, fall through to the legacy\n  synchronous path rather than dropping the request.\n- The tick itself now returns in seconds instead of minutes — a side benefit\n  that also frees the tick budget for other work.\n\n## Verified reference implementation\n\n`agent-message-handler.py` UPDATE_REQUEST branch (commit `282045ec`,\n2026-08-18): `_spawn_update_worker()` \u002F `_send_pending_update_results()` \u002F\n`_update_worker_code()` in `ops\u002Fscripts\u002Fagent\u002Fagent-message-handler.py`,\n`state\u002Fpending-update-results\u002F` under `FLEET_DEPLOY_HOME`. Tested end-to-end:\nworker → sweep → result received; worker-death (stale marker) → timeout result;\nmid-deploy health-doctor skip (killed a false 9-fail alert).\n\n## Pitfalls\n\n- **Don't keep the result send inside the worker** — if the worker itself is\n  killed (OOM, host restart) the result file never appears and the sweep's\n  timeout path covers it; if the send were inside the worker, both die together.\n- **Budget math**: sum ALL synchronous subprocess timeouts (pull 60s + update\n  300s + doctor 30s = 390s worst case) against the ACTUAL tick budget\n  (HERMES_CRON_TIMEOUT, default 300s, fleet-wide env — not per-job). If\n  worst-case > budget, this pattern is required, not optional.\n- **Early-archive makes kills fatal**: if the consumer archives the request\n  before processing, a kill mid-processing is unrecoverable without a\n  pending-result file. The pattern is the recovery mechanism.\n- **Sweep must run before the \"no work → return early\" shortcut** in the tick,\n  or completed results wait for the next message to arrive.\n","# Detached Worker Pattern — Surviving the Execution Budget\n\n## When to use\n\nAny **budgeted, at-least-once consumer** (a cron tick, a message handler tick,\na job queue worker) that must run work whose worst-case runtime can exceed the\nconsumer's execution budget:\n\n- Cron ticks with an execution timeout (`HERMES_CRON_TIMEOUT`, no_agent script\n  limits) running subprocess chains (pull + deploy + doctor ≈ 390s worst case\n  inside a 300s budget)\n- Handlers that early-archive the request message then process it — a kill\n  mid-processing loses the receipt forever (the message never re-processes)\n- Any \"send a result back\" flow where silence is indistinguishable from success\n\n## The failure it prevents (verified 2026-08-18)\n\nFleet `UPDATE_REQUEST` dispatch: 5 hosts consumed the request and the updates\nLANDED (verified via direct probes: repo + deploy sync at the target SHA), but\n**0\u002F5 returned UPDATE_RESULTs**. Root cause: the handler ran\npull+fleet-update+doctor synchronously (~390s worst case) inside a cron tick\nbudgeted at ~300s. The tick was killed mid-processing — after the early-archive\n— so the request was never re-processed and the receipt was silently lost.\n\"Consumed but no result\" looked like a bus failure; it was an execution-budget\nkill.\n\n## The pattern (four pieces)\n\n### 1. Detached worker\n\n```python\nsubprocess.Popen(\n    [sys.executable, \"-c\", WORKER_CODE, handler_path, json.dumps(msg_body), corr],\n    start_new_session=True,          # survives the parent's budget kill\n    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,\n)\n```\n- `start_new_session=True` detaches from the parent's process group so a kill\n  aimed at the tick's process GROUP cannot take the worker down. It does NOT\n  survive a **systemd oneshot unit's cgroup teardown**: with `KillMode` left at\n  its default (`control-group`), systemd kills every remaining process in the\n  unit's cgroup the moment the tick's `ExecStart` exits, so the worker dies\n  seconds after being spawned. Measured 2026-10-24 on the bridge-timer hosts:\n  four UPDATE_REQUESTs were consumed, none updated, and all four answered only\n  at the 30-minute sweep timeout (`docs\u002Fevidence\u002Fcost4-host-cost-adapter\u002F\n  update-worker-2026-10-24.txt`) — while the identical worker run by hand\n  (outside the unit) completed. A detached-worker consumer that is a systemd\n  unit needs `KillMode=process` on that unit; verifying the pattern means\n  checking the UNIT, not just the Popen flags.\n- The worker does the LONG work and writes its result to a state file:\n  `state\u002Fpending-results\u002F\u003Ccorr>.json` — never sends over the bus itself.\n\n### 2. State-file result + in-flight marker\n\n- Worker writes `\u003Ccorr>.json` when done (success OR crash — wrap in try\u002Fexcept\n  so a crash still yields a structured error result).\n- Handler writes `\u003Ccorr>.running` when spawning; worker deletes it on finish.\n  The marker also tells concurrent readers \"a deploy is mid-flight\" — see #4.\n\n### 3. Per-tick sweep (runs EVERY tick, even with no new work)\n\n```python\nfor f in sorted(PENDING_DIR.glob(\"*.json\")):\n    result = json.loads(f.read_text())\n    send_result(corr, result)          # bus \u002F webhook \u002F queue\n    f.unlink(missing_ok=True)\nfor m in sorted(PENDING_DIR.glob(\"*.running\")):\n    if now - m.stat().st_mtime > TIMEOUT:\n        send_result(corr, {\"success\": False, \"error\": \"worker died\"})\n        m.unlink(missing_ok=True)\n```\n- A worker that finished while the spawning tick was killed is still delivered\n  by the next tick — the guarantee that makes the pattern correct.\n- Stale `.running` markers (worker died without writing) become explicit\n  timeout error results — never permanent silence.\n- Duplicates on re-sweep are possible (kill between send and delete); make\n  consumers idempotent by correlation id, not by hoping for exactly-once.\n\n### 4. In-flight guard for concurrent health checks\n\nA tick that ALSO runs its own health doctor will catch the worker's mid-deploy\nstate (checksum mismatches, files half-rewritten) and fire false FAIL alerts.\nSkip the health check while any `.running` marker exists.\n\n## Key implementation notes\n\n- The worker must insert its own `sys.path` before importing the parent module —\n  cron children don't inherit PYTHONPATH. Insert **every directory the parent\n  imports from, not just the parent's own**: `agent-message-handler.py` imports\n  `hermes_paths` from its parent directory, so a worker that inserted only the\n  handler's dir died at `exec_module` (2026-10-24). And put the LOAD inside the\n  try, not just the work: a loader that raises outside it writes no result and\n  leaves a stale `.running` marker, which is indistinguishable from a hung\n  deploy and costs the requester the whole timeout.\n- Load the parent module by file path (`importlib.util.spec_from_file_location`)\n  and call its existing process function — don't duplicate the logic.\n- Spawn-failure fallback: if `Popen` raises, fall through to the legacy\n  synchronous path rather than dropping the request.\n- The tick itself now returns in seconds instead of minutes — a side benefit\n  that also frees the tick budget for other work.\n\n## Verified reference implementation\n\n`agent-message-handler.py` UPDATE_REQUEST branch (commit `282045ec`,\n2026-08-18): `_spawn_update_worker()` \u002F `_send_pending_update_results()` \u002F\n`_update_worker_code()` in `ops\u002Fscripts\u002Fagent\u002Fagent-message-handler.py`,\n`state\u002Fpending-update-results\u002F` under `FLEET_DEPLOY_HOME`. Tested end-to-end:\nworker → sweep → result received; worker-death (stale marker) → timeout result;\nmid-deploy health-doctor skip (killed a false 9-fail alert).\n\n## Pitfalls\n\n- **Don't keep the result send inside the worker** — if the worker itself is\n  killed (OOM, host restart) the result file never appears and the sweep's\n  timeout path covers it; if the send were inside the worker, both die together.\n- **Budget math**: sum ALL synchronous subprocess timeouts (pull 60s + update\n  300s + doctor 30s = 390s worst case) against the ACTUAL tick budget\n  (HERMES_CRON_TIMEOUT, default 300s, fleet-wide env — not per-job). If\n  worst-case > budget, this pattern is required, not optional.\n- **Early-archive makes kills fatal**: if the consumer archives the request\n  before processing, a kill mid-processing is unrecoverable without a\n  pending-result file. The pattern is the recovery mechanism.\n- **Sweep must run before the \"no work → return early\" shortcut** in the tick,\n  or completed results wait for the next message to arrive.\n",{"name":5,"version":24,"category":25,"metadata":26,"description":7},"1.0.0","devops",{"hermes":27},{"tags":28,"related_skills":37},[29,30,31,32,33,34,35,36],"cron","background","worker","timeout","at-least-once","result-receipt","deadlock","decouple",[38,39],"cron-job-management","fleet-commands","main","9dc0e92c5fa81d4db5292b205716e8ea0c00d10e","skills\u002Fdevops\u002Fdetached-worker-pattern",1,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet","steadfaste.com","https:\u002F\u002Fgithub.com\u002Flukemcqueen","AI Architect | Building Hermes Cortex: governed multi-agent AI for autonomous software engineering | Enterprise Tech Consultant","2026-11-14 22:33:34",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill detached-worker-pattern",{"tool":55,"command":56},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill detached-worker-pattern",{"tool":58,"command":59},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill detached-worker-pattern","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fdetached-worker-pattern\u002FSKILL.md",true,[],[64,72,79,86,93,100],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":71},"01M7DXY4G8NSVB59K8B6S2AQNP","macbook-linux-maintenance","Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fmacbook-linux-maintenance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":71},"01M7DXXYJCXFJ3TGB84ZQ8KFE6","governance-regression-triage","Triage a host's governance issues: what changed.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fgovernance-regression-triage\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":71},"01M7DXXSAP1G8FDRJAMXQGBBMK","enforcement-immutability","Use when enforcement files lose their immutable flag.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fenforcement-immutability\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":71},"01M78SSDQVRYX64Y16X32TC0NS","steadfaste-fleet-repo-deploy","Use when committing to the steadfaste-fleet repo.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-repo-deploy\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":71},"01M78SS928F3R2RJAYVW4E30CE","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.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-maintenance\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":71},"01M78SP1CHW0T0BWE5ZT6JBPX8","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.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-preflight\u002FSKILL.md",[],[]]