Repository navigation
fix(jobs): recover rows left running by a lost job - #1122
Conversation
`cancelStaleJobs` ran only from `onInit`, so a container that died mid-job left its row `processing` until a boot more than `STALE_JOB_MS` later — and while it stood, `countRunnableOrActiveJobsForQueue` stopped that task's schedule queueing another. `RecoverLostJobs` runs the same sweep hourly on the `nightly` queue, and the boot call stays: Payload refuses to schedule a task that already has a row in flight, so a sweep lost to a restart can only be cleared from boot. Cancelling frees the queue but tells nobody, so the sweep also settles the documents those runs owned. A class import's status is written by the run, so a lost one left `imports` reading `pending` behind a page whose `status` no writer may set; `failInterruptedImports` marks it `failed` with a notice to upload the file again. `cancelStaleJobs` therefore answers the rows it asked to cancel, read before the cancel — so a run that landed in between is tolerated, which is why only a still-`pending` import is marked. `refreshImportStatus` now moves one way, `review` to `completed`. It runs after every Events write, so ExpireEvents unpublishing an expired class, or a community denial drafting one, reopened a finished import for work that is not import work. A transcript derives its status from the job row, so the cancel is its whole recovery — but two things beside it were wrong. `TRANSCRIPTION_STALL_MS` was the same 15 minutes as the `transcription` safety-net cron's interval, so a run that cron picked up read `stalled` while it worked and the retry deleted the row under it; it now clears that interval plus the vendor's 5-minute timeout. And the task matched its row by audio filename alone, so a run superseded by a retry of the same recording still wrote onto the new row — it matches on the row's own `job` instead. Closes #1117 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYpdixnUxff4s7qxc1
…e it Review pass over the branch. `recoverLostJobs` moves to `src/lib/jobs/`, beside `runQueueSoon`. It has two consumers — the task and `onInit` — which is the definition of cross-boundary code, and leaving it in the job folder made `payload.config.ts` the one module reaching into one. `failInterruptedImports` now goes through `failImport`, so an import's failure keeps a single writer, and reads the job's input through `isRecord` as `jobCapture` already does. `IMPORT_TASK` moves to `constants.ts`, which breaks the `finish` ↔ `task` cycle the first spelling created. `cancelStaleJobs` selects only what names a run's owner and says so in its return type. The transcription run compares its row's `job` without stringifying either side, as every other `extractID` caller does. A cancelled run carried no message, so a transcript the sweep ended read `failed` with nothing beside it; `transcriptJobError` now says it was interrupted. The three specs that age a job row share one fixture. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYpdixnUxff4s7qxc1
|
🚅 Deployed to the SahajCloud-pr-1122 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
CI's smoke lane failed on this head: `/api/health` carried no `commit` field, so `scripts/get-railway-preview-url.ts` could not establish which build the preview served and exited 1. That field arrived with #1082, which merged after this branch was cut — so Actions ran the new script from the PR's merge ref while Railway deployed a branch head that still answered without it. Merging the base is the whole fix: the preview now reports `RAILWAY_GIT_COMMIT_SHA`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXBtbiNHV6j2jaqPso
The address step attached `pr-1122.cloud-preview.sydevelopers.com`, then
gave up on it three minutes later:
reachability attempt 18: fetch failed
::error::... was attached but did not answer within 3 minutes
Nothing was wrong with the address. It answered 302 — the Access login
page, which is what `waitReachable` looks for — about six minutes after
the attach, once Cloudflare had provisioned its edge certificate. The
bound was simply under the vendor's real provisioning time, so the first
push of any PR opened after #1082 fails here while every later push on
the same PR passes, the certificate by then being issued.
Ten minutes clears the observed six with room, and costs nothing on the
happy path: the poll returns on the first answer, so only a genuinely
unreachable address waits longer.
The job's own `timeout-minutes` has to move with it. The attach lands
about twelve minutes into the job, so a ten-minute wait plus the fill
and smoke steps after it no longer fits in thirty — and a job that runs
out of time dies without the error that names the cause, which the loop
then reads as infrastructure and re-runs rather than repairs.
Unit, integration and both typechecks were already green on this head;
this is the smoke lane's address step alone.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjX8uXG55i6XoES9nNz
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff matches #1117 and stays its size: one sweep, three small fixes the ticket names, no abstraction for a caller that does not exist. recoverLostJobs earns its own module — payload.config.ts cannot reach into a job folder. The custom.recovery registry is rebutted with a count, which is the right reason to reject it. No cross-repo contract moves; the migration only adds an enum value.
Two things to settle. The hourly schedule shares its own queue's tick, so "hourly" is up to two hours in the worst case. And a CI fix rode in on the branch with no line in the body.
Findings
- should-fix —
RecoverLostJobs.ts:22: the schedule's cron equals thenightlytick, whichqueues.tswarns against. - should-fix —
ci.yml:26: the CI andpreview-domain.tstimeout changes appear in neither Summary nor Change outline. - consider —
finish.ts:123: stale, lost and interrupted are three words for one condition.
What was checked
- #1117 against the diff: every acceptance criterion has a named assertion. AC4 reverses an old test, deliberately, as the body says.
- Read whole on the branch:
PayloadJobs.ts,finish.ts,recoverLostJobs.ts,RecoverLostJobs.ts,TranscribeMeditation.ts,status.ts,queues.ts,queueTranscription.ts. - Ladder, per new piece:
recoverLostJobs(two callers),failInterruptedImports(plugin barrel, no registry),markJobLost(one test spelling),REQUEST_TIMEOUT_MS(exported so the spec derives the bound). findCurrentRow's newjobmatch:queueTranscriptionwritesjobin the caller's transaction, so the row names its job before any run starts.- Stall arithmetic rederived:
3-59/15gives a 15-minute worst gap, plus 300 s, so 30 min clears the 20-minute floor. - Preview: both links open — 302 to the gated host, then 200. Empty, as the body says.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`cancelStaleJobs` (stale), `recoverLostJobs` (lost) and `failInterruptedImports` (interrupted) gave one condition three words, so a reader could not tell whether they named different states. The routine's word is "lost"; "interrupted" now belongs to the visitor copy alone. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW2F9mME4aiHfNczBo
The ⚠ on `JOB_AUTO_RUN` read as though every schedule waits for a later tick, which made an hourly sweep on the hourly queue look two hours late. Payload's tick calls `handleSchedules` and then `jobs.run`, and `waitUntil` is the occurrence just passed, so an aligned schedule is queued and run by one tick. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW2F9mME4aiHfNczBo
|
Three critic threads, all settled. Pushed
Gate: lint, format, both typechecks, 264 unit files / 3550 tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Option B of the review thread on `recoverLostJobs`: the boot call goes, and the schedule's own `beforeSchedule` takes over the job it was there for. `defaultBeforeSchedule` counts a `processing` row as active, and this sweep is the only thing that ever settles one — so a sweep lost mid-run held its own schedule for ever, and boot was the only caller nothing blocked. The hook delegates to `defaultBeforeSchedule` first and only narrows its refusal: past `STALE_JOB_MS` a `processing` row stops counting as a blocker, and the run that then queues is what cancels it. A window says which rows are lost; a write is what recovers one. With one consumer left, the routine moves out of `src/lib/jobs/` and into the job folder, as rule 4 in `src/AGENTS.md` asks. It is `recover.ts` rather than `recoverLostJobs.ts` because TypeScript refuses two names in one folder that differ only in casing. The cost the reviewer accepts: recovery after a lost sweep now waits for the next hourly tick rather than for the next deploy. `retention-jobs.int.spec.ts` pins both halves of the gate, each watched failing — a run in flight still blocks its own schedule, and a run past the window no longer does. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjW5EiigVaLaqFuGeVg
|
One thread, built and resolved. Pushed 4740bdb.
Both halves of the gate were watched failing: with no hook a lost row still blocks the schedule, and with a hook that always schedules a run in flight stops blocking it.
The body named the boot call in its Summary, Change outline and Notes; all three are refreshed, with Test results. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
`recover.ts` earned its own module while `payload.config.ts`'s `onInit` was its second consumer. 4740bdb removed that call, so the task config beside it is the only one left, and a one-function file in the same folder now costs a hop for nothing. `RecordAtlasSnapshot.ts` is the shape followed: the routine is exported next to the task config, which is what the two int specs call. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXMwbQ5U3MKGMcVqpM
|
One thread, built and resolved. Pushed 234985f.
The two int specs that call the routine import it by the new path. No behaviour changed, so no assertion moved.
The body named the old file twice, in the Change outline and the Notes; both are refreshed. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Both sides raised `REACHABLE_TIMEOUT_MS` to 10 minutes independently, so only the `⚠` explaining it conflicted. Neither explanation was redundant: `main` (#1122) states why a single-minute bound fails every PR's first push and that `ci.yml`'s `timeout-minutes` is the ceiling; this branch carries the two measurements that proved it (2m32s and past 3m) and the #1129 breadcrumb. The merged comment keeps both, with the measurement folded into `main`'s sentence rather than restated beside it. The error title stays `infrastructure-failure`. That hunk is this branch's alone and merged clean — `main` still names the step, which is what the dispatcher reads as a repairable failure. `ci.yml` needed no resolution: both sides landed the same 40-minute job bound with the same note, so the merged file equals `main`'s. Lean gate on the merged tree: lint, format, both typechecks, 267 unit files / 3586 tests green. `tests/int/clients-preview.int.spec.ts` 5 passed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWT8MVvvSavx6X7TUW
`cancelStaleJobs` landing on `main` touched the transcription task this branch had already renamed, so four files conflicted. `TranscribeMeditation.ts` was deleted here and modified there. Its fix is ported into `TranscribeRecording`: the run now tells its own transcript row from a later request's by the row's `job`, not by `audioFilename`. That is strictly the stronger test on this branch — a corrected `?language=` deletes and re-creates the row while keeping the filename, which is the case the post-vendor id check was added for, and a job id moves on where a filename does not. The id check stays beside it. `file-transcripts.int.spec.ts` did not conflict but called the task with no job, so every case would have read `superseded`. Its `transcribe` helper now resolves the row's own run, as `main`'s meditation helper does. `src/migrations/index.ts` takes both branches' entries in timestamp order. `20261112_171546_merge_main_snapshot_11` is the heal for the out-of-order snapshot that leaves: its DDL is byte-identical to `20261111_182607_recover_lost_jobs_task`, already applied, so the statements are dropped and the snapshot kept — it is the first taken on the merged tree. `tests/COVERAGE.md` keeps this branch's wider table plus `main`'s `recoverLostJobs` row. `job-schedules.spec.ts` follows `REQUEST_TIMEOUT_MS` to `lemonfoxClient`. Verified: typecheck, typecheck:tests, format:check, eslint on every file touched. The integration lane is CI's. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWsvNRJpZkDUy5GgwB
Summary
processingby a dead container is now swept hourly by a task of its own, instead of only on the next boot — and the sweep settles the documents those runs owned. The schedule carries its ownbeforeSchedule, so a sweep lost mid-run no longer blocks the next one.Change outline
Flow — the sweep, what frees its schedule, and what it now tells
Cancelling frees the queue. It settles nothing a run was in the middle of writing, which is the half that left a volunteer's import reading
pendingfor ever.transcriptsneeds no branch there: its status is derived from the job row, so the cancel is the whole recovery. It only lacked the words —jobs.cancelwrites{ cancelled: true }and no message, sotranscriptJobErrornow says the run was interrupted rather than leavingfailedbare.Behaviour — an import only moves forward
refreshImportStatusruns after every Events write, so the lifecycle re-drafting an imported class — ExpireEvents expiring one, a community denial drafting one — reopened a finished import.Behaviour — which row a transcription run owns
A retry deletes the row and creates a new one for the same recording, so the filename cannot tell one request from the next. The row's own
jobcan.Contract — the bounds that decide a lost run
jobStage.staleAfterMsontranscriptsreads the raised bound, so the Edit view and the Transcript tab still go stale together — and a genuinely lost run now waits 30 minutes rather than 15 before the tab offers a retry.CI — the preview address the smoke lane waits for
Nothing was wrong with the address #1082's gate attaches; it answered 302 about six minutes later, once Cloudflare had provisioned the certificate. The bound was under the vendor's own provisioning time, so the first push of a PR failed and every later push on the same PR passed.
Preview
hasErrorwithprocessingclearedData: not seeded. This repo configures no
previewUrl.seed, and a fresh Railway preview carries one row — its admin. Both lists are empty until a reviewer uploads a CSV or queues the task, which is what the Manual verification steps below do.Migration
src/migrations/20261111_182607_recover_lost_jobs_task.tsrecoverLostJobstoenum_payload_jobs_task_slugandenum_payload_jobs_log_task_slug. No table, column or row changes.downrebuilds both enums without the value. Apayload_jobsrow already carrying it would fail the cast, so sweep those rows first.Test results
retention-jobs.int(8),event-imports.int+meditation-transcription.int(73)Every new assertion was watched failing against its defect before the fix went back: the stall bound at 15 min (
expected 900000 to be greater than 1200000), the import leftpendingwithout the settle step, the re-drafted class reopening acompletedimport, the superseded run readingcompletedinstead ofsuperseded, the cancelled transcript readingfailedwith no message, and both halves of the schedule gate — with nobeforeSchedulehook a lost row still blocks (expected [] to include 'recoverLostJobs'), and with one that always schedules a run in flight stops blocking (expected [ … ] to not include 'recoverLostJobs').Manual verification
cancelled: 0against a healthy database.payload_jobsrow toprocessingwith anupdated_atover an hour old. Run the task; the import should read Failed with "The import stopped before it finished running. Upload the file again.", and its page should open rather than sit behind the waiting view.Notes for reviewer
recoverLostJobsthread.defaultBeforeSchedulewill not queue a scheduled task while one of its own rows is runnable or active, and this sweep is the only thing that ever settles such a row, so a sweep lost mid-run held its own schedule for ever.scheduleUnlessRunningdelegates todefaultBeforeSchedulefirst and only narrows its refusal: pastSTALE_JOB_MSaprocessingrow stops counting as a blocker, and the run that then queues is what cancels it. The cost: recovery after a lost sweep now waits for the next hourly tick rather than for the next deploy.retention-jobs.int.spec.tspins both halves through Payload's ownhandleSchedules.RecoverLostJobs.tsitself, beside the task config that is now its only consumer — the shapeRecordAtlasSnapshot.tsalready uses. It had a file of its own whilepayload.config.tswas the second consumer; with the boot call gone, that file was a hop for nothing.recoverLostJobscomposes the two andeventImportdecides which cancelled rows are its own (one new barrel export). The alternative this review raised twice is a declarativecustom.recoverythe waycustom.retentionworks — rejected here because retention has four declaring collections and this has one, so the registry would be a layer with a single consumer. The deeper alternative, derivingimports.statusoff the job row the waytranscriptsdoes, is a larger change to a stored column that four writers,defaultColumnsand aJobStageViewgate already read. Both are yours to call.jobs.cancelreturns nothing. A run that lands in between is tolerated by only touching a still-pendingimport;event-imports.int.spec.tspins that case.refreshImportStatuslosing its backward direction is a behaviour change the old two-way test covered. That test now asserts the opposite, deliberately — it is acceptance criterion 4.nightlyqueue, and its cron is that queue's own minute on purpose. AnautoRunentry of its own would need a staggered minute, and the alignment costs nothing: Payload's tick callshandleSchedulesand thenjobs.run, andwaitUntilis the occurrence that tick has just passed, so one tick both queues the sweep and runs it.queues.tssaid otherwise and now says this.runClockthrough the sweep (no production caller variesnow, and the window is already pinned from both sides by a fresh row and an aged one); a bulkupdatebywherein place of the per-import loop (it would fork the import-failure write away fromfailImport, and N is 0–1 on an hourly job).Detail
Why the gate counts rather than cancels. The hook could sweep the lost rows itself and let
defaultBeforeSchedulesee them settled, but that puts the recovery write in a hook that runs on every tick and leaves the task with nothing to do. A window says which rows are lost; a write is what recovers one — so the hook reads, and the run it lets through writes. It also delegates todefaultBeforeSchedulebefore counting anything, so that function stays the authority on every other reason not to queue, and its blocker set is mirrored rather than replaced.Why 30 minutes. The transcript row's
updatedAtis stamped when the recording is asked for, not when the run starts. Thetranscriptionqueue's cron (3-59/15) is the safety net for a kick lost to a restart, so the worst-case start delay is one tick; the vendor call is then bounded by Lemonfox's 5-minute request timeout. 20 minutes is the floor, 30 leaves room for the glossary pass and the write.job-schedules.spec.tsderives the floor from the cron andREQUEST_TIMEOUT_MSrather than restating it, so tightening either fails the spec. The cost is that a user-facing wait is now coupled to that cron's interval; the deeper fix — derivingstalledfrom the job row's own pick-up time rather than the request's — is a change to a client-side seam and is not in this ticket.docs/rules/admin-ui.mdwas wrong about the retry. It said ajobStagewindow opening is the retry, "setting the status column back to its queued value".importsclosesstatusto every writer, so that window opened a page with no retry on it. The rule now names both ways a row gets settled and says to check which one a collection has.Rejected: a hook on the cancel.
jobs.runHooksis not configured, andpayloadJobsOverridesrecords why adding one is not a small change — Payload warns and the hook never runs. The sweep tells the owner directly instead.Rejected: bounding the sweep's read.
cancelStaleJobsreads withpagination: false, now with aselectdown toinputandtaskSlug. The set is rows a dead container left behind, bounded in practice by the worker concurrency of the containers that died, and every row it finds is one the same call then cancels.IMPORT_TASKmoved toconstants.ts. Reading the slug off a cancelled job row putfinish.tsandtask.tsin an import cycle; the constant now sits where neither has to reach the other.Closes #1117