Skip to content

fix(drizzle): limit atomic predicate updates to one document - #19156

Closed
DanRibbens wants to merge 2 commits into
mainfrom
fix/atomic-update-one
Closed

DanRibbens wants to merge 2 commits into
mainfrom
fix/atomic-update-one

Conversation

@DanRibbens

Copy link
Copy Markdown
Contributor

Written with AI

Description

Atomic updateOne predicates could update every matching row while returning only the first. Select one matching ID, retain the original predicate on the write, and reject predicates requiring joins. Branch row-ID resolution remains in the content branching PR.

Extracted from #19101. This PR targets main and can merge independently of the content branching stack and the other extracted PRs.

Changes

This PR contains only the standalone behavior and its focused regression coverage. The content branching stack inherits this change through its prerequisite branch instead of duplicating the implementation.

Test Plan

  • SQLite integration regression: 1 passed.
  • pnpm lint passed with existing repository warnings.
  • Changed files formatted with pnpm exec oxfmt --write.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 329547c and e3594d6.

Files selected for processing: 2
  • packages/drizzle/src/updateOne.ts
  • test/database/conditional-update.int.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Walkthrough

Atomic updateOne now selects one row that matches the predicate and updates it only if its ID and predicate still match. It rejects atomic predicates that require joins. Integration tests cover concurrent calls and a single call when two posts match.

Changes: Atomic Conditional Updates

Layer / File(s) Summary
Select and update one matching row
packages/drizzle/src/updateOne.ts, test/database/conditional-update.int.spec.ts
Atomic updateOne rejects predicates that require joins. It selects one matching row and updates it only when the row ID and original predicate still match. It returns null when no row matches and retries if the selected row is no longer updated. Integration tests check concurrent calls and verify that a single call changes one of two matching posts.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

  • payloadcms/payload#19101: Includes related atomic predicate changes; this PR isolates the one-row selection and retry behavior.
  • payloadcms/payload#19069: Uses a distinct-ID-first pattern for deleteOne fallback behavior, related to predicate-based single-row mutation selection.

Suggested reviewers: paulpopus

Merge Risk: Minimal · up to e3594

The atomic update change is mergeable after normal checks; no actionable issue remains from this review.

Security architecture risk: Low · up to e3594

The change restricts conditional writes to one qualifying document and preserves the original predicate at write time. No introduced authorization bypass was identified. Remaining uncertainty concerns compatibility for join-dependent predicates and behavior under database contention and different transaction modes.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed branch affects callers using atomic predicates without an explicit ID. For those calls, its successful write scope contracts from all predicate matches to one selected primary-key row in the resolved collection table. This does not establish authorization beyond the predicate supplied by the caller.

Security Findings and Attack Paths

  • inferred — No introduced predicate-dropping or row-identity bypass was identified in the inspected transition. A competing change that makes the selected row cease to qualify causes the guarded write to return no row rather than write unconditionally. This conclusion is limited to the inspected path, not a complete security assessment of all consumers.

Trust Boundaries and Controls

  • observed — The built predicate is reused in both selection and write, with selected-ID equality added to the write. Join-dependent predicates are rejected before mutation rather than executed with missing join conditions.

Resilience and Maintainability Implications

  • observed — The retry loop exits on success or no candidate, but has no explicit attempt limit or cancellation check. Database exceptions are not handled locally. This establishes an unbounded local retry policy, not a demonstrated denial-of-service or failure of caller-level recovery.

Hardening Proposals

  • proposed — Consider an explicit contention budget or cancellation-aware retry policy, together with transaction-mode-specific validation, to bound database work without conflating predicate mismatch with lock or serialization failures.
Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the main change: atomic predicate updates in Drizzle's updateOne are limited to one document, matching the raw summary (one matching ID is selected, the predicate is kept on the write,…
Description check Passed The description relates directly to the changeset. It states that atomic updateOne predicates could update every matching row while returning only the first, and it says the PR selects one matching ID…
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: atomic predicate updates in Drizzle's updateOne are limited to one document, matching the raw summary (one matching ID is selected, the predicate is kept on the write, and join-requiring predicates are rejected). The title is short, specific, and uses the conventional fix(scope) format. It does not mention the retry behavior or the join rejection, but it does not need to cover every detail.

Full details: Description check

Explanation

The description relates directly to the changeset. It states that atomic updateOne predicates could update every matching row while returning only the first, and it says the PR selects one matching ID, keeps the original predicate on the write, and rejects predicates that require joins. These points match the updateOne.ts changes. It also gives test-plan details that match the added integration regression.

Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 2 files.

Finishing Touches: 💡 1
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖
This PR introduced no changes to the esbuild bundle! 🙌

@DanRibbens
DanRibbens marked this pull request as ready for review October 29, 2026 02:59

if (!docs[0]) {
return null
while (true) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Did you explore using a subquery for this? Given we have no joins or complex fields here, it may be easy enough. I don't like this being done in a branch that asserts if (options.atomic === true) , this is no longer true here

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.

Written with AI

Explored the subquery approach and replaced this implementation in #19214. Candidate selection and the guarded write now run in one UPDATE ... RETURNING statement, with no separate lookup or application retry loop. The path remains behind options.atomic === true.

PostgreSQL needs FOR UPDATE inside the candidate subquery: in a controlled contention probe, a plain subquery with the outer predicate returned no row after losing the first candidate, even though another qualifying row remained. The locking subquery lets the waiting caller continue to that other row. SQLite uses the subquery without FOR UPDATE because it serializes writers. The original predicate is retained on the outer update, and predicates requiring joins remain rejected.

The replacement's focused tests pass on PostgreSQL (8) and SQLite (6, with 2 PostgreSQL-only tests skipped), including competing commits, competing rollbacks, and rollback of the caller's update. D1 execution remains unverified. Closing this PR as superseded by #19214.

@DanRibbens

Copy link
Copy Markdown
Contributor Author

Written with AI

Superseded by #19214, which implements the suggested single-statement subquery approach and adds PostgreSQL contention coverage. The replacement targets main and remains an independent prerequisite for the content branching stack.

@DanRibbens DanRibbens closed this Oct 29, 2026
DanRibbens added a commit that referenced this pull request Nov 10, 2026
Written with AI

## Description

Atomic `updateOne` predicates can update every matching SQL row while
returning only the first. Limit the write to one matching primary key
using a subquery inside the `UPDATE`, retaining the original predicate
on the outer write.

Supersedes #19156 and addresses [the subquery review
suggestion](#19156 (comment)).
This replaces the separate candidate lookup and application retry loop
with one SQL statement. PostgreSQL locks the candidate with `FOR
UPDATE`, allowing a waiting caller to continue to another matching row
if a competing write makes the first candidate ineligible. SQLite uses
the same subquery without a locking clause because it serializes
writers.

## Changes

- Keep the single-statement path behind `options.atomic === true`,
preserving main-table write validation and rejecting predicates
requiring joins.
- Return at most one updated document, or `null` when no document
qualifies.
- Add coverage for multiple matches, concurrent claims, no match,
unsupported predicates/writes, and PostgreSQL contention with competing
commits and rollbacks.
- Verify that rolling back the caller's transaction also rolls back its
atomic update.

This remains an independent prerequisite extracted from #19101.
Branch-specific physical row-ID resolution and visibility remain in the
content branching stack.

## Test Plan

- Focused PostgreSQL integration suite: 8 passed.
- Focused SQLite integration suite: 6 passed; 2 PostgreSQL-only tests
skipped.
- Changed-file oxlint, formatting, and `git diff --check` passed.
- Drizzle package typecheck passed on the reviewed draft. The broader
database-test typecheck reports repository errors; the changed test file
has no diagnostics.
- D1 adapter execution remains unverified.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants