Skip to content

fix(harness): reconcile sync runs orphaned by a supervisor crash - #579

Merged
pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:fix/558-supervisor-crash-reconcile
Oct 22, 2026
Merged

pdettori merged 2 commits into
rossoctl:mainfrom
pdettori:fix/558-supervisor-crash-reconcile

Conversation

@pdettori

@pdettori pdettori commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Fixes #558.

Root cause

A sync /v1/runs leaf 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 IPC disconnect graceful path can run (worker.ts documents exactly this), so the finally that would writeResult(leaf:result:<sid>) never fires. Result: /runs/status answers queued forever (or a bare 404 through an edge), run_started never pairs with run_finalized, and the control-plane session row stays state=active with 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)

  • Run lease (harness/src/run-lease.ts): every sync run now records an in-flight marker sh:run:<sid> (holder id + raw session id, TTL = result TTL) plus a short-TTL heartbeat key sh:run:<sid>:hb refreshed every 10 s. Begin is fail-open — a Redis that can't take the marker gets a warning, not a failed run — and release() clears both keys from a finally that covers the saturation-retry loop, the 503 early return, and a thrown runLeaf alike.
  • Reaper: every worker arms a periodic sweep (armRunReaper, wired in worker.ts boot; 30 s default) that claims markers whose heartbeat is gone — atomically, via GETDEL, so the N workers per supervisor can't double-finalize — and writes {status: 'failed', reason: 'owner_lost'} with the same leaf:result shape the sandbox-kill path produces, plus the run_finalized audit (marked reaper: true) its run_started is still waiting for. A holder that revives between the stale read and the claim gets its marker restored rather than a failure to overwrite.
  • Periodic rather than boot-only on purpose: a worker that OOM-crashes mid-run is restarted by the supervisor within seconds — long before the 60 s heartbeat goes stale — so a one-shot boot scan would find the orphan still "alive" and never look again.

After the fix, mocactl get <sid> on a supervisor-killed session returns a legible terminal failed/owner_lost within ~90 s (stale window + sweep interval), instead of http_404 forever, and mocactl sessions/get no 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)

  • 🐛 Supervisor crash mid-leaf leaves session unrecoverable #558 point 3: the mocactl ledger row failed / fetch failed (UND_ERR_SOCKET) still reads like a server-side verdict; with this fix mocactl get on the same session now shows the server-side owner_lost, but the ledger wording itself is unchanged.
  • The control-plane session row stays state=active after reconciliation, as it does for any completed session; freeing it remains mocactl sessions delete.

Testing

  • New 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 thrown runLeaf, and the reaper's arm/sweep/audit/stop surface.
  • Suites: harness 680 passed / 17 failed, knative-server 522 passed / 3 files failed — identical failure sets on unmodified upstream/main in 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

…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]>
Comment thread harness/src/run-lease.ts
Comment on lines +150 to +152
`[run-lease] could not record in-flight run ${sid}: ${
err instanceof Error ? err.message : String(err)
}; running unreconciled`,

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:69 lists the failed reasons a stored record / /runs/status can carry; add owner_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 new reaper field nor the owner_lost reason. Add both, so the "closed set" stays true.
  • FYI: the CodeQL log-injection alert on run-lease.ts:152 looks like a false positive, because sid there is already toSessionId-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

Comment thread harness/src/run-lease.ts
owner: typeof marker.owner === 'string' ? marker.owner : 'unknown',
};
try {
await writeResult(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The worker is SIGKILLed between writeResult and release() (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.
  2. release() is best-effort: if del(markerKey) fails (a Redis blip) while del(hbKey) succeeds, the marker is left with no heartbeat right away. If both fail, the heartbeat simply expires after SH_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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread harness/src/run-lease.ts Outdated
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@pdettori

Copy link
Copy Markdown
Member Author

Review follow-ups landed in 9f3b2de (replies inline on the two anchored threads):

  • must-fix — reaper no longer overwrites a run's own result: it reads leaf:result:<sid> after claiming the marker and drops the stale marker untouched when the record's ts ≥ marker.startedAt (ts comparison, not existence, so a same-sid re-run still reaps over an older record). Two new run-lease tests cover both sides.
  • suggestion — leaf-and-envelope.md now lists owner_lost among the stored-record failed reasons, and the audit-mirror spec §3.1 gains both the owner_lost reason and the reaper field, with ALLOWED_KEYS in audit-log.test.ts updated so the closed set stays enforced.
  • CodeQL log-injection on run-lease.ts — agreed it's a false positive (sid is leafSessionId-sanitized to [A-Za-z0-9._-] before it reaches any log line); left for dismissal rather than distorting the log format to satisfy the scanner.

Typecheck, prettier, and the touched suites (harness 16, control-plane audit-log 5, route 14) all green.

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 GETDEL claim and the heartbeat re-check, reapOrphanedRuns now reads leaf:result:<sid>. When the record's ts is at or after marker.startedAt, it drops the heartbeat and skips the write, the onReap/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 unparseable ts falls through to reaping, and a marker with no startedAt suppresses 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 the owner_lost reason and the reaper field, and ALLOWED_KEYS in audit-log.test.ts has reaper.
  • CodeQL log injection on run-lease.ts:156: still a false positive (sid is 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.

Comment thread harness/src/run-lease.ts
// 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@pdettori
pdettori merged commit a638111 into rossoctl:main Oct 22, 2026
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Supervisor crash mid-leaf leaves session unrecoverable

3 participants