Repository navigation
fix(platform): recover background jobs stranded on crash or restart - #3157
Merged
Merged
Conversation
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
marked this pull request as ready for review
September 3, 2026 04:20
This was referenced Sep 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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: 0with 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
task.agent_steerkickFallbackomittedorganizationId; the shim binds it into SQL → postgres.jsUNDEFINED_VALUE→ every settled-run fallback kick lost (retryLimit 0)args.organizationId(TurnKeys carries it)task.agent_turnsetAgentRunRunning→ runqueued, no op row, no capacity stamp → invisible to the running-state re-attach, the parked wake, and the deadline sweep for 12hrecoverStuckQueuedTaskAgentRuns: CAS-rotate the exec id (single-winner) + re-enqueuetask.agent_turn; fail immediately if the agent was deletedwatchdog.task_agents(2 min)automation.ask_resumeawaiting_humanexemption skips it → stranded to the 7-day ask deadlinerecoverAnsweredAskResumes: re-enqueueask_resume(idempotent —retargetAgentCursoris a FOR-UPDATE CAS on the asking exec; a throw self-settles)watchdog.automation_agents(2 min)object_storage.backfillstatus='running'forever → theobject_storage_backfill_one_runningpartial 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_pollwaitingforever; crash after the claim →claimedwedge (uncancellable tray chip)singletonKey+shortpolicy dedups the chain, so a blind re-poll only revives dead chains;recoverStuckDeferredSendsre-polls waiting rows and clears wedged claimed rows; the claim now stampswaiting_since_mswatchdog.deferred_sends(2 min, new)conversation.send_messagequeuedforever, retry/discard UI hidden (needsfailed)0065addsstatus_changed_at_ms+ a partial index;recoverStuckConversationSendsflips stale queued rows tofailedwith a reasonwatchdog.conversation_sends(5 min, new)Per-finding: fix · test · verification
1 — Outbound conversation reply stuck
queuedforever (send.ts:840 / tasks.ts:372). VERIFIED. The handler settlesfailedon its own throw, so the dead-end is specifically a lost/expired job leaving the rowqueuedwith no waker; a retry also re-queues without touchingcreated_at_ms, so no existing column dates the current queued state → migration0065addsstatus_changed_at_ms(stamped at insert/retry/sent/failed) + a partial index; the sweep flips stale queued →failedand 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 provesretrySendMessagere-opens it (fresh queued spared).2 — Deferred-send chain severs / claimed wedge (deferred-sends.ts:370 & :408). VERIFIED.
singletonKey+shortcollapses the self-chain to one queued hop; the sweep re-polls waiting rows (deduped against a live chain) and clears wedgedclaimedrows (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-sendsingletonKey; 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
retargetAgentCursoris a FOR-UPDATE CAS, re-enqueuingask_resumeis idempotent (a completed resume no-ops) — so the waker re-enqueues rather than changingretryLimit(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
queuedup to 12h (tasks/reattach.ts:66). VERIFIED. New sweep forqueued+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-fencedsetAgentRunRunning) 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
failedon its own throw, so the dead-end is a process death leavingrunningforever; the sweep fails stale runs (updated_at_msstamped 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 looseFunctionRefso the extra arg type-checks. Test: colocated unit drivessteerTaskAgentTurnImplover a settled run and asserts the fallback payload carriesorganizationId(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
serverproject, 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.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.--project server): 11/11 pass on branch; 11/11 FAIL with the six source files reverted to base (each fix is load-bearing).backend:integrationon throwawaytale-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 onlystatus='waiting', so a crash between the kick and the cursor persist can re-enterstepAgentNodeand 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.