Skip to content

fix(admin): a failed document write in the admin reaches no one - #1046

Merged
Ardnived merged 13 commits into
mainfrom
claude/fix-1039-report-admin-writes
Oct 30, 2026
Merged

Ardnived merged 13 commits into
mainfrom
claude/fix-1039-report-admin-writes

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A Local API write the admin makes — while a page renders, or inside a server function — now sends one error-level Sentry event when it fails, naming the collection, the failing field and the acting manager.
  • Both report sites share one capture body, so a new one cannot re-report what mapPostgresCastError deliberately drops.
  • The magic-link endpoint swallows the same sign-in failure the page does, so it reports it too (from review).
  • Joined, not listed: a root error with no collection set the collection tag to the string "undefined"; docs/rules/email.md claimed the plugin hooks afterError alone.

Change outline

Flow — where a failed admin write goes

The two paths the ticket names are caught inside node_modules, so neither reaches afterError or onRequestError. The Local API call is the seam that sees both.

 RootPage → DocumentView                      @payloadcms/next/.../views/Document/index.js
   payload.create({ data, draft: true, req, user })   # autosave create-on-open, `pages` only
+    captured: collection, failing field, acting manager
   catch → logError({ err, payload })         # ValidationError logs at `info`
   return undefined                           # 200, admin chrome, empty body

 serverFunction → handleServerFunctions → schedulePublishHandler
   payload.delete({ collection: 'payload-jobs', req })      # the cancel branch
+    captured
   payload.jobs.queue({ input, task, waitUntil })           # NO req — see below
+    captured, manager read off `input.user`
   catch → payload.logger.error({ err }, msg)
   return { error }                            # a toast, and nothing else

 requestSignInLinkAction                      src/components/admin/SignIn/actions.ts
   catch → payload.logger.error(…)
+    captured: no acting manager exists here by design
   return SENT                                 # the uniform answer, either way

Behaviour — the two gates, read off Payload's own request

 reportWrite(error, options)                   src/plugins/sentry/localApiCapture.ts
+  req.payloadAPI !== 'local'  → stand down
+    # createPayloadRequest stamps REST/GraphQL; createLocalReq PRESERVES it,
+    # so a hook's write during a request reads as routed and afterError owns it
+    # initReq (page render, every server function) goes through createLocalReq → 'local'
+  no req.user                 → stand down
+    # a job, a seed, a script; and eventImport, which passes `user` with no req
+  else                        → captureFailure({ level: 'error', source: 'localApi' })

 reportQueue(error, options)                   # jobs.queue answers neither gate
+  a routed request owns it    → stand down
+  else                        → captureFailure({ collection: 'payload-jobs', user: input.user })

Files — one capture body, every reporting site

 src/plugins/sentry/
+├── captureFailure.ts        # the exclusions, the tags, the levelling — extracted from the hook
 ├── sentryPlugin.ts          # the afterError hook, now a caller; installs both wrappers at onInit
+├── localApiCapture.ts       # wraps create/update/updateGlobal/delete/duplicate + jobs.queue,
+│                            #   and schedulePublish's job handler
 │                            # also called by SignIn/actions.ts and login/endpoints/requestMagicLink.ts
 ├── credentialRejection.ts   # unchanged
 └── authAttempt.ts           # unchanged

Flow — the publish a scheduled job runs

The publish fails inside Payload's job runner, which records it on the job row and in a log line alone. Its payload.update carries no request, so the write wrapper stands down for it.

 sentryPlugin onInit                                 src/plugins/sentry/sentryPlugin.ts
   installLocalApiCapture(payload)                   # the writes, plus jobs.queue (now tagged `target`)
+  installScheduledPublishCapture(payload)           src/plugins/sentry/localApiCapture.ts
+    config.jobs.tasks['schedulePublish'].handler    # the runner reads it off the live config at run time
+      catch → captureFailure({ source: 'job', collection, target: 'pages/12', user: input.user })
+              # no req: the runner's carries the default locale, and on /api/payload-jobs/run the triggering admin
+      rethrow                                       # the runner still records the job row as before

Preview

Neither link needs seeded data: the first creates its own draft on open, and the second is a sign-in form. The change itself is invisible until a write fails — that is what the Manual verification below is for.

Data: nothing to seed for these two. previewUrl.seed is unset for this repo, so a link needing content would say so here.

Test results

  • Lean gate: ✓ lint, format, typecheck (src + tests), 234 unit files / 2967 cases
  • Targeted specs: ✓ admin-write-capture.int, database-cast-errors.int, error-disclosure.int (11 passed), sentry-admin-write-capture, sentry-credential-rejected, sentry-auth-attempt (35 passed)
  • Build: N/A — CI and Railway build it

Every new assertion was watched failing against its own defect first: the capture site removed, each gate removed, the dedupe removed, the field-path extraction removed, and the queue reporter swapped for the write reporter.

Manual verification

The swallow needs an injected throw to reproduce, so it cannot be a spec. On the preview:

  1. On a scratch commit, add a beforeChange hook to pages that throws. Not versions.drafts.validate — that skips the create-on-open outright.
  2. Open /admin/collections/pages/create. Confirm the 200 with admin chrome and no body — that is the defect.
  3. With NEXT_PUBLIC_SENTRY_DSN set, confirm exactly one event in sahajcloud, at error, tagged collection: pages and capture_source: localApi, carrying the acting manager and a fields extra.
  4. Schedule a publish on a pages document with the same injected throw. Queuing it succeeds; the throw comes when the job runs at the scheduled time, or run it at once with POST /api/payload-jobs/run. Confirm the job row records the failure and one event arrives, at error, tagged capture_source: job, collection: pages and target: pages/<id>, naming the manager who scheduled it, not whoever triggered the run.
  5. Revert the scratch commit.
  6. Confirm an ordinary REST validation failure (Save with a required field empty) still produces exactly one event, from afterError.

Notes for reviewer

  • Only schedulePublish's handler is wrapped, not every job. Payload has no final-failure hook that carries the error: onFail gets none and runs on every attempt. So a handler wrapper reports once per attempt, and schedulePublish, with no retries, is one event per job.
    • Some of our own tasks also fail unreported: CleanupCollections and CleanupOrphanedMedia log and rethrow. That is out of this PR's scope.
    • A dev HMR reload swaps in a fresh config without running onInit, so in dev the job wrap lasts until the first reload. Production does not reload.
  • Two limits, accepted and documented in docs/architecture.md:
    • The cancel branch of schedulePublishHandler is a bulk payload.delete({ where }). It answers a per-document failure in result.errors rather than throwing, so the wrapper never sees it.
    • A nested write that a hook catches and recovers from can still send an error event: resolveClipParent's lost create race, upsertUserByEmail's duplicate.
  • Tags now drop null and '', as the code before the slim-down did, without the cast that hid it.

The route stamp the ticket recommended is gone, and so is the generated-file edit. The first version built an AsyncLocalStorage flag set by src/app/(payload)/api/[...slug]/route.ts, exactly as the Approach describes. Payload already answers the question: createLocalReq preserves a REST/GraphQL stamp into a nested Local API call. Reading req.payloadAPI removed the module, the deviation in a file carrying Payload's "DO NOT MODIFY" banner, and the hazard that regenerating it would make every REST 400 report twice. It also removed a leak the flag had — runQueueSoon fires a job run from a setTimeout inside a request, and async context follows it there.

The config.logger seam was considered and not taken, and docs/architecture.md now says so rather than implying the Local API was the only option. Both swallow sites do log, and config.logger is ours — but the log record carries no req, so the collection and the acting manager that criteria 1 and 2 ask for are both lost, and it would additionally need loggingLevels: { ValidationError: 'error' } to keep the error object at all.

One open question is a thread on the diff — a third swallow site of the same shape, in ListView.

Dismissed review findings:

  • Share the @sentry/nextjs stub across the four specs that now have it. Not done: vi.mock's factory is hoisted above imports, so a shared module needs a top-level-await vi.hoisted dance that costs more clarity than the 15 duplicated lines, and it would edit two specs this PR does not otherwise touch.
  • Move captureErrors / debug into the shared body, keyed on source. Not done: those are the hook's policy about which routed statuses are worth reporting. A swallowed write has no "ordinary" case to filter, so keying the filter on its caller would put the hook's knob in the shared body without giving the other sites one.
  • Guard installLocalApiCapture against a second call. Not done: getPayload sets disableOnInit for a cached instance and dev HMR goes through reload(), which does not re-run onInit, so nothing stacks today.
  • Read data.errors[].path through a structural walk rather than a runtime instanceof. Replaced with validationFieldErrors, which does ask instanceof — the integration spec pins that it still finds the paths through a real payload.create.
Detail

Why jobs.queue needs its own rule. schedulePublishHandler passes it only input, task and waitUntil. With an acting-user gate it reported nothing, while the payload.delete cancel branch beside it — which does pass a request — looked covered. The first version of the spec handed jobs.queue a request no real caller sends, which is what kept the gap green; the spec now calls both halves the way their callers do.

Why the acting-user gate asks for the user on req, not on either. src/plugins/eventImport/task.ts passes user: run.uploader with no request, inside a try that records a human-readable skipped row — a refused CSV row is that feature's normal path. On the looser gate, a 200-row import with 50 bad rows sent 50 error-level events for a failure already reported to the uploader.

Fixture pre-mortem. The unit spec's ValidationError assumes data.errors[].path carries a field name and that payloadAPI survives a Local API call. Both are assumptions about node_modules, so tests/int/admin-write-capture.int.spec.ts settles them against a real failed payload.create on pages — verified against src/collections/Pages/Pages.ts, whose one required field is title, and payload/dist/utilities/createLocalReq.js.

Security review skipped. No file in the branch diff matches securityReview.triggerPattern, and this repo sets no contentPattern. The generated API route matched in an earlier revision; that edit is gone.

What stayed out of the capture body. reportRejectedCredential still has its own withScope block. It captures a message rather than an exception, deliberately, because its denial never throws — folding it in would mean teaching captureFailure a second capture shape for no new coverage.

Closes #1039

Slimmed down after review

Requested in review: captureFailure.ts went from 225 to about 117 lines, and localApiCapture.ts from 138 to about 80. Nothing that reaches Sentry changes.

  • The context plugin option is gone, along with SentryContext and SentryContextFn. Its only caller, in payload.config.ts, restated the default locale tag.
  • Sentry.captureException(error, { level, user, tags, extra, fingerprint }) replaces the hand-built withScope plus scope.set*. Specs read the capture context instead.
  • The level argument is gone. source: 'localApi' alone means error.
  • One reporter replaces reportWrite and reportQueue, and a .bind loop replaces the capturing<> generic.
  • Proof:
    • Each gate was broken on purpose (the localApi level, the jobs-row tag, the routed check, the queued-user check, the rejected-credential tags), and each time a spec failed.
    • admin-write-capture and manager-signin-page int specs pass, and the lean gate passes.
    • A fresh critic pass found one narrowing: a queue with no req whose input names nobody. It was reported before; the first cut dropped it. That rule is restored and pinned with a new spec, proven red then green. Two comment facts the cut had lost are back (the jobs.depth/runHooks condition, and the requireActiveClient gap at chore(sentry): a rejected key on a custom endpoint is still invisible #743).

Local review

A fresh critic pass on the scheduled-publish change found no blockers. Adopted:

  • The job event carried the runner's request, so it had the default locale, a placeholder URL, and on /api/payload-jobs/run the triggering admin as its user. It now passes no request, and a spec pins that the scheduler is named.
  • The stated reason for wrapping only schedulePublish was false. It is now the real one: no hook carries the error, so a wrapper reports per attempt.
  • The wrap moved to its own installScheduledPublishCapture, since it is no Local API write.
  • The HMR caveat and the softened "can still send" wording are in the docs.

Not adopted:

  • Dropping the global arm of the target tag, which no collection reaches today. The request listed globals, and it costs one line.
  • Moving the wrap into a post-sanitize config transform to survive HMR: a dev-only gap, stated instead.

Proof:

  • Against 2e009c01, the job, queue-target and tag-drop unit cases fail, and so does the int case, which runs a real schedulePublish job for an untitled page.
  • Passing the runner's req again fails the "names who scheduled it" case.
  • Specs pass: sentry-admin-write-capture (18), admin-write-capture.int (3), database-cast-errors, error-disclosure, manager-magic-link and manager-signin-page.
  • Lean gate: 234 files / 2972 tests.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq

A second capture site is coming for the admin writes `afterError` never
sees, and the exclusions it must not drop live inside the hook: the
`mapPostgresCastError` suppression and the rejected-credential levelling.
Both move to `captureFailure`, which both sites now call, so a new site
cannot re-report what the old one deliberately drops.

Two behaviour notes. The helper never throws, because its new callers run
on a failure path where a telemetry error would replace the failure the
caller is handling. And a `capture_source` tag now says which seam
reported, since a routed failure and a swallowed one can carry the same
error class.

One defect fixed on the way: a root error with no collection set the
`collection` tag to the string "undefined", because `String(undefined)` is
truthy and the hook read `'collection' in args` rather than the value.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
A write the admin makes through the Local API — while a page renders, or
inside an admin server function — was reported nowhere. `DocumentView`
catches the render, hands the error to Payload's `logError` and returns
`undefined`, so the page answers 200 with the admin chrome and an empty
body; `schedulePublishHandler` catches the same way and returns
`{ error }` to the UI. Payload logs a `ValidationError` at `info` by
default, so neither leaves a line that reads as an incident, and nothing
escapes the render for `onRequestError`. #1038 — nobody could create a
Page at all — stood four months behind that.

Both failures are caught inside `node_modules`, upstream of any component
we can supply, so the Local API call itself is the only seam left.
`installLocalApiCapture` wraps every write on the live instance from the
plugin's `onInit`, and rethrows untouched. Two gates keep it to the writes
the admin makes: a request Payload itself routed is excluded, because
`afterError` is about to report it and our own hooks write through the
Local API while one is in flight; and a write with no acting user is
excluded, which is every job, seed and operator script.

That first gate is a flag the generated REST route sets, read through
Node's async context — lexical, never inferred from timing. Editing a
generated file is the cost; a comment there carries it, and the sign-in
action reports from its own catch because its answer is uniform by design
and it has no acting manager to name.

Closes #1039

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
The unit spec covers the wiring: that the Local API is wrapped at all,
that the wrapper rethrows, that it stands down inside a Payload route and
on a write with no acting user, that one error instance reports once, and
that `mapPostgresCastError` still drops a cast failure on the new site.
Each case was watched failing against its own defect first.

The integration spec settles what a stub cannot. The unit fixture assumes
`data.errors[].path` is where a field name lives, and a fixture wrong
about that shape passes while production reports no field at all — so one
real failed `payload.create` on `pages` pins the paths and the 400.

PERF.md records this session's lane figures, as its own row.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
The story behind the second capture site: which two paths reach it, why
`afterError` and `onRequestError` both miss them, why `jobs.queue` needs
its own wrapper, and why the field paths rather than the message. Also the
warning that re-running Payload's generator drops the route wrapper, after
which an ordinary REST 400 reports twice.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
`perf-figures-pinned` holds three docs to PERF.md's counts, and the new
spec moves the lane to 234 files / 2963 tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
`docs/rules/email.md` said the plugin hooks `afterError` alone, which is
why a non-throwing send must report itself. The reason survives — both
sites need a throw — but the claim no longer did.

`tests/COVERAGE.md` gains the row for the new specs.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
Per the /simplify pass over the branch:

- `validationFieldErrors` replaces the hand-rolled walk of
  `error.data.errors[].path`. It asks `instanceof ValidationError` and reads
  Payload's own field-error type, so this stops being a fourth site encoding
  that payload's shape.
- `isRecord` replaces three fresh copies of its own guard.
- `errorStatus` gives the status derivation one home; the hook's own gate and
  the Local API site now read the same function, and the latter stops passing
  a status at all.
- `eventLevel`, `fingerprint` and `clientIp` were mutable locals carrying
  values out of the `rejected` block while `rejected` itself stayed in scope.
  All three are now derived once.
- `describeRejectedCredential` is asked only on the hook's own path, which is
  the only one that can see a rejected credential — the other two sites hold
  an acting user or carry no request. The `source` literal it takes was
  already right, and now it is visibly right.
- The `collection` tag reads `args.collection?.slug` directly. Both guards
  around it were no-ops on `AfterErrorHookArgs`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
The first version built an AsyncLocalStorage flag, set by the generated REST
route, to answer "did a route ask for this write?". Payload already answers
it: `createPayloadRequest` stamps a routed request `REST` or `GraphQL`, and
`createLocalReq` preserves that stamp into a nested Local API call — exactly
the case the flag existed for. The admin page render and every admin server
function build their request through `initReq`, so both read `local`.

Reading the property instead removes the whole mechanism: the module, the
permanent deviation in a file carrying Payload's "DO NOT MODIFY" banner, and
the hazard that regenerating it would make every REST 400 report twice. It
also removes a leak the flag had: `runQueueSoon` fires a job run from a
`setTimeout` inside a request, and async context follows it there, so a job
kicked from a route read as routed for its whole life while the same run
started by `autoRun` did not.

The acting-user gate now asks for the user on `req` rather than on either.
`eventImport`'s task passes a `user` option with no request, and a refused
CSV row is its normal path — reported to the uploader already. Under the
looser gate a 200-row import with 50 bad rows sent 50 error-level events.

The integration spec pins the preservation against a real `payload.create`,
since nothing in this repo sets `payloadAPI` and only a real write can show
the gate still holds after a Payload bump. The architecture section now also
records why the `config.logger` seam was not taken: both swallow sites do log,
but the log record carries no `req`, so the collection and the acting manager
that criteria 1 and 2 ask for are both lost there.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
`schedulePublishHandler` hands `payload.jobs.queue` only `input`, `task` and
`waitUntil` — no `req`. So the acting-user gate covered nothing on the path
the ticket names, while the `payload.delete` cancel branch beside it, which
does pass a request, looked covered and made the gap green. The unit spec was
handing `jobs.queue` a request no real caller sends, which is what hid it.

`jobs.queue` now reports under its own rule: no routed request owns the
failure. A failed queue is told to nobody else — the handler logs it and hands
the UI a toast — and it has no collection and no request to gate on. The
acting manager comes from the queued input, which is where `schedulePublish`
records who asked, through a new optional `user` on `captureFailure` for a
site that knows who acted but holds no request.

The spec now calls both halves the way their real callers do, and a third case
pins that a queue a routed request owns still stands down.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVV5QxGrfxP8A6eeQq
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1046 October 28, 2026 17:28 Destroyed
@railway-app

railway-app Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

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

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

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

1 question for the reviewer, one per thread.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/plugins/sentry/localApiCapture.ts Resolved
@sydevs-bot

sydevs-bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 20:03Z review-pr · attempt 2 · session · done
  • 20:03Z review-pr · attempt 2 · session
  • 14:36Z review-pr · attempt 1 · session · timed out
  • 14:36Z review-pr · attempt 1 · session
  • 07:27Z review-pr · attempt 2 · session · done

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

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 28, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Oct 28, 2026
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 28, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A mention (@sydevs-bot) or a push from you starts me again.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Oct 29, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 29, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Oct 29, 2026
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 29, 2026
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 29, 2026
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A mention (@sydevs-bot) or a push from you starts me again.

🤖 sydevs dispatcher

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 29, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Oct 29, 2026
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 29, 2026
- Drop the `reported` WeakSet: `@sentry/core` already marks a captured
  exception `__sentry_captured__` and drops a repeat, which also covers the
  `onRequestError` path the set never saw.
- A `jobs.queue` that carries a request answers the write gates, so a job or
  a cron tick queuing with a userless local request stands down. Only
  `schedulePublishHandler`'s request-less queue reads the manager off input.
- The magic-link endpoint swallows the same failure as the sign-in page, so
  it reports it too; both sites now have a case that fails without them.
- Drop an unused type re-export and a history line from the header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1046 October 29, 2026 22:11 Destroyed
@Ardnived

Ardnived commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Adversarial review, run locally (the dispatched critic never finished). Adopted in 63570fe7:

  • Dropped the reported WeakSet. @sentry/core 10.76.2 already drops a repeat capture of one exception (checkOrSetAlreadyCaught, client.js:139), which also covers the onRequestError path the set never saw.
  • jobs.queue with a request answers the write gates. A job (ScreenSubmissions queues with its own req) or a cron tick (handleSchedules uses a userless local request) no longer reports at error on each retry. Only schedulePublishHandler's request-less queue reads the manager from input.
  • The request-magic-link endpoint reports its swallowed failure too. It shares issueMagicLink with the page and answers 202 from its own catch, so afterError never sees it. Both sites now have a case in manager-signin-page.int.spec.ts, each watched to fail with its capture removed (criterion 6).
  • An unused type re-export and a history line removed.

Noted, not built: a database failure inside issueMagicLink can carry the typed address in its message. A routed 500 already accepts that exposure, and the comment says so.

Lean gate green; admin-write-capture, manager-signin-page and the unit spec run locally.

@Ardnived
Ardnived marked this pull request as ready for review October 29, 2026 22:11
@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

Copy link
Copy Markdown
Contributor Author

The session for this item did not finish after 3 attempts. I have stopped retrying. A mention (@sydevs-bot) or a push from you starts me again.

🤖 sydevs dispatcher

Drop the plugin's `context` option, whose one caller restated the default
locale tag, and with it SentryContext/SentryContextFn. Hand the SDK its
capture context directly instead of building a scope by hand. Merge the
write and queue reporters, and wrap the operations with one bind loop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1046 October 30, 2026 01:41 Destroyed
Ardnived added a commit that referenced this pull request Oct 30, 2026
…nyway

Every list render that changes a viewer's columns, sort or limit saves
them through Payload's `upsertPreferences`, which writes
`payload-preferences` with `user: req.user` and no `req`. `ListView`
swallows a throw there with a bare `console.error` and renders a blank
list. The capture's gate asked for the user on `req`, so it excluded the
write.

- **Reported.** A `user` option with no request now counts when access is
  left overridden, so the user only attributes the write. A caller that
  names a user with `overrideAccess: false` acts as them and owns their
  refusals, so `eventImport` and Payload's scheduled-publish job stay out
  exactly as before. The rule turns on the call's shape, not the
  collection.
- **Non-fatal.** Once reported, that one shape answers with the document
  it was given, which is all `upsertPreferences` reads back (`.value`),
  so the list renders with the incoming preferences, unsaved. The bind
  loop's catch absorbs only a reported `create` or by-id `update` on
  `payload-preferences` with no request. Everything else still rethrows.

The eventImport case in the unit spec now sends the shape
`src/plugins/eventImport/task.ts` really sends, `overrideAccess: false`
included. The integration spec drives the real `upsertPreferences` into
a failing write, so a Payload release that changes its call shape fails
a test instead of reopening the gap.

Follow-up to #1046 (review thread decision A).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ardnived and others added 2 commits October 29, 2026 21:33
Review findings on the slimmed capture:

- **A scheduled publish could fail without telling anyone.** Payload's
  own `schedulePublish` task calls `payload.update` with no request, so
  the write wrapper stands down, and the job runner records the throw on
  the job row and a log line alone. `installLocalApiCapture` now also
  wraps that one task's handler, which the runner reads off the live
  config at run time. It reports with `capture_source: job`, the
  target's collection, a `target` tag and the scheduling manager. Only
  `schedulePublish` is wrapped: our own tasks report themselves, or
  record expected failures for a person.
- **A failed queue is tagged with the schedule's `target`** (`pages/12`,
  or a global's slug), so failing schedules do not share one blind
  `payload-jobs` issue.
- **Tags drop `null` and `''`**, as the code before the slim-down did,
  without the `Record<string, string>` cast that hid it.
- **Docs and comments now count both sign-in callers**, the action and
  the magic-link endpoint. They also state two accepted limits: the bulk
  cancel `delete` reports per-document errors without throwing, and a
  nested write a hook recovers from still sends an event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…wrapped

Critic findings on the job capture:

- **The wrong request.** The capture passed the runner's request, which
  carries the default locale and a placeholder URL. On
  `/api/payload-jobs/run` that request is the admin who triggered the
  run, so the event named them, not the scheduler. It now passes none,
  and the user comes from the queued input.
- **The wrong reason for the scope.** The stated reason for wrapping
  only `schedulePublish` was false: some of our own tasks also fail
  unreported. The real reason is that Payload has no final-failure hook
  that carries the error, so a handler wrapper reports once per attempt.
  `schedulePublish`, with no `retries`, is the one task where that is
  one event per job.
- **The wrap gets its own installer,** `installScheduledPublishCapture`,
  since it is no Local API write. The docs note that a dev HMR reload
  drops it, and that a recovered nested write "can" send an event rather
  than always does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1046 October 30, 2026 04:45 Destroyed
Ardnived added a commit that referenced this pull request Oct 30, 2026
…anyway

Every list render that changes a viewer's columns, sort or limit saves
them through Payload's `upsertPreferences`, which writes
`payload-preferences` with `user: req.user` and no `req`. `ListView`
swallows a throw there with a bare `console.error` and renders a blank
list, and the capture's gate excluded the write.

One predicate, `preferencesUpsert`, now matches that exact call: a
`payload-preferences` create or by-id update whose options are exactly
the keys `upsertPreferences` passes, with `depth: 0` and
`disableTransaction: true`. That means no `req`, no `where`, and access
left overridden. It decides both halves of the change:

- **Report.** The call is reported without a request. The admission is
  on `payload-preferences` alone, so no other collection's `user`-only
  write is widened in, and `eventImport` stays out as before.
- **Absorb.** Once reported, the failure answers with the document the
  call was given, which is all `upsertPreferences` reads back (`.value`).
  Its five callers, the folder views included, read only that value, so
  the list renders with the incoming preferences, unsaved. A failure
  `captureFailure` drops is not reported and still throws, as does every
  other.

The integration spec drives the real `upsertPreferences` into a failing
create and a failing update, so a Payload release that changes either
call fails a test instead of reopening the gap.

Follow-up to #1046 (review thread decision A).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Ardnived
Ardnived disabled auto-merge October 30, 2026 17:28
@Ardnived
Ardnived merged commit f763961 into main Oct 30, 2026
9 checks passed
@Ardnived
Ardnived deleted the claude/fix-1039-report-admin-writes branch October 30, 2026 17:28
@sydevs-bot sydevs-bot moved this from Awaiting to Done in SYDevelopers Technical Roadmap Oct 30, 2026
Ardnived added a commit that referenced this pull request Oct 30, 2026
…anyway

Every list render that changes a viewer's columns, sort or limit saves
them through Payload's `upsertPreferences`, which writes
`payload-preferences` with `user: req.user` and no `req`. `ListView`
swallows a throw there with a bare `console.error` and renders a blank
list, and the capture's gate excluded the write.

One predicate, `preferencesUpsert`, now matches that exact call: a
`payload-preferences` create or by-id update whose options are exactly
the keys `upsertPreferences` passes, with `depth: 0` and
`disableTransaction: true`. That means no `req`, no `where`, and access
left overridden. It decides both halves of the change:

- **Report.** The call is reported without a request. The admission is
  on `payload-preferences` alone, so no other collection's `user`-only
  write is widened in, and `eventImport` stays out as before.
- **Absorb.** Once reported, the failure answers with the document the
  call was given, which is all `upsertPreferences` reads back (`.value`).
  Its five callers, the folder views included, read only that value, so
  the list renders with the incoming preferences, unsaved. A failure
  `captureFailure` drops is not reported and still throws, as does every
  other.

The integration spec drives the real `upsertPreferences` into a failing
create and a failing update, so a Payload release that changes either
call fails a test instead of reopening the gap.

Follow-up to #1046 (review thread decision A).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ardnived added a commit that referenced this pull request Oct 30, 2026
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]>
Ardnived added a commit that referenced this pull request Oct 30, 2026
* fix(jobs): report a failed job run to Sentry

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

* feat(jobs): let a task mark an expected failure, reported at warning

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

* feat(jobs): mark config gaps outside production, no speech and a deleted 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]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Ardnived added a commit that referenced this pull request Nov 5, 2026
…anyway

Every list render that changes a viewer's columns, sort or limit saves
them through Payload's `upsertPreferences`, which writes
`payload-preferences` with `user: req.user` and no `req`. `ListView`
swallows a throw there with a bare `console.error` and renders a blank
list, and the capture's gate excluded the write.

One predicate, `preferencesUpsert`, now matches that exact call: a
`payload-preferences` create or by-id update whose options are exactly
the keys `upsertPreferences` passes, with `depth: 0` and
`disableTransaction: true`. That means no `req`, no `where`, and access
left overridden. It decides both halves of the change:

- **Report.** The call is reported without a request. The admission is
  on `payload-preferences` alone, so no other collection's `user`-only
  write is widened in, and `eventImport` stays out as before.
- **Absorb.** Once reported, the failure answers with the document the
  call was given, which is all `upsertPreferences` reads back (`.value`).
  Its five callers, the folder views included, read only that value, so
  the list renders with the incoming preferences, unsaved. A failure
  `captureFailure` drops is not reported and still throws, as does every
  other.

The integration spec drives the real `upsertPreferences` into a failing
create and a failing update, so a Payload release that changes either
call fails a test instead of reopening the gap.

Follow-up to #1046 (review thread decision A).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1046 — f63498b8 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.

fix(admin): a failed document write in the admin reaches no one

3 participants