Repository navigation
fix(harness): reconcile sync runs orphaned by a supervisor crash - #579
Conversation
…soctl#558) A sync /v1/runs leaf held its whole lifecycle in worker memory, so a supervisor pod deletion (PID 1's exit SIGKILLs the workers before the IPC disconnect path runs) left no leaf:result record, no run_finalized audit, and a /runs/status that answered 'queued' forever -- the sandbox-pod-kill path reconciled only because its worker survived the failure it observed. Every sync run now records an in-flight marker (sh:run:<sid>) plus a short-TTL heartbeat in the data-plane Redis, and every worker arms a periodic reaper that atomically claims markers whose heartbeat is gone and finalizes them as failed/owner_lost -- the same terminal shape the sandbox-kill path produces, so mocactl get reads a legible failure instead of 404/queued indefinitely. The reaper is periodic rather than boot-only because a worker restarted seconds after an OOM crash would otherwise find the orphan's heartbeat not yet stale and never look again. Adds SH_RUN_HEARTBEAT_MS / SH_RUN_STALE_MS / SH_RUN_REAP_INTERVAL_MS knobs, documented in docs/reference/configuration.md. Fixes rossoctl#558 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
| `[run-lease] could not record in-flight run ${sid}: ${ | ||
| err instanceof Error ? err.message : String(err) | ||
| }; running unreconciled`, |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Reviewed at 7f56e8a. The lease + periodic reaper design is sound: the GETDEL claim, the revive-restore re-check, the restore-on-failed-write and the fail-open begin all hold up, and arming periodically (not boot-only) correctly covers the OOM-restart case. sh:run: collides with no existing key on main, and sanitized sids can't contain :, so the :hb skip is safe. The supervisor's N workers each sweeping is fine given the atomic claim.
One must-fix: the reaper can overwrite a run's real result with owner_lost (inline on run-lease.ts:221).
Not anchored to the diff:
- suggestion —
docs/reference/leaf-and-envelope.md:69lists thefailedreasons a stored record //runs/statuscan carry; addowner_lost(written only by the reaper). Also the audit-mirror spec's closed field whitelist (docs/specs/2026-10-20-audit-log-mirror-design.md§3.1) has neither the newreaperfield nor theowner_lostreason. Add both, so the "closed set" stays true. - FYI: the CodeQL log-injection alert on
run-lease.ts:152looks like a false positive, becausesidthere is alreadytoSessionId-sanitized ([A-Za-z0-9._-]). Dismissing it is fine.
Author: pdettori (MEMBER — maintainer) · Agent/IDE config: none · Commits: 1, signed off · CI: 15/15 green
| owner: typeof marker.owner === 'string' ? marker.owner : 'unknown', | ||
| }; | ||
| try { | ||
| await writeResult( |
There was a problem hiding this comment.
must-fix — the reaper never checks whether the run already wrote its result, so it can turn a finished run into failed/owner_lost.
In handleRunLeafParsed, writeResult (the real record) runs before finally { await lease.release() }. Two ways the marker survives a completed run:
- The worker is SIGKILLed between
writeResultandrelease()(it also has to write the response first). This is the supervisor-pod-kill scenario this PR targets, and it can land at any instant. release()is best-effort: ifdel(markerKey)fails (a Redis blip) whiledel(hbKey)succeeds, the marker is left with no heartbeat right away. If both fail, the heartbeat simply expires afterSH_RUN_STALE_MS.
Either way, the next sweep GETDELs the marker and writeResults owner_lost over a done/solved/responded record. A client that already read the real result won't notice, but one that polls afterward sees a terminal failure. It also emits a second run_finalized for a run that already had one.
Suggested fix: before writing, read leaf:result:<sid> and skip the write (just drop the marker and heartbeat) when the record's ts is at or after marker.startedAt. Compare ts rather than "a record exists", because a re-run of the same session id can find an older record. Add a run-lease test: marker + no heartbeat + a fresh done record, then reapOrphanedRuns leaves the record untouched and reports nothing.
There was a problem hiding this comment.
Fixed in 9f3b2de. The reaper now reads leaf:result:<sid> after claiming the marker and drops the stale marker untouched (no write, no run_finalized, nothing reported) when the record's ts is at or after marker.startedAt — the run's own final word, exactly the SIGKILL-between-writeResult-and-release shape. ts rather than existence, per your suggestion, so a re-run of the same sid still reaps over an older record; a record with an unparseable ts reads as older (reap), and a marker with no readable startedAt suppresses the write whenever any record exists (conservative for an unattributable marker). Two new tests cover the fresh-record skip and the older-record reap.
| export function runLeaseTimings(env: NodeJS.ProcessEnv = process.env): RunLeaseTimings { | ||
| return { | ||
| heartbeatMs: positiveInt(env, 'SH_RUN_HEARTBEAT_MS', 10_000), | ||
| staleMs: positiveInt(env, 'SH_RUN_STALE_MS', 60_000), |
There was a problem hiding this comment.
nit — nothing ties SH_RUN_STALE_MS to SH_RUN_HEARTBEAT_MS. An operator who sets stale ≤ heartbeat (e.g. SH_RUN_HEARTBEAT_MS=60000 with the default stale of 60000) makes every live run read as dead between beats, and the reaper then fails them all. Clamp it (e.g. staleMs = max(staleMs, 2 * heartbeatMs)), or warn at boot, and note the constraint in configuration.md.
There was a problem hiding this comment.
Fixed in 9f3b2de — took the clamp rather than a boot warning: staleMs = max(staleMs, 2 * heartbeatMs) in runLeaseTimings, since the 60000/60000 failure mode is silent and total, and a clamp can only make reconciliation slower, never wrong. Noted the constraint in configuration.md's SH_RUN_STALE_MS row, with a clamp test added.
…n result (rossoctl#558) Review must-fix on rossoctl#579: the reaper never checked whether a run had already written its result, so a marker whose release was lost (a SIGKILL between writeResult and the release DEL, or a failed best-effort DEL) let the next sweep overwrite a done/solved/responded record with failed/owner_lost and emit a second run_finalized. The reaper now reads leaf:result:<sid> before writing and drops the stale marker untouched when the record's ts is at or after the marker's startedAt -- the run's own final word. Comparing ts rather than existence keeps a re-run of the same session id reaping over an older record. Also from review: runLeaseTimings clamps staleMs to at least 2x heartbeatMs (an operator setting stale <= heartbeat made every live run read as dead between beats and the reaper failed them all), noted in configuration.md; leaf-and-envelope.md and the audit-mirror spec's closed sets gain owner_lost (reason) and reaper (field), with the control-plane whitelist test updated to match. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Review follow-ups landed in 9f3b2de (replies inline on the two anchored threads):
Typecheck, prettier, and the touched suites (harness 16, control-plane audit-log 5, route 14) all green. |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Re-reviewed the incremental diff 7f56e8a..9f3b2de (fast-forward, 6 files, +107/−18). Both items from the previous round are closed:
- must-fix (reaper overwrites a finished run): fixed. After the
GETDELclaim and the heartbeat re-check,reapOrphanedRunsnow readsleaf:result:<sid>. When the record'stsis at or aftermarker.startedAt, it drops the heartbeat and skips the write, theonReap/run_finalized, and the report. A record from before the marker (an earlier run of the same sid) is still reaped. Both sides have tests. An unparseabletsfalls through to reaping, and a marker with nostartedAtsuppresses the write whenever a record exists. Both are reasonable choices. The holder writes both timestamps from the same pod clock, so clock skew doesn't affect the SIGKILL case. - nit (stale ≤ heartbeat): fixed with the clamp
staleMs = max(staleMs, 2×heartbeatMs), a test, and a note in the configuration.md row. - suggestion (docs): done. leaf-and-envelope.md lists
owner_lost, the audit-mirror spec §3.1 gains theowner_lostreason and thereaperfield, andALLOWED_KEYSin audit-log.test.ts hasreaper. - CodeQL log injection on
run-lease.ts:156: still a false positive (sidis sanitized). OK to dismiss.
One optional test nit is inline.
Commits: 2, both signed off · CI at review time: 13/15 green, check and lint still pending. Confirm they're green before merging.
| // each: a record whose `ts` cannot be parsed reads as older (reap), while a marker with no | ||
| // readable `startedAt` cannot attribute any record to this run, so any record present | ||
| // suppresses the write. | ||
| const existing = await readResult(store, sid); |
There was a problem hiding this comment.
nit: the new tests cover the fresh-record skip and the older-record reap. They don't cover the third branch, where a marker with no readable startedAt (unparseable or legacy marker JSON) suppresses the write whenever any record exists. A small test (marker {} or "garbage" plus any record → reaped is [] and the record is unchanged) would lock that conservative choice in place. Without it, a later refactor of the startedAt === undefined || guard could quietly change it.
Fixes #558.
Root cause
A sync
/v1/runsleaf holds its entire lifecycle in the worker process that received the POST: it registers in no registry, no queue, nothing in Redis. When the supervisor pod is deleted, PID 1's exit SIGKILLs the workers before the IPCdisconnectgraceful path can run (worker.tsdocuments exactly this), so thefinallythat wouldwriteResult(leaf:result:<sid>)never fires. Result:/runs/statusanswersqueuedforever (or a bare 404 through an edge),run_startednever pairs withrun_finalized, and the control-plane session row staysstate=activewith nothing to reconcile it. The sandbox-pod-kill path reconciles precisely because its worker survives the failure it observes and finalizes in-band.Fix (option (a) from the issue)
harness/src/run-lease.ts): every sync run now records an in-flight markersh:run:<sid>(holder id + raw session id, TTL = result TTL) plus a short-TTL heartbeat keysh:run:<sid>:hbrefreshed every 10 s. Begin is fail-open — a Redis that can't take the marker gets a warning, not a failed run — andrelease()clears both keys from afinallythat covers the saturation-retry loop, the 503 early return, and a thrownrunLeafalike.armRunReaper, wired inworker.tsboot; 30 s default) that claims markers whose heartbeat is gone — atomically, viaGETDEL, so the N workers per supervisor can't double-finalize — and writes{status: 'failed', reason: 'owner_lost'}with the sameleaf:resultshape the sandbox-kill path produces, plus therun_finalizedaudit (markedreaper: true) itsrun_startedis still waiting for. A holder that revives between the stale read and the claim gets its marker restored rather than a failure to overwrite.After the fix,
mocactl get <sid>on a supervisor-killed session returns a legible terminalfailed/owner_lostwithin ~90 s (stale window + sweep interval), instead ofhttp_404forever, andmocactl sessions/getno longer disagree about whether the session is lost.New knobs (documented in
docs/reference/configuration.md):SH_RUN_HEARTBEAT_MS(10 s),SH_RUN_STALE_MS(60 s),SH_RUN_REAP_INTERVAL_MS(30 s).Out of scope (follow-ups)
failed / fetch failed (UND_ERR_SOCKET)still reads like a server-side verdict; with this fixmocactl geton the same session now shows the server-sideowner_lost, but the ledger wording itself is unchanged.state=activeafter reconciliation, as it does for any completed session; freeing it remainsmocactl sessions delete.Testing
harness/test/run-lease.test.ts(13 tests): marker/heartbeat writes, heartbeat refresh vs expiry, release, fail-open begin, reaper skip-live / finalize-dead / claim-races / revive-restore / no-markers.run-leaf-route.test.ts(+4): the route holds the lease for the run's duration and releases it on success, on a thrownrunLeaf, and the reaper's arm/sweep/audit/stop surface.upstream/mainin the same environment (no local Redis available in this sandbox; CLAUDE.md notes those suites require Redis). Typecheck and prettier clean.🤖 Assisted-By: Claude Code