Repository navigation
fix(jobs): stop jobs overwriting state that changed mid-run - #1128
Conversation
…-run Four writers read a row, did slow work — sent an email, rendered a page — then wrote the row back unconditionally. A manager's review, a block, a verify or a "Check again" press landing in that window was silently overwritten, and every `activityLog` append dropped whatever another writer had added since its own read. Two writes now carry the assumption each makes: - `updateIfUnchanged` (`src/lib/atomicWrites/`) ANDs the row's id with the values the caller read into one `payload.update`, so the row is re-selected at write time. It is `payload.update` rather than the atomic `payload.db.updateOne`, because both callers need what the operation carries: the hook that keeps an event's capacity flag in step with a failed delivery, and the version row an unpublish writes. - `appendLogEntry` (same folder) adds one entry with `jsonb ||`, trimmed to `DEFAULT_LOG_LIMIT` in the same statement, on the caller's own connection — two of the nine writers are `afterChange` hooks whose transaction already holds the row's lock. The pure `appendLogEntry` it replaces is gone, with its nine read-modify-write call sites. `persistVerification` is the same rule for `canonical.verification`, which no Payload `where` can compare: the nightly job and the Check endpoint now share one statement, conditioned on `IS NOT DISTINCT FROM` the state each folded from, so neither discards the other's attempt and failure count. Two smaller defects in the same files ride along. Restoring an event from the trash re-armed nothing, so the next nightly run trashed it again; the save hook now runs a `finished` event's retention from the restore and returns a managerless one to `unverified`. And the Install guide read any attempt as a failed install, so an inconclusive-only history showed the red "we could not open the page ourselves" banner while a released service still read "Your atlas is live". Refs #1116 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWf8vMnBkEKgYtLuoy
One spec per race, each driving the two writers through the slow step that opens the window — a stubbed send or render — and asserting which answer the row ends on. Every one of them was watched failing against the behaviour it pins: - `block-user`: a block landing mid-delivery keeps `spam`, and the delivery is still in the log. - `expire-events`: a verify landing mid-fan-out keeps its stage, its watermark and its own log entry, beside the reminder the run really sent. Plus the two restore cases, which the nightly run re-trashed. - `client-canonical`: a Check during the nightly render, and the nightly verdict during a Check, each leave the other's result standing. - `session-reminders`: a writer replacing the whole log mid-send no longer costs the ledger entry, so the next hourly run sends nothing. - `atomic-writes` is new, and pins what neither is: the `jsonb ||` merge, its trim, a column holding something other than an array, and that the append runs on the transaction its request carries. - `install-model`: an inconclusive-only history is `seen`, and a service at the failure limit is not live. The three guides that describe these writes say so now: `src/AGENTS.md` for the new lib folder, the collections guide for how an `activityLog` is appended, and `docs/rules/clients.md` for the one statement both verification writers share. Refs #1116 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWf8vMnBkEKgYtLuoy
A four-lens pass over the branch. Everything here is quality, not behaviour,
except the two reads the Install guide was still taking twice.
- `appendLogEntry` resolved its table and column off the Drizzle adapter, for
a helper called with two slugs against a column `logField` always names. It
now reads the schema through `quotedDbSchema`, which is where that answer
already lived, and spells the rest the way the repo's two other raw
statements do. The `merged` expression is bound once rather than
interpolated twice, and the cast is down to the one thing genuinely new
here: the transaction's own session.
- `quotedDbSchema` / `getDbSchema` take a `Payload` as well as a request —
a Server Action has only the instance, and the alternative was a second
copy of "which schema is this adapter bound to".
- `isAtFailureLimit` is exported from the verification ladder and read by both
`nextVerificationState` and the Install guide, which had restated the
comparison. The `confirmed` milestone asked the same question a third time,
off `verification.verified` alone, so a released service read as confirmed
there while the banner said otherwise; it reads the stage now.
- `EventBookkeeping` no longer Picks `activityLog`: nothing passes it, so the
capability to clobber a log through the validation-skipping writer is gone
rather than narrowed by one caller.
- `updateBookkeeping` takes one object, not five positional arguments, and
ExpireEvents' in-memory copy is named `known` — it is what this run has
sent, never the column's value.
- `depth: 0` on the two submission writes whose returned document nobody
reads; at the config's default a proposal recomputes both review
projections. Two `select`s in `block.ts` named a column neither reader uses.
`tests/unit/activity-log-writers.spec.ts` is the new half: the nine converted
call sites are held by prose otherwise, and a tenth writer spelling
`data: { activityLog: [...] }` would compile, pass, and reintroduce #1116. It
allows exactly one whole-array write — the cycle reset in `Events/lifecycle/
verify.ts` — and fails if that exemption stops being used. Watched failing
against a re-added read-modify-write.
Refs #1116
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWf8vMnBkEKgYtLuoy
… back from The security sweep raised the fallback as a correctness question rather than a vulnerability: a request naming a transaction the adapter no longer holds would write on the plain connection. That is Payload's own `getTransaction` behaviour, and it is safe for the reason the helper exists — a session is gone only once it has committed or rolled back, so there is no row lock left to wait on. Said so where the fallback is. `updated_at` goes through `escapeIdentifier` like its two neighbours, rather than being the one hand-quoted name in the statement. Refs #1116 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWf8vMnBkEKgYtLuoy
|
🚅 Deployed to the SahajCloud-pr-1128 environment in sahajcloud
1 service not affected by this PR
|
…tional-writes # Conflicts: # AGENTS.md # docs/rules/testing-reqs.md # tests/AGENTS.md # tests/PERF.md
The four conflicts were all the pinned unit-lane counts, which #1082 moved on main while this branch moved them too. Resolved to main's numbers plus this branch's one new spec, and recorded as a row of its own rather than over #1082's measurement, as tests/PERF.md asks. Refs #1116 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjWf8vMnBkEKgYtLuoy
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the shape #1116 asks for: four read-then-write races closed, each write stating what it assumed, plus the two ride-alongs the ticket names. Every deviation from the ticket's prescribed payload.db.updateOne is argued in the body, and the arguments hold against Payload 3.90.2.
My one reservation is the total, not any piece. The ticket asked for one helper; this lands three mechanisms, and the jsonb column is what forces the rawest of them. That is a column-shape question, worth asking before activity-log-writers.spec.ts makes the shape permanent.
Findings
consider— an appended entry and the admin's draft read (src/lib/atomicWrites/appendLogEntry.ts:31).consider— three mechanisms where the ticket asked for one (src/lib/atomicWrites/appendLogEntry.ts:54).consider— an outcome counted but not persisted (src/jobs/VerifyEmbeds/VerifyEmbeds.ts:167).
What was checked. Reviewer profile read. #1116 against the diff, file by file. Read whole on the branch: both atomicWrites/ modules, persistVerification.ts, updateEventWithoutValidation.ts, ExpireEvents.ts, DeliverSubmissions.ts, verifyEmbed.ts, syncVerificationOnSave.ts, installModel.ts, and the three new or changed specs.
Ladder, against node_modules at 3.90.2: Payload's bulk update does take unpublishAllLocales and excludes trashed rows exactly as updateByID does, so updateIfUnchanged loses neither; @payloadcms/drizzle exports no getTransaction from its index, so the sessions[id].db cast reimplements nothing public. getLatestCollectionVersion compares no updatedAt — the first finding.
Both preview links answer 302 to sign-in, so they are deployed; the admin behind them needs a browser sign-in this run has none for.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`events` carries drafts, so Payload serves every `draft: true` read from the `latest: true` version row whenever one exists — `getLatestCollectionVersion` compares nothing against the main row. The admin edit view reads that way, and it is the Activity Log table's only reader, so an atomically appended entry was invisible there. Worse, `updateByID` loads the document it is about to write from that same row and writes the merged whole back, so the next ordinary save of the event deleted every entry appended since — the dropped reminder entry #1116 exists to stop. The `payload.update` this helper replaced reached both rows, through `saveVersion({ unpublish })`. Both halves are now pinned by specs that were watched failing. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZ2a4zVWBENr19VjZt
The outcome counter ran before `persistVerification`, and the lost-race path below it continues without undoing the count — so a nightly run reported a verdict it had discarded, while the Check that won counted the same service again on its own path. Every other counter in this loop already sits after the write, for that reason. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjZ2a4zVWBENr19VjZt
|
Three critic threads. Two built, one back to you.
Lean gate green. Re-ran 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Approved, but this thread still waits on you, and the ruleset will not merge until it is resolved: #1128 (comment). Reply there, or resolve it. 🤖 sydevs dispatcher |
The reviewer chose option A on the three-mechanisms thread: fix the column rather than keep a hand-escaped `jsonb ||` merge beside two other writers. `logField` is a Payload `array` now, so one entry is one row. An append is an INSERT with bound parameters — no `escapeLiteral`, no merge expression, no `jsonb_array_elements` guard — and the trim is a DELETE of the oldest. `appendLogEntry` still runs on the caller's own connection, and still reaches the `latest: true` version row, for the two reasons its docblock gives. An entry's four named parts are columns; everything else it carries is one `data` column, because each writer owns its own keys and a row cannot grow a column per writer. `toLogRow` splits an entry, `asLog` spreads `data` back out, so every reader still sees one flat entry and no call site had to learn where a key is stored. The migration is hand-augmented, which `src/migrations/AGENTS.md` otherwise forbids: it drops each jsonb column in the same transaction that creates the table replacing it, so there is no later window to move the entries in. An emptied log is a reminder sent twice — it is the verification cycle's exactly-once marker and the session-reminder ledger. Two observable changes, both pinned: a denied read answers with no rows rather than no field, which `docs/rules/access.md` already documents for an array; and an entry's machine fields are no longer queryable paths, so the address a reminder went to cannot be filtered on by anybody, an admin included. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjVGV7eh45m3RDruTp2
|
One thread, answered. You chose A, so the column is fixed rather than worked around.
Three things worth your eye, all in the refreshed body:
Lean gate green. Whole integration lane re-run: 108 files, 1998 tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
…tional-writes All three conflicts were the pinned unit-lane figures, which both sides had moved: this branch to 265 files / 3548 tests, `main` to 265 / 3552 after #1112. Neither number describes the merged tree, so the figures are re-measured here rather than taken from a side — 266 files / 3555 tests, the gate's unit lane at 51.44 s. `tests/PERF.md` says to add a row rather than replace one, so both sessions' rows stay, ordered by commit time, and this merge records its own. `AGENTS.md` needed the same file count: it conflicted with neither side, because both sides said 265, and only the merge makes it 266. `main` brought in #1112, which touches AppCards alone and shares nothing with this branch's log and atomic-write changes. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYxiu3EzJyBTKCDi4c
|
Merged Neither number describes the merged tree, so I re-measured rather than taking a side: 266 files / 3555 tests, the unit lane at 51.44 s inside the gate.
Gate: ✓ lint, format, both typechecks, 3555 unit tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
#1128 and #1112 both landed with a migration, so `src/migrations/index.ts` conflicted on the one line each side appends. Both entries are kept, in timestamp order: this branch's `recover_lost_jobs_task` (18:26) then main's `activity_log_rows` (21:55). No other file conflicted. `main`'s snapshot is the newer one and knows nothing of the `recoverLostJobs` task slug, so `migrate:create` re-emitted both `ADD VALUE` statements that `20261111_182607_recover_lost_jobs_task` already ships. Replaying one aborts the boot migration, so `20261111_232203_merge_main_snapshot_8` keeps only its snapshot — generated on the merged tree, which heals the chain. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjYBoRAv89LXUYU7iHz
#1128 added a migration and a batch of unit tests, which collided with this branch's own. - `src/migrations/index.ts`: both migrations are wanted, ordered by timestamp. #1128's snapshot is the newest, and this branch's migration is data-only, so the snapshot chain needs no healing. - `tests/PERF.md`: both sides' measurement rows kept, `main`'s numbering preserved and this branch's appended. The merged tree measures 267 files / 3562 tests, written into the metric table and the four consumer docs `perf-figures-pinned.spec.ts` holds to it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV9PjD3U4U88XF9fj7
#1128 landed a migration beside this branch's. src/migrations/index.ts carries both, in timestamp order — the encrypt migration is data-only, so main's snapshot stays the newest and the chain needs no healing. The other four conflicts were the unit-lane counts, each side stating its own. Re-measured on the merged tree: 268 files, 3571 tests, 59.19 s, and every consumer doc says so. tests/PERF.md's session table is a log, so both branches' rows survive, renumbered, with this run's appended. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjX29DbGatggeyMkJVs
Summary
jsonbarray, so an append is anINSERTwith bound parameters (reviewer's call, option A).Change outline
The defect is one shape in four places: read → slow work → unconditional write. Each write now carries its own condition, and the
activityLogappend stops being a whole-array write at all.Flow — one background writer, before and after
ExpireEventsis the same shape over a fan-out: each reminder's log entry is appended as it is sent, and the stage advance at the end is conditional on both the stage and the watermark as read — a manager's verify leaves the stage atverifiedand moves onlynextCheckAt, so the stage alone would not have caught it.processEvent(event) src/jobs/ExpireEvents/ExpireEvents.ts for recipient of recipients sendNotification(...) # seconds, per recipient - log = capLog([...log, entry]); updateBookkeeping { activityLog: log } + appendLogEntry entry # `known` stays in memory, for this run's dedup only if allDelivered updateBookkeeping { verificationStage, nextCheckAt, _status? } + expect verificationStage == stage AND nextCheckAt == the one readThe column — one row per entry
logFielddeclares a Payloadarray, not a JSON column. That is what makes the append parameterised: noescapeLiteral, no merge expression, nojsonb_array_elementsguard.An entry's four named parts are columns; everything else it carries is one
datacolumn, because each writer owns its own keys and a row cannot grow a column per writer.toLogRowsplits,asLogrejoins — so every reader still sees one flat entry and no call site had to learn where a key is stored.Files — where the three writes live
Two mechanisms now, not three. Only
canonical.verificationstill needs raw SQL, because a Payloadwherecannot compare a wholejsonbobject:payload.updatewith awhereactivityLogINSERTone row,DELETEthe oldest, bound parametersdatacan carry without rewriting every rowcanonical.verificationUPDATE … IS NOT DISTINCT FROMwherecannot compare a wholejsonbobjectBehaviour — a restore, and what the Install guide calls a failure
Migration
20261111_215539_activity_log_rowscreatesevents_activity_log,user_submissions_activity_logand_events_v_version_activity_log, moves every stored entry into them, then drops the threejsonbcolumns.⚠ It is hand-augmented, which
src/migrations/AGENTS.mdotherwise forbids, and that guide says to put the trade-off to a person. This run had nobody to ask, so the reasoning is here instead: the generated migration drops each column in the same transaction that creates the table replacing it, so there is no later window a separate data migration could run in. And an emptied log is not cosmetic — an event's log is the reminder job's exactly-once marker for the open verification cycle, and a registration's is the session-reminder ledger, so losing it re-sends reminders already sent. Thedowndirection re-aggregates the rows back into the columns for the same reason.Preview
Both pages need a record to show anything, and this repo sets no
previewUrl.seed.Data: not seeded yet— no seed command is configured for this repo, so a fresh preview holds only its admin manager. Create a class and a service on the preview to see either page on data.Test results
.claude/skills/pr-prep/check.sh— lint, format, both typechecks, 3550 unit testsBoth lanes were re-run after merging
main(#1082). Its four conflicts were all the pinned unit-lane figures, which this branch had also moved.Manual verification
Notes for reviewer
payload.update, not the atomicpayload.db.updateOnefix(jobs): stop jobs overwriting state that changed mid-run #1116 names. That form writes the main table alone, and both callers need what the operation carries: theafterChangehook that keeps an event's capacity flag in step when a registration's delivery fails, and the version row an unpublish writes. What it leaves open is Payload's own select-then-update, which is milliseconds against the render or the send this closes.appendLogEntrybinds its values now, through Drizzle's ownsqltemplate rather thanpg.escapeLiteral. It still reaches one adapter internal — the Drizzle transaction session, with a narrow cast beside the onesrc/plugins/usage/db.tsalready holds for the pool — because it has to run on the caller's connection: two of its nine writers areafterChangehooks whose transaction already holds the row's lock, and a second connection would wait on it for ever.activity-log-writers.spec.tsstays. One row per entry did not retire the whole-log spelling: Payload rewrites every row of an array field on each save, sodata: { activityLog: [...] }still clobbers a concurrent append exactly as it did. The spec allows the one reset that means to.docs/rules/access.mdalready documents for an array (managers-access,manager-contacts). And an entry's machine fields are no longer queryable paths, so the address a reminder went to cannot be filtered on by anybody, an admin included — strictly narrower than thejsonbcolumn, which admittedactivityLog.destinationfor an admin.Detail
What the column change cost and bought. An append is now one
INSERTplus oneDELETE, both with bound parameters, against one statement of hand-built SQL before._orderis read and written in the same statement, so two concurrent appends can land on the same number — a tie in the stored order and nothing else, since no entry is lost and the table is read back sorted onat. The admin table reassembles the rows from form state (useLogValue), becauseuseFieldanswers an array field's row count;reduceFieldsToValuesis Payload's own way back to a document shape, and is what the live-preview provider posts into the iframe.Checked and dropped, from the four-lens and security passes:
persistVerificationshould live besideClients, not inlib/. It has two consumers outsidesrc/lib— the nightly job and the Check endpoint — which is whatlib-boundary.spec.tsasks for, and sharing one statement between them is the point.expectrequired onupdateEventBookkeeping. It would routeregistrations/fullnessandeventFeedbackthrough the bulk form, which collects a per-document error instead of throwing — a silent-failure change to two writes this ticket does not touch.resolveNextCheckAtas a "never in the past" floor. ExpireEvents deliberately leaves a pastnextCheckAton a partial fan-out, so the next run retries the recipients it could not reach. A floor there would break that.SendDigestsis a fourth instance of the same read-modify-write. Its task declaresconcurrency: { key: () => 'sendDigests', exclusive: true }anddigestWatermarkscarriesaccess.update: () => false, so the job is the column's only writer and only one run exists at a time.refuseOpenSubmissionsnow costs 2N round trips. N is one sender's open submissions, and the loop already ran N updates. Converting it to a bulk update changes which shape each hook sees, on an endpoint this ticket only touches to move a log write.Why the append is not enforced by the field. A Payload field hook cannot see the stored rows any earlier than the operation already does, so a
beforeChangemerge would leave the same window. The rule is a spec instead, in the mould oflib-boundary— it allows exactly one whole-log write, the cycle reset inEvents/lifecycle/verify.ts, and fails if that exemption stops being used.What the append still gives up. It appends no version history and runs no hook. Nothing reads an activity log back as state, and the entry is built in our own code rather than taken from a caller.
It still writes the
latest: trueversion row, where the collection carries drafts.eventsdoes, and Payload serves everydraft: trueread from that row whenever one exists —getLatestCollectionVersioncompares nothing against the main row. The admin edit view reads that way, and it is the Activity Log table's only reader.updateByIDloads the document it is about to write from that same row, so the main row alone meant the next ordinary save of the event deleted every entry appended since. The version table keys its rows on_events_v.id, not the event's, so the append resolves the latest version row first.The condition on
canonical.verificationis the whole object, not a cheaper sibling column.nextVerifyAtwould have worked today, because the same two statements write both — but that is a coupling a reader has to be told about, andIS NOT DISTINCT FROMneeds no note.Work this removes. The per-recipient fan-out in
ExpireEventspreviously ran a fullpayload.updateoneventsper recipient — a document read, the whole hook chain, a new version row — to append one array element; it is one insert now.SendSessionRemindersdropped the same shape from its innermost loop, and three reads stopped selecting a 50-entry column they no longer use.Closes #1116
🤖 Generated with Claude Code
https://claude.ai/code/session_01Mg9rjVGV7eh45m3RDruTp2