Skip to content

fix(jobs): report a failed job run to Sentry - #1050

Merged
Ardnived merged 3 commits into
mainfrom
claude/fix-report-failed-job-runs
Oct 30, 2026
Merged

Ardnived merged 3 commits into
mainfrom
claude/fix-report-failed-job-runs

Conversation

@Ardnived

@Ardnived Ardnived commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #1046: the owner asked for our own jobs' failures to be reported, in a separate PR.

Summary

  • A job run that fails for good now reaches Sentry, once, on its final attempt, tagged with its task and job id.
  • It covers all 13 of our tasks and Payload's schedulePublish, through fix(admin): a failed document write in the admin reaches no one #1046's handler wrap, generalised rather than duplicated.
  • A task can mark an expected failure (ExpectedJobFailure). It is still reported, but at warning. Seven cases are marked in importEvents and transcribeMeditation, two of them only outside production.

Change outline

Flow — every task's handler, wrapped once at onInit

 sentryPlugin onInit                                   src/plugins/sentry/sentryPlugin.ts
   installLocalApiCapture(payload)                     # unchanged: writes + jobs.queue
-  installScheduledPublishCapture(payload)             # schedulePublish only
+  installJobCapture(payload)                          src/plugins/sentry/jobCapture.ts
+    for each task in config.jobs.tasks                # read off the live config at run time
+      handler catch:
+        JobCancelledError                → rethrow, no report
+        not isFinalAttempt(task, job)    → rethrow, no report   # the runner will retry it
+        else → captureFailure({ source: 'job', job: { id, task },
+                                expected: error instanceof ExpectedJobFailure })   # → warning, not error
+               + target and user, for schedulePublish's input only
+        rethrow                                       # the runner records the job row as before

Behaviour — the final-attempt rule, read off the job the runner hands the handler

+isFinalAttempt(task, job)
+  job.taskSlug !== task.slug            → false    # a task inside a workflow: its retries are unseen
+  prior    = job.taskStatus[slug]['1'].totalTried ?? 0
+  attempts = task.retries (number) | task.retries.attempts | 0
+  prior >= attempts                                # handleTaskError's own rule for a single-task job

Behaviour — which failures a task marks as expected

+src/lib/jobs/expectedFailure.ts   class ExpectedJobFailure extends Error
 importEvents        src/plugins/eventImport/task.ts
+  import deleted while pending     → ExpectedJobFailure   # read before the try: nothing left to mark
+  target region gone               → ExpectedJobFailure
+  uploader no longer active        → ExpectedJobFailure
   geocoder down / not configured   → Error                # error, unchanged
 transcribeMeditation               src/jobs/TranscribeMeditation/TranscribeMeditation.ts
+  recording replaced mid-run       → ExpectedJobFailure
+  no speech (normalizer)           → ExpectedJobFailure   # src/collections/MeditationTranscripts/lemonfox.ts
+  no Lemonfox key / no public URL  → configGap:
+    isProductionDeployment()       →   Error              # a lost key or bucket URL alerts
+    preview, local                 →   ExpectedJobFailure
   unreadable body, vendor errors   → Error                # error, unchanged

Payload re-wraps any handler throw in a TaskError built from its message. So the job row, the import's error and the transcript's status read exactly as before; only the Sentry level changes.

Files

 src/plugins/sentry/
+├── jobCapture.ts          # installJobCapture, isFinalAttempt; the schedulePublish input helpers moved here
 ├── localApiCapture.ts     # the writes and jobs.queue only; imports the schedule helpers
 └── captureFailure.ts      # `job` source already; adds `task` and `job_id` tags

Preview

Nothing on a preview shows this change. It acts only when a job fails on its final attempt (see Manual verification). Railway may also build no preview for a PR whose base is not main.

Test results

  • Lean gate: ✓ lint, format, typecheck (src + tests), 234 unit files / 2977 cases
  • Targeted specs: ✓ sentry-admin-write-capture (23), admin-write-capture.int (4), meditation-transcription.int (37), event-imports.int (30), lemonfox-response (6), database-cast-errors, error-disclosure, manager-magic-link

Each rule was watched failing first, by removing it:

  • Report every attempt: the unit "final attempt" and "object retries" cases fail. So does the int case, which runs the real verifyEmbeds task (retries: 1) through the real runner twice: no event on the first run, one on the second.
  • Wrap schedulePublish only (fix(admin): a failed document write in the admin reaches no one #1046's behaviour): the three cases for our own tasks fail.
  • Report a cancelled job: the cancelled case fails.
  • Judge a workflow job: the workflow case fails.
  • Drop the input gate: "sends no input of any task but schedulePublish, even one shaped like it" fails.
  • Ignore the marker (expected: false): "still reports a failure the task marked as expected, at warning" fails.
  • The four marked throws back to a plain Error: the two transcription cases and the two import cases fail.
  • Delete the replaced-recording check: the transcription case completes instead of failing. Its key is set, so its vendor assertion counts.
  • Make a config gap always expected: both "outage in production" cases fail (key and URL).
  • Make it never expected: both "on a preview" cases fail, and so does the no-key case.
  • Judge production by NODE_ENV too (deploymentEnvironment()): both "local build with NODE_ENV=production" cases fail.
  • No speech back to a plain Error: the int case and the lemonfox-response unit case fail.
  • The deleted-import guard removed: the deleted case fails.

Manual verification

  1. On a scratch commit, make one of our tasks throw (e.g. verifyEmbeds). Queue it, then run it with POST /api/payload-jobs/run once more than its retries.
  2. With NEXT_PUBLIC_SENTRY_DSN set, confirm no event on the earlier attempts, and exactly one on the last: capture_source: job, task: verifyEmbeds, job_id: <id>.
  3. Confirm the job row still records the failure, as before.
  4. Revert the scratch commit.

Notes for reviewer

  • Scope: every task, ours and Payload's.
    • Every final failure of ours was unreported, and the handler wrap from fix(admin): a failed document write in the admin reaches no one #1046 already covers the mechanism.
    • The eventImport per-row refusals never throw, so they stay out. Its whole-import failures (target region gone, uploader inactive) are reported.
    • No double report: a job's writes carry no user, or a routed request when /api/payload-jobs/run started the job, so the Local API wrapper stands down inside a job.
  • Once per job. There is one exception: a manual runByID of a job that already failed for good runs it again and reports again, as the runner itself logs "max retries reached" again.
  • Limits, documented in docs/architecture.md. A failure the handler never sees is not reported:
    • a task answering { state: 'failed' } (none does)
    • a throw after the handler returns
    • a task no longer registered
    • a job a crash left processing
  • The exception message is sent as it is, as at every other capture site. DeliverSubmissions can carry a transport message that names a rejected recipient over SMTP. Production's Resend transport does not throw that way.
  • HMR: a dev reload() replaces the config without running onInit, so in dev the wrap lasts until the first reload. Production does not reload.

Local review

Pass on the owner's extra marks. No blockers. Adopted:

  • A deleted import still logged "could not be marked" at error, because failImport tried to mark the missing row. The job now reads the import before its try, and the case asserts nothing is logged.
  • Production now uses isProductionDeployment(), the repo's own predicate (Railway's name, never NODE_ENV, per docs/environment.md), instead of deploymentEnvironment(), which counted a local production build as production. A case pins it.
  • The task's JSDoc had become detached by configGap, and a comment still called no speech "a failed run like any other". Both fixed.
  • The production/preview matrix now stubs after the fixture, and also asserts the message and that the vendor is never called.

Kept as is: the normalizer throws ExpectedJobFailure itself. Its other caller is a seed script, where the class name changes nothing.

Pass on the expected-failure convention. No blockers. Behaviour was confirmed unchanged for every consumer except the Sentry level. Adopted:

  • The new transcription case had a false comment and a vacuous vendor assertion. It unset the key it didn't need. It now uses the spec's own takeAwayRecording helper, with the key set, and describes the real race (two parallel reads).
  • A comment classified "no speech" as an outage, which the owner never decided. It now says only that the task does not mark it.
  • The class's JSDoc was trimmed to its three facts, the src/AGENTS.md paragraph wrapped and given the importEvents path, and the architecture sentence order fixed.

Pass on the job capture. No blockers. Adopted:

  • The PII gate's test was vacuous: its input was {}. A schedulePublish-shaped input now goes to another task, and removing the gate fails it.
  • A deleted ⚠ line and its reason are restored: "No req is passed", and why the wrap must judge the final attempt itself (onFail gets no error).
  • "A job's writes carry no user" was incomplete: /api/payload-jobs/run makes it a routed request.
  • The manual re-run report is now documented, instead of claiming "once per job".
  • The { state: 'failed' } branch is dropped. No task returns it, and its synthetic Error would group every such task into one issue. It is listed as a limit instead.
  • Stale comments fixed: captureFailure.ts's capture sites, a misplaced comment in the int spec, and a duplicate JSDoc.

🤖 Generated with Claude Code

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1050 October 30, 2026 15:07 Destroyed
@railway-app

railway-app Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-1050 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Oct 30, 2026 at 5:37 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot

Copy link
Copy Markdown
Contributor

This PR is stacked on claude/fix-1039-report-admin-writes. Merge it into that branch, or retarget it to main: the loop does not work stacked PRs, so nothing runs here until then.

🤖 sydevs dispatcher

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1050 October 30, 2026 16:21 Destroyed
Ardnived added a commit that referenced this pull request Oct 30, 2026
…ted import as expected

The owner's decisions on #1050's expected failures:

- **A missing Lemonfox key, or a missing public R2 URL, is the
  deployment's gap.** It is expected on a preview or locally, where
  nothing configures them. In production it stays a plain `Error`, so a
  lost key or bucket URL still alerts. Production is the repo's own
  `isProductionDeployment()`, which reads Railway's environment name and
  never `NODE_ENV`, so a local production build counts as local.
- **Lemonfox returning no speech** is an answer about the recording
  (music, silence), already shown on its row: always expected.
- **An import deleted while it waited** is a manager's choice: always
  expected. The job now reads the import before its `try`, so a deleted
  row no longer reaches `failImport`. It used to try to mark the missing
  row and log "could not be marked" at error.

"Address lookup is not configured" stays at `error`, as the owner chose.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1050 October 30, 2026 17:03 Destroyed
Base automatically changed from claude/fix-1039-report-admin-writes to main October 30, 2026 17:28
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 30, 2026
@sydevs-bot

sydevs-bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

🤖 no session running

recent dispatches
  • 18:43Z resolve-conflicts · attempt 2 · session · done
  • 18:43Z resolve-conflicts · attempt 2 · session
  • 17:28Z resolve-conflicts · attempt 1 · session · timed out
  • 17:28Z resolve-conflicts · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Oct 30, 2026
Ardnived and others added 3 commits October 30, 2026 10:29
The job runner catches a task's throw, records it on the job row and a
log line, and tells no one. `CleanupCollections`, `CleanupOrphanedMedia`
and our other tasks therefore failed silently, as `schedulePublish` did
before #1046.

#1046's `schedulePublish` handler wrap becomes `installJobCapture`
(`src/plugins/sentry/jobCapture.ts`), which wraps every task in
`config.jobs.tasks`: ours and Payload's own. It reports with
`capture_source: job` and tags `task` and `job_id`.

- **Once per job, on its final attempt.** Payload has no final-failure
  hook that carries the error: `onFail` gets none and runs on every
  attempt. The handler does receive the job the runner hands it, whose
  `taskStatus` counts the task's prior tries. For a single-task job the
  runner retries task `'1'` until those reach the task's `retries`, so
  that comparison is the runner's own rule. A task run inside a workflow
  is not reported, since workflow retries also decide its last attempt
  and none is configured. A manual `runByID` of a job that already
  failed for good reports again.
- **A cancelled job is not reported.**
- **No input beyond what `schedulePublish` already sent.** Only its input
  adds a `target` and the scheduling manager.
- **No double report.** A job's own writes carry no user, or a routed
  request, so the Local API wrapper stands down inside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Some job failures are answers, not incidents: an import whose target
region was deleted or whose uploader left, or a transcript whose
recording was replaced mid-run or which has no Lemonfox key. Each is
already shown to whoever needs it, so reporting it at `error` alerts for
nothing.

`ExpectedJobFailure` (`src/lib/jobs/expectedFailure.ts`) is the
convention. A task throws it, with the message the job row should carry,
in place of an `Error`. The job capture still reports it, at `warning`,
so it stays visible without alerting anyone. Every other failure in
these tasks, such as the geocoder being down or Lemonfox returning no
speech, stays a plain `Error`, reported at `error`. Payload re-wraps any
handler throw in a `TaskError` built from its message, so the job row,
the import's error and the transcript's status read exactly as before.

`importEvents` marks its two cases, and `transcribeMeditation` its two.
The convention is documented in `src/AGENTS.md`'s jobs section and in
`docs/architecture.md`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ted import as expected

The owner's decisions on #1050's expected failures:

- **A missing Lemonfox key, or a missing public R2 URL, is the
  deployment's gap.** It is expected on a preview or locally, where
  nothing configures them. In production it stays a plain `Error`, so a
  lost key or bucket URL still alerts. Production is the repo's own
  `isProductionDeployment()`, which reads Railway's environment name and
  never `NODE_ENV`, so a local production build counts as local.
- **Lemonfox returning no speech** is an answer about the recording
  (music, silence), already shown on its row: always expected.
- **An import deleted while it waited** is a manager's choice: always
  expected. The job now reads the import before its `try`, so a deleted
  row no longer reaches `failImport`. It used to try to mark the missing
  row and log "could not be marked" at error.

"Address lookup is not configured" stays at `error`, as the owner chose.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Ardnived
Ardnived force-pushed the claude/fix-report-failed-job-runs branch from d837720 to ee9bd72 Compare October 30, 2026 17:34
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1050 October 30, 2026 17:34 Destroyed
@Ardnived
Ardnived merged commit 58f80a4 into main Oct 30, 2026
9 checks passed
@Ardnived
Ardnived deleted the claude/fix-report-failed-job-runs branch October 30, 2026 17:58
@sydevs-bot sydevs-bot moved this from Working to Done in SYDevelopers Technical Roadmap Oct 30, 2026
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 30, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 30, 2026
@Ardnived Ardnived removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 27, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1050 — ee9bd72d Deployed Oct 30, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

2 participants