Repository navigation
fix(api): map a Postgres 22P02 cast failure to 400, on Payload's routes and in geojson - #685
Conversation
A caller-supplied value Postgres cannot cast to a column's type raises SQLSTATE 22P02 and reached the client as an unhandled 500. Two instances are live in production and are the same error class one type apart: `invalid input value for enum enum_meditations_type: "path"` (Sentry 126185460, 190 events since June) and `invalid input syntax for type integer: "NaN"` (Sentry 136881789, 114 events). This is a diagnosability problem, not a load one. A 500 tells the caller nothing, which is why the first has fired unchanged for three months — and 300-odd events of "the server broke" are noise in a channel where a 500 is supposed to mean wake someone. Map the database error rather than pre-validating the query, per the approach agreed on #670. The database is already making this judgement correctly and precisely at the moment it matters; a `where`-value check would only reach the 51 `select` fields, so it would fix the enum instance and leave the integer one firing, and it would re-derive per request what one handler covers for every enum, id and date cast that exists or is added later. It also costs nothing on a healthy request, because it runs only after a query has already failed. Two things the ticket flagged as unverified, now measured rather than assumed: - `afterError`'s return value does re-shape the REST response in [email protected] — `payload/dist/utilities/routeError.js` assigns `response = result.response` and `status = result.status` before `Response.json(response, { status })`. - the SQLSTATE does survive drizzle's wrapping, on `cause`. `tests/int/database-cast-errors.int.spec.ts` makes a real Postgres reject a real query and asserts it, so a drizzle or pg upgrade that stopped preserving `cause` reddens the lane instead of silently restoring the 500s. The Sentry plugin asks the same pure predicate before reporting, rather than reading a flag the other hook sets, so the two are independent of the order they are registered in. Without that guard the noise would survive the fix: `captureErrors` includes 400, so restatusing alone would keep reporting them. Everything else is untouched — a genuine 500 stays a 500 and is still reported. The `Path`/`lesson` mismatch behind the enum instance is recorded as decided, not left open: `lesson` is the in-code name for a Path step and sending the label is the client's mistake, which the 400 now says. Both new assertions were watched failing at the site that would really cause them — `findPostgresError` not walking `cause` — and restored: 3 unit and 2 integration assertions went red. Closes #670 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PmKbZaa1XnbTvLehjR3GoG
Review found `findPostgresError` stopping at the first error carrying
*any* string `code`, then comparing. Those are the same thing only while
nothing between Payload and the driver sets a `code` of its own — true
of drizzle-orm 0.45.2, and an assumption about somebody else's library
rather than an invariant.
The failure it invites is silent and self-concealing: one wrapper with a
`code` (a Node `SystemError`, a future `DrizzleQueryError` revision) and
the 22P02 beneath it is never reached, so the request reverts to the 500
this change exists to remove *and* the Sentry suppression stops — with
both specs still green, because each pinned the chain at
drizzle-wrapper-over-pg-error. `findPostgresError` now takes the code to
look for and keeps walking; a new unit case puts an `ECONNRESET` decoy
between the wrapper and the driver, and was watched failing against the
old shape.
Two wording corrections from the same review, no behaviour change:
- the WARN is **additive**. `routeError` calls `logError` at ERROR with
the full stack before any `afterError` hook runs, and `loggingLevels`
cannot reach it — that keys on `err.name`, which `DrizzleQueryError`
never sets. Both lines are emitted; only the Sentry report goes.
Anything alerting on ERROR still fires, and the docs implied it would
not.
- the predicate keys on the SQLSTATE alone, so a 22P02 **our own** code
causes is now a 400 blaming the caller and is reported nowhere. That
is the accepted cost of the trade, and it was worth stating where
"a genuine 500 stays a 500" could be read as covering it.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmKbZaa1XnbTvLehjR3GoG
|
🚅 Deployed to the SahajCloud-pr-685 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the size of the ticket: ~60 lines of logic, ~240 of tests, ~150 of docs and comments, no refactor smuggled alongside. Both premises #670 flagged as unverified are genuinely settled, and I re-checked the first one independently against [email protected]'s dist/utilities/routeError.js — a hook's { response, status } is applied (response = result.response || response), hooks are reduced in registration order, and a later hook returning undefined does not clobber an earlier result, so the Sentry hook's early return is safe and the two plugins really are order-independent.
One shape problem is worth fixing before merge: the claim of generic coverage is wider than the seam delivers. afterError fires from Payload's own REST handler, so GET /api/events/geojson — which forwards the client's where verbatim and catches its own errors — still answers a flat 500 for exactly this failure class on an enum column the OpenAPI docs invite callers to filter on. Either map it there too or narrow the sentence. Beyond that: the response body invents a name field that is outside the ErrorResponse schema this API publishes, and the rationale is now written out three times (module header, plugin header, docs/architecture.md) in a change whose logic is one predicate and one hook. Nothing here questions the design — mapping the database's own judgement rather than re-deriving it per field is the right call, and shipping the blunt 400 as a floor is the right sequencing.
Not flagged, but stated so the decision is visible: the 400 forwards Postgres's message verbatim, so enum_meditations_type becomes client-visible; given debug: true in src/payload.config.ts:54 already returns stacks (filed as #684), this narrows rather than widens the leak. And a non-numeric id now yields 400 rather than 404, which #670's acceptance criteria explicitly allowed either way.
Findings
- should-fix —
docs/architecture.md:221: "covers every enum, id and date cast" does not hold for custom endpoints that catch their own errors;src/collections/Events/endpoints/geojson.ts:118-133still 500s onwhere[eventType][equals]=bogus. - should-fix —
src/plugins/databaseErrors/databaseErrorPlugin.ts:72:name: 'BadRequest'is outside the publishedErrorResponseschema and unlike every other error body in this repo. - consider —
src/plugins/sentry/sentryPlugin.ts:117: suppression keys on the error class, not on whose value it was;&& req.userwould keep a trace when the bad value is ours. - consider —
src/lib/databaseErrors/index.ts:8: four files across two new directories for one predicate and one hook. - consider —
src/lib/databaseErrors/postgresCastError.ts:24: the rationale is told three times, and line 72's ⚠ block narrates a review round rather than the code.
What was checked
- Ticket #670 read in full against the diff — approach, all seven acceptance criteria, the two ⚠ premises, and the one open product decision (
Path/lesson, recorded in the module header as the ticket asked). - Diff from the attached checkout:
git diff origin/main...origin/claude/fix-22p02-cast-400— 9 files, +524/-0, commits03341d5andfcfb8f3. - Payload internals, since this repo has no
node_moduleshere: fetched[email protected]'sdist/utilities/{routeError,formatErrors,isErrorPublic}.jsand read them. Confirms (a) hook return values re-shape response and status, (b) multipleafterErrorhooks reduce without clobbering, (c)logErrorruns at ERROR with the stack before any hook — so the PR's "the WARN is additive" caveat is accurate, and (d)formatErrorsemitsnameonly for anAPIError/ValidationErrorcarryingdata, which is the basis of the second finding. - Consumer side. Grepped
WeMeditateWebandSahajAtlasWebfordaily_fallback_shri_mataji_clipand for ameditationstypefilter: no in-tree client sends either value, so the 500→400 change breaks no repo in this workspace, and the failing client is external.SahajAtlasWeb/src/config/api/mutate.ts:59-105readserrors[].messageanderrors[].code/errors[].data.code— it tolerates an extraname, but it is not a consumer of one either. - Contract surfaces in-repo:
src/plugins/openapi/customEndpoints.ts:224-237and theErrorResponseschema at:1585-1605; the ~20 hand-built{ errors: [{ message }] }bodies acrosssrc/lib/endpoints/,src/endpoints/atlas/,src/collections/*/endpoints/. - Reach of the seam: read every custom endpoint that catches its own errors —
Events/endpoints/geojson.ts,endpoints/atlas/seo/index.ts,endpoints/atlas/sitemap/index.ts— and confirmedEvents.ts:348-353makeseventTypeaselect, hence an enum column, which is what makes the geojson gap concrete rather than theoretical. - Log convention:
src/plugins/usage/hooks.ts:180-210— the new WARN matches the existingpayload.logger.warn({ msg, clientId: req.user?.id, … })shape exactly, as #670 asked. - Specs: both new files read. The integration spec drives a real Postgres for both live cases and pins the
causeshape rather than a fixture; the unit spec'sECONNRESETdecoy is the one that would fail against the pre-fcfb8f3walker. Not re-run — CI is green onfcfb8f3. - Reviewer profile (
workflow/skills/adversarial-review/reviewer-profile.md) read and applied; no findings raised on style, naming, or test volume.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
…`name` Answers my own adversarial review on #685. Two should-fix findings acted on, two consider adopted, one rebutted with evidence. **The coverage claim was wider than the seam reaches, and geojson was the concrete gap.** Root `afterError` hooks are invoked by payload's `dist/utilities/routeError.js`, so a custom endpoint that catches its own errors never reaches the plugin. `Events/endpoints/geojson.ts` forwards the client's `where` verbatim onto `eventType`, a Postgres enum column the OpenAPI docs advertise filtering on — so `where[eventType][equals]=bogus` was still a flat 500 naming nothing, with no Sentry event either, on a documented client route. It now calls `mapPostgresCastError` in its own catch, and `docs/architecture.md` states the seam's real reach plus the obligation any future self-catching handler inherits. The regression case is in `tests/int/events-geojson.int.spec.ts`, driven against a real Postgres because the SQLSTATE is the whole assertion. Watched failing at the site that causes it — with the catch reverted it reports `expected 500 to be 400`; restored, 23/23. **`name: 'BadRequest'` is gone.** It was outside the published `ErrorResponse` schema (`plugins/openapi/customEndpoints.ts`), unlike ~20 other error bodies here, and carried nothing the 400 status did not. Replaced with `code: '22P02'`, which *is* in the schema and lets a client branch on the cause without parsing Postgres prose. **Folded `postgresCastError.ts` into `lib/databaseErrors/index.ts`** — the import path is byte-identical, and one file now holds the idea instead of a header, a barrel and a plugin barrel each restating it. The rationale was told three times (module header, both plugin comments, `docs/architecture.md`); the code now carries the imperatives and the doc carries the story, and the ⚠ block that narrated a review round is one line. **Not adopted: discriminating the Sentry suppression on `req.user`.** It would change nothing. `hasPermission` returns false for a null user (`plugins/access/permissions.ts:59`) and no collection overrides `read` publicly, so an anonymous read is denied before any SQL runs — `req.user` is set on every error that can reach these hooks, including a 22P02 our own code composed during a client's request, which is the case it was meant to catch. What does preserve the signal is already there: `routeError` calls `logError` at ERROR with the full stack before any hook runs. Written down in `docs/architecture.md` so it is not re-proposed. Gate: lint, typecheck, typecheck:tests, test:unit (120 files / 1553 specs), plus `tests/int/{events-geojson,database-cast-errors}.int.spec.ts` — all green. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS
|
My own review found a real gap and it is fixed:
The one that needs no decision from you but is worth reading. The The regression case, and the gateWatched failing at the site that causes it, per with the new catch reverted; 23/23 with it restored, and the WARN confirms the value reaches the caller — The other two self-catching handlers were checked before concluding geojson was the only one owed a call: Gate, all green in the checkout: Diff since the review: 8 files, 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Ardnived
left a comment
There was a problem hiding this comment.
Looks good. We accept the decision to not change the discriminator raised by the adversarial review.
…`name` Answers my own adversarial review on #685. Two should-fix findings acted on, two consider adopted, one rebutted with evidence. **The coverage claim was wider than the seam reaches, and geojson was the concrete gap.** Root `afterError` hooks are invoked by payload's `dist/utilities/routeError.js`, so a custom endpoint that catches its own errors never reaches the plugin. `Events/endpoints/geojson.ts` forwards the client's `where` verbatim onto `eventType`, a Postgres enum column the OpenAPI docs advertise filtering on — so `where[eventType][equals]=bogus` was still a flat 500 naming nothing, with no Sentry event either, on a documented client route. It now calls `mapPostgresCastError` in its own catch, and `docs/architecture.md` states the seam's real reach plus the obligation any future self-catching handler inherits. The regression case is in `tests/int/events-geojson.int.spec.ts`, driven against a real Postgres because the SQLSTATE is the whole assertion. Watched failing at the site that causes it — with the catch reverted it reports `expected 500 to be 400`; restored, 23/23. **`name: 'BadRequest'` is gone.** It was outside the published `ErrorResponse` schema (`plugins/openapi/customEndpoints.ts`), unlike ~20 other error bodies here, and carried nothing the 400 status did not. Replaced with `code: '22P02'`, which *is* in the schema and lets a client branch on the cause without parsing Postgres prose. **Folded `postgresCastError.ts` into `lib/databaseErrors/index.ts`** — the import path is byte-identical, and one file now holds the idea instead of a header, a barrel and a plugin barrel each restating it. The rationale was told three times (module header, both plugin comments, `docs/architecture.md`); the code now carries the imperatives and the doc carries the story, and the ⚠ block that narrated a review round is one line. **Not adopted: discriminating the Sentry suppression on `req.user`.** It would change nothing. `hasPermission` returns false for a null user (`plugins/access/permissions.ts:59`) and no collection overrides `read` publicly, so an anonymous read is denied before any SQL runs — `req.user` is set on every error that can reach these hooks, including a 22P02 our own code composed during a client's request, which is the case it was meant to catch. What does preserve the signal is already there: `routeError` calls `logError` at ERROR with the full stack before any hook runs. Written down in `docs/architecture.md` so it is not re-proposed. Gate: lint, typecheck, typecheck:tests, test:unit (120 files / 1553 specs), plus `tests/int/{events-geojson,database-cast-errors}.int.spec.ts` — all green. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS
Summary
enum_meditations_type: "path"(Sentry 126185460) andinteger: "NaN"(136881789).⚠ Two seams, not one — the second was found by review. Payload's root
afterErrorhook is invoked byrouteError, which serves Payload's own REST routes. A custom endpoint that catches its own errors never reaches it, soGET /api/events/geojson— which forwards the client'swhereverbatim ontoeventType, an enum column the OpenAPI docs advertise filtering on — was still answering a flat 500. It now calls the same predicate directly.Changes
src/lib/databaseErrors/index.ts— the pure recogniser. Matches the SQLSTATE down thecausechain, since drizzle wraps every failed query.src/plugins/databaseErrors/— theafterErrorhook that answers with it and logs at WARN, for Payload's own REST routes.src/collections/Events/endpoints/geojson.ts— the same mapping in a handler the hook cannot reach.src/plugins/sentry/sentryPlugin.ts— asks the same predicate before reporting.src/payload.config.ts,docs/architecture.md— registration, the behaviour written down, and what the seam does not reach.Preview
The
SahajCloud-pr-685environment deployed successfully (logs) on the previous head; the new commit redeploys it.⚠ No public host to link. Railway's comment leaves the Web column empty for this deploy, and
scripts/get-railway-preview-url.tsneedsRAILWAY_API_TOKEN, which this session does not hold — so the URL is neither published nor discoverable from here. The Manual verification commands below are written against$URL; the environment link above is where to get it.Nothing here is reachable from a normal route anyway — the change is only observable through a deliberately-bad request.
Test results
test:unit(120 files / 1553 specs), all exit 0tests/unit/postgres-cast-error.spec.ts(12), ✓tests/int/database-cast-errors.int.spec.ts(3), ✓tests/int/events-geojson.int.spec.ts(23) — the last two against a real Postgresfcfb8f3; re-running oncfbab29Manual verification
Against the preview, with an API key:
curl -s -o /dev/null -w '%{http_code}' "$URL/api/meditations?where\[type\]\[equals\]=path&select\[id\]=true"→ 400equals=lesson→ 200curl -s "$URL/api/lectures/daily_fallback_shri_mataji_clip"→ 400, not 500curl -s "$URL/api/events/geojson?select\[title\]=true&depth=1&where\[eventType\]\[equals\]=bogus"→ 400 withcode: "22P02", not 500126185460and136881789should record no new events.Notes for reviewer
The ticket's two ⚠ unverified premises are measured, not assumed. Both were the reason it said "verify before implementing":
afterError's return value does re-shape the REST response in[email protected]—routeError.js:82-85assignsresponse = result.response || responseandstatus = result.status || statusbeforeResponse.json.cause.tests/int/database-cast-errors.int.spec.tsmakes a real Postgres reject a real query and asserts it, so a drizzle orpgupgrade that stopped preservingcausereddens the lane instead of silently restoring the 500s.Your
Path/lessoncall is recorded in the code, not just in the ticket —lessonis the in-code name for a Path step, sending the label is the client's mistake, and the 400 now says so.One thing this PR trips over and does not fix, filed as #684:
src/payload.config.ts:54setsdebug: trueunconditionally, which switches off Payload's production error redaction — so today production already returns the fullFailed query: …plus a stack trace for every unhandled error. This change narrows that for 22P02 (one Postgres message, no SQL, no parameters, no stack), but the general leak is wider than this ticket and belongs in its own PR.One thread is deliberately left open — the
consideron whether the Sentry suppression should discriminate onreq.user. I declined it with evidence rather than silently; the decision is yours to reverse and the reasoning is indocs/architecture.md.Design, what review changed, and the negative proofs
Why map the error rather than validate the query
Agreed on the ticket, and it holds up: the database is already making this judgement correctly and precisely at the moment it matters. A
where-value check reaches only the 51selectfields, so it fixes the enum instance and leaves the integer one firing; and it re-derives per request, per field type, what one handler covers for everything.The cost is message quality — Postgres names the type (
enum_meditations_type), not the field, and cannot enumerate valid options. Shipped as the floor, as the ticket proposed: a blunt 400 that cannot miss a case beats a 500.Why Sentry asks the predicate rather than reading a flag
captureErrorsincludes 400, so restatusing alone would keep reporting these — the noise would survive the fix. The Sentry hook therefore calls the same puremapPostgresCastError. Asking rather than reading a marker the other hook sets means the order the two plugins are registered in is not load-bearing, which is one less invariant nothing checks.What the adversarial review changed
Five findings. Two should-fix and two consider adopted; one consider rebutted.
geojson.tswas the concrete gap — a documented client route, forwarding the client'swhereonto an enum column, still answering 500 with no offending value named and no Sentry event. It callsmapPostgresCastErrorin its own catch now, anddocs/architecture.mdstates the reach plus the obligation any future self-catching handler inherits.tests/int/events-geojson.int.spec.tspins it against a real Postgres — watched failing at the site that causes it (expected 500 to be 400with the catch reverted), then restored.name: 'BadRequest'is gone. It was outside the publishedErrorResponseschema and carried nothing the status did not. Replaced withcode: '22P02', which is in that schema and is the one thing a client cannot recover by parsing Postgres prose.postgresCastError.tsfolded intolib/databaseErrors/index.ts— identical import path, no call site or spec touched, one file holding the idea instead of a header, a barrel and a plugin barrel each restating it.docs/architecture.mdcarries the story.req.user. It would change nothing.hasPermissionreturns false for a null user (plugins/access/permissions.ts:59) and no collection overridesreadpublicly, so an anonymous read is denied before any SQL runs —req.useris set on every error that can reach these hooks, including a 22P02 our own code composes during a client's request, which is the case it was meant to catch. A job's own query never reaches the hook at all (routeErroris the only invoker). And the signal it was meant to preserve already exists:routeErrorcallslogErrorat ERROR with the full stack before any hook runs, so these are absent from Sentry but never invisible.The earlier author-side review
Three findings, all acted on; a fourth was raised as a defect and then disproved by the security pass (it is #684's, above).
findPostgresErrorstopped at the first error carrying any stringcode, then compared — identical to matching the code only while nothing between Payload and the driver sets acodeof its own, which is an assumption about somebody else's library rather than an invariant. Now it keeps walking, with anECONNRESETdecoy case that was watched failing against the old shape.routeErrorcallslogErrorat ERROR with the full stack before anyafterErrorhook runs, andloggingLevelscannot reach this error — it keys onerr.name, whichDrizzleQueryErrornever sets. Both lines are emitted; only the Sentry report goes.Measured while implementing, and worth knowing
payload.findByID({ collection: 'lectures', id: 'daily_fallback_shri_mataji_clip' })throws Payload's ownNotFound(404) before any SQL runs — the slug is not the way in through the local API. Only the numericNaNreaches Postgres, which is what the integration spec asserts; the coercion in front of it belongs to the REST layer this lane cannot drive.Closes #670
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01BG2uTcLbYEjqrx62vc7yAS