Skip to content

fix(platform): recover background jobs stranded on crash or restart - #3157

Merged
larryro merged 8 commits into
mainfrom
fix/job-liveness-watchdogs
Sep 3, 2026
Merged

larryro merged 8 commits into
mainfrom
fix/job-liveness-watchdogs

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

The invariant

Every background job that advances a user-visible row must, on a crash or restart, either retry to completion (idempotently) or land the row in an honest terminal/retryable state that a waker re-drives. This PR closes the "断头路" (dead-end) class the review kept surfacing: a job registered retryLimit: 0 with no watchdog, so if the worker dies or the handler throws once between claiming work and finishing it, the row is left non-terminal (queued/claimed/running/parked) that nothing ever re-drives — and the user is never told.

Each lane's waker is a directly-callable function (unit- and integration-testable), never a reliance on pg-boss's internal expiry-retry timing.

Per-lane table

Lane (job) Failure on crash/restart Mechanism chosen Waker
task.agent_steer kickFallback omitted organizationId; the shim binds it into SQL → postgres.js UNDEFINED_VALUE → every settled-run fallback kick lost (retryLimit 0) Plain bug: pass args.organizationId (TurnKeys carries it) Immediate — the kick itself
task.agent_turn Start job lost before setAgentRunRunning → run queued, no op row, no capacity stamp → invisible to the running-state re-attach, the parked wake, and the deadline sweep for 12h recoverStuckQueuedTaskAgentRuns: CAS-rotate the exec id (single-winner) + re-enqueue task.agent_turn; fail immediately if the agent was deleted watchdog.task_agents (2 min)
automation.ask_resume Resume lost to a restart while the run parks on the asking exec → the awaiting_human exemption skips it → stranded to the 7-day ask deadline recoverAnsweredAskResumes: re-enqueue ask_resume (idempotent — retargetAgentCursor is a FOR-UPDATE CAS on the asking exec; a throw self-settles) watchdog.automation_agents (2 min)
object_storage.backfill Crash mid-copy → status='running' forever → the object_storage_backfill_one_running partial unique index rejects every future backfill (409) recoverStuckBackfills: fail stale runs with a reason (re-run is idempotent — copied blobs are skipped) watchdog.object_storage (10 min, new)
chat.deferred_send_poll Poll self-chain severs → send waiting forever; crash after the claim → claimed wedge (uncancellable tray chip) singletonKey + short policy dedups the chain, so a blind re-poll only revives dead chains; recoverStuckDeferredSends re-polls waiting rows and clears wedged claimed rows; the claim now stamps waiting_since_ms watchdog.deferred_sends (2 min, new)
conversation.send_message Worker killed mid-send or job expired past 600s → reply queued forever, retry/discard UI hidden (needs failed) Migration 0065 adds status_changed_at_ms + a partial index; recoverStuckConversationSends flips stale queued rows to failed with a reason watchdog.conversation_sends (5 min, new)

Per-finding: fix · test · verification

1 — Outbound conversation reply stuck queued forever (send.ts:840 / tasks.ts:372). VERIFIED. The handler settles failed on its own throw, so the dead-end is specifically a lost/expired job leaving the row queued with no waker; a retry also re-queues without touching created_at_ms, so no existing column dates the current queued state → migration 0065 adds status_changed_at_ms (stamped at insert/retry/sent/failed) + a partial index; the sweep flips stale queued → failed and emits a hint so the existing retry surface appears. Test: colocated unit locks the failed-flip + hint; integration probe seeds a stale queued send, sweeps it, and proves retrySendMessage re-opens it (fresh queued spared).

2 — Deferred-send chain severs / claimed wedge (deferred-sends.ts:370 & :408). VERIFIED. singletonKey+short collapses the self-chain to one queued hop; the sweep re-polls waiting rows (deduped against a live chain) and clears wedged claimed rows (at-most-once: the turn is never re-run — the chat-generation watchdog owns the composer). Test: colocated unit asserts the re-poll carries the per-send singletonKey; integration probe seeds a severed waiting + a wedged claimed (fresh of each spared).

3 — Answered-ask resume lost on restart (automations/reattach.ts:128). VERIFIED, scope narrowed on read: the resume handler self-settles the run on a throw (its catch), so only a worker death before the cursor retarget is a true dead-end. Because retargetAgentCursor is a FOR-UPDATE CAS, re-enqueuing ask_resume is idempotent (a completed resume no-ops) — so the waker re-enqueues rather than changing retryLimit (preserving at-most-once LLM spend). Test: colocated unit locks the re-enqueue payload; integration probe seeds an answered ask still parked on the asking exec and spares moved/pending/fresh.

4 — Task run stranded queued up to 12h (tasks/reattach.ts:66). VERIFIED. New sweep for queued + waiting_for_capacity_at_ms IS NULL + stale, past no deadline; CAS-rotates the exec (so a lost-but-slow start orphans itself via the exec-fenced setAgentRunRunning) and re-enqueues, or fails a run whose agent was deleted. Test: colocated unit (rotate + claim-lost branches); integration probe covers requeue, agent-gone fail, and fresh/parked untouched.

5 — Crashed backfill blocks all future backfills (object_storage/service.ts:356). VERIFIED. The handler settles failed on its own throw, so the dead-end is a process death leaving running forever; the sweep fails stale runs (updated_at_ms stamped per ~100-blob batch). Test: colocated unit locks the failed-flip + reason; integration probe proves a re-run is unblocked after recovery and a fresh run is left running.

6 — Steer-miss fallback always throws (core/tasks/agent_run_host.ts:1660). VERIFIED. One-line fix; the internal.* ref is a loose FunctionRef so the extra arg type-checks. Test: colocated unit drives steerTaskAgentTurnImpl over a settled run and asserts the fallback payload carries organizationId (red on base: expected undefined to be 'org_steer_fallback'); integration probe drives the real shim over a genuinely settled run — threw="" mentionRuns=1.

Refuted: none — all six are genuine dead-ends confirmed in code (charitable read). Excluded per brief: the transcription-status watchdog (fixed on a sibling branch) and the realtime-outbox unbounded-growth issue (a different class).

Tests added

  • 6 colocated vitest files (11 tests, server project, no DB): agent_run_host.steer_fallback.test.ts, reattach.queued.test.ts, reattach.ask.test.ts, service.backfill-watchdog.test.ts, deferred-sends.watchdog.test.ts, send.watchdog.test.ts.
  • 6 real-Postgres crash-recovery probes in integration-check.ts (checkSteerFallbackRecovery, checkQueuedRunRecovery, checkAnsweredAskRecovery, checkBackfillRecovery, checkDeferredSendRecovery, checkStuckSendRecovery) — each seeds the crash state (non-terminal row / lost job) and asserts the waker re-drives it or lands an honest failed state.

Gates observed

  • bunx tsc --noEmit → exit 0.
  • bunx oxlint --type-aware → exit 0; opengrep (pre-commit SAST) → 0 findings on every commit.
  • Colocated vitest (--project server): 11/11 pass on branch; 11/11 FAIL with the six source files reverted to base (each fix is load-bearing).
  • backend:integration on throwaway tale-db + MinIO (minioadmin): BASE (main-tip) 279/279, BRANCH 285/285. The +6 are this PR's probes — all green on branch, absent on base. (A transient object-store-boot fail was confirmed to be MinIO-container state carryover, not code; clean containers → 285/285.)

Cross-class discovery (not in scope here)

core/automations/stepper.ts:986 ("Crash between agent-node kick and cursor persist double-spends a turn") is a double-spend, not a strand — the automation-agent watchdog scans only status='waiting', so a crash between the kick and the cursor persist can re-enter stepAgentNode and spend a second turn. It's the same crash window as this class but the opposite failure mode (over-run, not dead-end); flagging for a follow-up.

Draft — do not merge.

The settled-run fallback kicks a fresh mention run through a shim handler that binds organizationId into SQL, but kickFallback never passed it, so postgres.js threw UNDEFINED_VALUE and the kick was lost (task.agent_steer has retryLimit 0). TurnKeys already carries it.
A start job lost before setAgentRunRunning leaves the run queued with no op row and no capacity stamp, invisible to the running-state re-attach, the parked wake, and the deadline sweep until the 12h wall. recoverStuckQueuedTaskAgentRuns re-kicks it under a rotated exec id (single-winner claim) or fails it when its agent was deleted.
A resume lost to a restart while the run parks on the asking exec is skipped by the awaiting_human exemption and strands to the 7-day ask deadline. recoverAnsweredAskResumes re-enqueues automation.ask_resume; the resume is idempotent (retargetAgentCursor is a FOR-UPDATE CAS on the asking exec), so a completed one no-ops.
A backfill whose process died mid-copy sat status=running forever, and the one-running partial unique index then rejected every future backfill (409). recoverStuckBackfills fails runs stale past the window; re-running is idempotent (already-copied blobs are skipped).
A poll self-chain that severs leaves the send waiting forever; a crash between claim and the finally-DELETE wedges it claimed (uncancellable). recoverStuckDeferredSends re-polls waiting rows (a per-send singletonKey + short policy dedups a live chain) and clears wedged claimed rows; the claim now stamps waiting_since_ms.
conversation.send_message has retryLimit 0, so a worker killed mid-send or a job expired past 600s left the reply queued forever with the retry/discard controls hidden (they need failed). recoverStuckConversationSends flips stale queued rows to failed with a reason. Migration 0065 adds status_changed_at_ms (a retry re-queues without touching created_at_ms) plus a partial index for the sweep.
Wire the crash-recovery sweeps into the job engine: new watchdog.conversation_sends, watchdog.deferred_sends, and watchdog.object_storage queues + crons; extend watchdog.task_agents and watchdog.automation_agents with the queued-run and answered-ask wakers; set chat.deferred_send_poll to the short policy so the per-send singletonKey dedups the poll chain. Adds a real-Postgres crash-recovery probe per lane to integration-check.ts (285/285).
@larryro
larryro marked this pull request as ready for review September 3, 2026 04:20
@larryro
larryro merged commit 49a922c into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/job-liveness-watchdogs branch September 3, 2026 04:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant