Skip to content

fix(db-*): atomic job claiming for drizzle and mongodb in 3.x (#18565) - #18709

Merged
JessRynkar merged 10 commits into
payloadcms:3.xfrom
PINYOPATTANAWASANPORN:fix/3.x-jobs-atomic-claiming-18565
Nov 16, 2026
Merged

JessRynkar merged 10 commits into
payloadcms:3.xfrom
PINYOPATTANAWASANPORN:fix/3.x-jobs-atomic-claiming-18565

Conversation

@PINYOPATTANAWASANPORN

Copy link
Copy Markdown
Contributor

Summary of Changes

  • @payloadcms/db-mongodb (updateJobs.ts):
    • Implement atomic single-job claiming via Model.findOneAndUpdate(query, updateData, ...) for limit === 1.
    • Preserve the original query (processing: false) in $and: [query, { _id: { $in: candidateIDs } }] during batch claiming (limit > 1) so concurrent workers do not overwrite each other's claims.
  • @payloadcms/drizzle (updateJobs.ts):
    • Perform single-pass atomic row claiming guarded by and(inArray(table.id, jobIDs), eq(table.processing, false)) returning only newly claimed rows when isInitialJobClaim(data).

Root Cause / Technical Context

In Payload 3.x (v3.90.2), job claiming uses a non-atomic two-phase find followed by updateMany per row without concurrency guards:

  1. Two or more workers polling simultaneously find the same pending jobs with processing: false.
  2. Both workers mark and execute the same jobs concurrently.
  3. With deleteJobOnComplete: true, the faster runner finishes and deletes the job row. The slower runner then attempts to update the deleted row, resulting in TypeError: Cannot read properties of null (reading 'log') and HTTP 500 errors.

Verification & Testing

Closes #18565

…dcms#18565)

- In @payloadcms/db-mongodb, use findOneAndUpdate for single job claims (limit: 1) and maintain  query filters for multi-job candidate claiming.
- In @payloadcms/drizzle, perform atomic single-pass row updates guarded by eq(table.processing, false) and return only newly claimed rows.
- Eliminates race conditions and null reading 'log' crashes across concurrent runners in 3.x without requiring schema migrations.

Closes payloadcms#18565
@PINYOPATTANAWASANPORN PINYOPATTANAWASANPORN changed the title fix(core): atomic job claiming for drizzle and mongodb in 3.x (#18565) fix: atomic job claiming for drizzle and mongodb in 3.x (#18565) Oct 14, 2026

@DanRibbens DanRibbens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Written with AI

Requesting changes on ddb73f4. A non-breaking v3 fix is possible, but this backport is incomplete and introduces a MongoDB regression.

  1. Blocking: MongoDB batch claims leave jobs stuck without executing them. In packages/db-mongodb/src/updateJobs.ts, lines 135–146, claimQuery retains the original processing: false predicate. updateMany changes the matching jobs to processing: true, then Model.find(claimQuery) excludes those same jobs. With the default limit: 10, even a single runner can mark jobs as processing, return no jobs to execute, and leave them stranded. Reading back only by candidate IDs would reintroduce duplicate execution. For a schema-free v3 fix, claim each candidate with conditional findOneAndUpdate using the original eligibility query and return only the documents those calls actually claimed.

  2. Concurrent runByID calls remain unprotected. The caller still uses an unconditional update by ID. MongoDB matches only the ID, and Drizzle's optimized ID path returns before reaching the new conditional-claim branch. #17441 also changed the caller to use a conditional claim; the adapter changes alone do not cover this path. Please add an atomic processing-state guard while deliberately preserving v3's other existing runByID behavior, rather than copying all of v4's eligibility restrictions without a compatibility assessment.

  3. The v3 hook/depth paths bypass these adapter changes. queues/utilities/updateJob.ts uses payload.update when jobs.runHooks is true or jobs.depth is nonzero. Those paths need an explicit solution or a clearly documented limitation; silently removing or bypassing hooks/population would change supported v3 behavior.

Please add database-backed regression coverage for default/greater-than-one batch limits, competing queue runners, concurrent runByID, and completion cleanup on MongoDB, PostgreSQL, and SQLite. Copying #17441's limit: 1 polling test alone would miss the MongoDB batch regression above. The hook/depth paths also need coverage if included in the concurrency guarantee.

There is no need to backport #17441's breaking changes wholesale: Drizzle's conditional UPDATE ... RETURNING can identify the jobs it claimed without a token, and MongoDB can do the same with per-candidate findOneAndUpdate. This avoids adding processingToken to the jobs schema or requiring SQL migrations. Keep the optional custom-adapter fallback for v3 rather than making updateJobs mandatory; scope the concurrency guarantee accordingly.

Validation: source comparison against #17441 and execution of this PR's MongoDB adapter function with mocked database operations confirmed the batch read-back failure and repeated ID claims. Database-backed integration tests were not run as part of this review.

@denolfe denolfe added the v3 label Oct 15, 2026
- db-mongodb: claim batch candidates with per-candidate conditional findOneAndUpdate
  and return only the documents actually claimed (fixes jobs stuck as processing)
- drizzle: drop non-existent processingToken from claim detection
- runByID: atomically claim only when the job is not already processing
- runHooks/depth: claim through the adapter first, then run payload.update on the
  claimed IDs so hooks and population still apply
- add regression tests for batch limits, competing runners, concurrent runByID and
  completion cleanup, with and without runHooks
@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 30f3e58c-366a-48ec-b873-3645a259830e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@r1tsuu
r1tsuu requested a review from DanRibbens November 3, 2026 14:05
@DanRibbens DanRibbens changed the title fix: atomic job claiming for drizzle and mongodb in 3.x (#18565) fix(db-*): atomic job claiming for drizzle and mongodb in 3.x (#18565) Nov 3, 2026
@DanRibbens
DanRibbens requested a review from AlessioGr November 3, 2026 15:20
@DanRibbens

Copy link
Copy Markdown
Contributor

Written with AI

Follow-up review of 29a4fdd10b3c5b8074f2e205ac79fd68ce7f18b7: the MongoDB batch claiming and concurrent runByID issues from the previous review are addressed. The per-candidate MongoDB claims return only documents actually claimed, and runByID now adds the processing-state guard while preserving its other v3 eligibility behavior. The regression tests cover default batch limits, competing runners, concurrent runByID, and completion cleanup with runHooks enabled and disabled. No schema migration was added, and the custom-adapter fallback remains.

I would keep changes requested because the hook/depth path still needs work:

  1. Hook failures can leave jobs stuck as processing without executing them. In claimJobsWithHooks, the database claim commits processing: true before payload.update runs. If a hook throws, there is no release of the claim. A document-level hook failure is also returned in the bulk update's errors array, which this helper ignores; that job is omitted from result.docs and remains claimed. Either way, it never executes and subsequent queue runners exclude it. Please handle both thrown errors and per-document errors so failed hook updates do not strand claimed jobs.

  2. Existing hook behavior changes. Hooks now receive originalDoc.processing === true during the claim update. Hooks that detect the transition from pending to processing therefore stop working. The implementation acknowledges this in a code comment, but the compatibility concern from the previous review remains. Please preserve the supported v3 hook behavior or explicitly assess and document the limitation.

  3. Targeted hook/depth regression coverage is still missing. The new tests toggle runHooks, but do not add custom job hooks to verify transition behavior or failure handling. They also do not exercise jobs.depth > 0. Please cover hook failures, hook transition semantics, and populated job retrieval at nonzero depth alongside the concurrency assertions.

Validation: source review and execution of the actual updated helper with mocked database/API operations reproduced both the thrown-hook and bulk-error cases leaving processing: true. CI is green for this commit, including MongoDB, PostgreSQL, and SQLite integration jobs. Database-backed tests were not run locally for this follow-up review.

PINYOPATTANAWASANPORN and others added 8 commits November 4, 2026 19:13
…tion semantics

- Release claimed jobs back to processing: false when payload.update throws or reports per-document hook errors
- Preserve originalDoc/previousDoc processing: false during pre-claimed hook updates
- Add integration coverage for hook transitions, hook failures, and nonzero jobs.depth population
…tion semantics

- Release claimed jobs back to processing: false when payload.update throws or reports per-document hook errors
- Preserve originalDoc/previousDoc processing: false during pre-claimed hook updates
- Add integration coverage for hook transitions, hook failures, and nonzero jobs.depth population
…tion semantics

- Release claimed jobs back to processing: false when payload.update throws or reports per-document hook errors
- Preserve originalDoc/previousDoc processing: false during pre-claimed hook updates
- Add integration coverage for hook transitions, hook failures, and nonzero jobs.depth population
@PINYOPATTANAWASANPORN

Copy link
Copy Markdown
Contributor Author

Hi @DanRibbens,

Thank you for the detailed follow-up review! The three points have been addressed in the latest updates (bf11dd0):

  1. Hook Failure Unstranding & Error Handling:

    • In claimJobsWithHooks, both thrown errors in the update call and per-document failures returned in result.errors are now caught. Any un-executed or failed claims in failedIDs are released immediately back to processing: false in the database so jobs are never left stranded.
  2. Hook Transition Semantics Preserved:

    • In update.ts, claimedJobIDs ensures that document hooks observe the genuine pending -> processing transition by providing originalDoc.processing === false for the claimed operation while retaining real database state for external readers.
  3. Targeted Hook, Depth & Contention Test Coverage:

    • Extended test/queues/int.spec.ts across runHooks: true, depth: 1, contended batch retries, and competing worker lock races across all supported database adapters.

All database-backed integration test suites (MongoDB, PostgreSQL, SQLite) and queue suites pass cleanly in CI. Ready for your final re-review whenever you have a moment.

@JessRynkar
JessRynkar enabled auto-merge (squash) November 16, 2026 11:29
@JessRynkar
JessRynkar merged commit 45e6edc into payloadcms:3.x Nov 16, 2026
344 of 346 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚀 This is included in version v3.94.0

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.

5 participants