Repository navigation
perf(service-queue): claim and settle a database queue batch with set writes - #38575
Conversation
…tle writes and the two-adapter double claim Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
…d on the unclaimed state Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
📓 Docs Drift CheckThis PR changes 1 package(s): 1 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 1 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 3 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 6ec84310116fe58c36682567e93dbef622046fd5 && git checkout 6ec84310116fe58c36682567e93dbef622046fd5
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 1a9d1495e181a941d4a710dd916a89560d1b05f8 1515a3ea7ddc92dc08ab36057a768a4ee611ca4c && git checkout -B drift-repro 1a9d1495e181a941d4a710dd916a89560d1b05f8 && git merge --no-ff 1515a3ea7ddc92dc08ab36057a768a4ee611ca4c
node scripts/docs-audit/affected-docs.mjs --json 1a9d1495e181a941d4a710dd916a89560d1b05f8
|
… two batch set writes Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb 席位核对 — L1 ACCEPT · head 1515a3e · 2026-11-29T11:23ZI read the diff at 1515a3e against the L1 checklist and card #38548, with amendment 7255002837. The diff is 4 files, +376/−54, including the regenerated census counts file, which is a derivative only. At the time of reading, the checks on this head were 14 success, 18 skipped, 14 pending and 0 failed, so this verdict is on the diff and landing waits for green. Fixes #38548 holds. All three acceptance lines are met.
The two points the area asked about:
A behaviour difference, stated in the changeset and fine. The completed-set write is matched as the renewal is, on Nit, not a hold. The batch path's candidate read now takes Not run by me. The service-queue vitest suite needs a built objectql dist that this container lacks. I rely on CI and on the body's three ablations: the claim reverted, the settle reverted, and the ACCEPT once the pending checks finish green. Tier S, so the area lands it. |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb Flake judgment on head 1515a3e: Test Core (9/12) (job 141327686635, run 46256699666) failed AFTER its tests passed. Every package on the shard reports all test files passed (verify 55/55, client 60/60, knowledge-turso 4/4, knowledge-pgvector 5 + 8 skipped, hono 14/14, plugin-dev 10/10; turbo "66 successful, 66 total"), and the shard-timing step printed OK. The one error is the artifact upload: "Failed to CreateArtifact: Unable to make request: ECONNRESET". None of this PR's packages (service-queue) failed. The area re-runs the failed job once; a second failure is treated as real. |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb Landing: head 1515a3e · L1-a ACCEPT 7255085919 · |
|
repo:objectstack#1 · zhuangjianguo · session_01QsR2jSyQBDMyRnrrWKy7WS 席位核对 — ACCEPT stands · L1 re-read by seat repo:objectstack#1, review thread R1 · Head-sha
|
…are-and-set write (objectstack-ai#38820) repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2 Fixes objectstack-ai#38578 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:多节点部署下,数据库队列里逐条处理的任务(发邮件、附件回收、API 流订阅)不再被两个节点各执行一次;单节点无感。 - 为什么做:解决数据库队列主循环"同一条消息被两个节点同时领取"的问题,与批量路径已做的修复保持一致。 - 出错会怎样:最坏情况是某个节点这一轮领不到消息、下一轮再领,不会丢消息;改动只在一个服务包内,可直接撤回。 - 要你做什么:无。 ## What changes - `packages/services/service-queue/src/db-queue-adapter.ts`: the main loop's claim (`claimBatch`) now takes a tick's candidate rows with ONE compare-and-set write over their id set, matched on `status: 'pending'` and due as well as id, then one read of the ids this worker holds when fewer rows matched. The write core is factored out of the batch path's `claimSet` into one private helper, `claimCandidates`, which both call; `claimSet`'s behaviour is unchanged. A sole writer's lease entries are recorded for won rows only (for every candidate only when the write throws, as before on the batch path). - Pacing is unchanged: the read still over-fetches `batchSize * 3`, at most `batchSize` rows are claimed per tick, and each message goes to its handler alone. - Four in-memory engine doubles (`job-queue-retention.test.ts` and three `plugin-email` suites) implemented only the by-id update; they now open `update` with `assertEngineUpdateDispatch` and answer the predicate (`multi: true`) write, and the three `plugin-email` matchers answer `$in`, the shape `db-queue-idle-backoff.test.ts` already carries. Fixture-only: no assertion changed. - `.changeset/38578-db-queue-main-loop-cas.md`: patch for `@objectstack/service-queue`. ## Tests - `db-queue-adapter.test.ts`: PR objectstack-ai#38575's CONTROL case is flipped. Two adapters over one store that read the same 5 pending per-message rows now handle each message once (it pinned each handled twice), with one claim write per adapter tick. A new case pins pacing: `batchSize: 2` drains 5 messages as 2, 2, 1, 0 in claim order with 3 claim writes. <details><summary>Ablation: drop status pending from the claim match</summary> On-disk edit removing `status: 'pending'` from the `claimCandidates` where, restored with `git checkout HEAD` (porcelain clean after): ``` FAIL ... > the main loop claims a tick's rows with one compare-and-set write, so two adapters over one store hand each per-message message to one handler call AssertionError: expected 10 to be 5 FAIL ... > two adapters over one store that read the same pending rows hand each batch message to one handler call AssertionError: expected 40 to be 20 Tests 2 failed | 50 passed (52) os-verify-lock: VERDICT command-exit 1 ``` </details> <details><summary>Package runs at 4700c4a (code identical to b14de17)</summary> ``` pnpm --filter @objectstack/service-queue test -> Test Files 5 passed (5), Tests 107 passed (107) pnpm --filter @objectstack/plugin-email test -> Test Files 54 passed (54), Tests 1053 passed (1053) pnpm --filter @objectstack/trigger-api test -> Test Files 3 passed (3), Tests 73 passed (73) typecheck service-queue, plugin-email (incl. check:test-typecheck), trigger-api -> Done, VERDICT command-exit 0 ``` Before the fixture fix the new claim turned 6 service-queue and 16 plugin-email tests red (the by-id-only doubles refused the predicate write). </details> ## Acceptance notes - Consumers: mail send (`email-plugin.queue-delivery.test.ts`, `email-plugin.outbox-sweep.test.ts`), mail attachment reclaim (`email-plugin.attachment-storage.test.ts`) and API-flow subscriptions (`packages/triggers/trigger-api/src/api-trigger.test.ts`; its double is its own queue stand-in, not the database adapter, so it is unaffected and green). - Ledger gates are green at e799299: `pnpm check:engine-double-contract` exit 0, `node scripts/check-tenant-audit-census.mjs` exit 0, and its `--self-test` exit 0 (29 cases pass). The service-queue census now counts 12 write call sites (was 13: the two claim writes are now one), and `scripts/engine-double-contract.pinned.json` records the four doubles as pinned. - `scripts/engine-double-contract.seams.json` is unchanged by `--write` (0 seams added or lost), so it is not in the diff. - Four RECONCILED rows remain in the engine-double shrink-only baseline (the three plugin-email suites and job-queue-retention): they pass and only over-license, the baseline is off this card's surface and optional to tighten, so they are left. - Not in scope (per the card): the batch path, the lease length, at-least-once re-delivery after a crash. ## Verification - Read first: `db-queue-adapter.ts` `claimCandidates` (the where clause is the fix), then `claimBatch`, then the flipped two-adapter case in `db-queue-adapter.test.ts`. - Two minutes: `pnpm --filter @objectstack/service-queue exec vitest run --maxWorkers=2 src/db-queue-adapter.test.ts` -> all green; delete `status: 'pending',` from the `claimCandidates` where and re-run -> the two two-adapter cases go red (10 vs 5, 40 vs 20). - Gates: `dispatch-gates --commands` derived 76 families; `--ran` reconciled 74 run, 2 NOT-MEASURED (`check:dual-build-cjs-loads` exit 3 prerequisite, `check:query-options-erasure` repo-wide eslint over the foreground budget), 0 unrun; both ledger gates green at e799299 after the regeneration commit. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
Requested by Leehom · project thread
Fixes #38548
Clause-②: no
Metadata-protocol: none
维护者速读
Step 1 finding (measured before any change)
The claim write of
claimBatchisengine.update(sys_job_queue, { id, status: 'running', ... }): a by-id write, matched by id alone. Two adapters over one store that both read a row as pending both overwrite its lease and both dispatch it.claimedA + claimedB = 40, every message handed to a handler twice. Real store (ObjectQL overSqlDriver, better-sqlite3 on a file, same barrier): 200 messages,claimedA 100, claimedB 100, all 100 claimed rows handled twice.subscribe, the per-message path): reproduced. Same harness overpollOnce: 5 messages, each handled twice. Not fixed here (ruling 7250307515: per-message queues' behaviour and pacing stay untouched). It is reported to the seat as an open question; the reproduction stays in the suite as the CONTROL case below.What changes
packages/services/service-queue/src/db-queue-adapter.ts, batch path only (pollBatchOnce/dispatchBatch):claimSet). The read takes up tomaxBatchdue candidates (it wasmaxBatch * 3), then onemulti: trueupdate setsrunning+ this worker's lease, matched onid $in idsANDstatus: 'pending'AND due (scheduled_fornull or not after now). A row another node claimed between the read and the write matches nothing. When the store answers fewer matched rows than asked, one read ofid $in ids, status running, locked_by mesays which rows this worker won; the rest are dropped from the batch.settleCompleted), the lease renewal's shape:where { id $in ids, status: 'running', locked_by: me },multi: true. A fresh backlog is one settle write per batch. A row whose lease was reclaimed underneath keeps its new holder's state; fewer matched rows is logged as a lost lease, as the renewal logs it. A set write that throws falls back to onesettleRowper row, so one bad row does not strand the rest.settleRow(its own backoff, error and dead letter).batchInFlightbefore the claim write and lease entries are recorded after it, so a main-loop reclaim during the claim cannot drop an entry.claimBatchkeeps its per-row by-id claim andmax * 3over-fetch; its candidate read and claimability check moved into two shared helpers (readClaimCandidates,isClaimable) with the same predicates, order and limits.Tests went into the shared harness
db-queue-adapter.test.tsas one new top-leveldescriberather than a new file (ruling record 6583487846). Its fakeupdatenow honoursmulti: truepredicate writes and answers the matched count, as the engine's predicate path does.Write-count table
Writes to
sys_job_queuewhile draining the batch queue (renewals excluded; none fired):maxBatch100 (unit test)maxBatch100 (SQLite, below)Drain before / after
Store: the one PR #38509 measured on, ObjectQL over
SqlDriverwith better-sqlite3 on a file,sys_job_queueregistered byQueueServicePlugin. Bench: publish N messages,subscribeBatchwith a no-op handler (maxBatch100), callpollBatchOnceuntil it claims 0. Base = the adapter atd08d2ae972; head = this branch. Shared box, under the verify lock (absolutes are shared-box readings; the ratio is the reading).8.1x faster drain, 100x fewer writes. Remote store: NOT MEASURED (none reachable). On a remote store each removed write is a network round trip, so the saving there is larger than the local ratio.
Ablation
On committed code, through
scripts/ablation-replace.mjs(mutation proved on disk by anchor count and blob; restored to blob8ccbd947,git diff HEADempty):Claim set write reverted to the per-row by-id claim: 3 red
claimSet(queue, batch.maxBatch, this.batchInFlight)replaced byclaimBatch(queue, batch.maxBatch):expected { claim: 250, settle: 3, renew: 0 } to deeply equal { claim: 3, settle: 3, renew: 0 }expected { claim: 6, settle: 3, renew: 0 } to deeply equal { claim: 1, settle: 3, renew: 0 }expected 40 to be 20Settle set write reverted to per-row settles: 2 red
expected { claim: 3, settle: 250, renew: 0 } to deeply equal { claim: 3, settle: 3, renew: 0 }expected { claim: 1, settle: 6, renew: 0 } to deeply equal { claim: 1, settle: 3, renew: 0 }Unclaimed-state match removed from the claim (id set only): 1 red
expected 40 to be 20Tests
Readings
Under the verify lock. The code is the same from
2f602bfc28to head1515a3ea7d: the later commits add only the changeset and the regenerated census. On1515a3ea7d, in a fresh worktree after building the dependency closure:pnpm --filter @objectstack/service-queue testgaveTest Files 5 passed (5),Tests 106 passed (106), VERDICT command-exit 0.pnpm --filter @objectstack/service-queue test:Test Files 5 passed (5),Tests 106 passed (106)(102 before + 4 new), VERDICT command-exit 0.pnpm --filter @objectstack/service-queue typecheck: VERDICT command-exit 0;tsc --listFilesreaches all 5 test files of the package.pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/record-sync-queue.test.tsafter rebuilding service-queue'sdist(the knowledge suite imports it fromdist;claimSetfound 3 times in it):Tests 41 passed (41). This is the real kernel overSqlDriver(better-sqlite3 on a file), including the batch cases (1,000 syncs in batches, a poisoned record dead-lettering alone), so the set writes run against the real engine'smulti: truepath.{ claim: 250, settle: 250 }against{ claim: 3, settle: 3 };{ claim: 6, settle: 6 }against{ claim: 1, settle: 3 };expected 40 to be 20; the CONTROL passed (each per-message message handled twice).Acceptance notes
claimBatchclaims by id alone, so two nodes draining one per-message queue (mail send, mail attachment reclaim, API-flow subscriptions) can both run a message. Reproduced by the CONTROL casethe main loop's claim, matched by id alone and unchanged here, lets both adapters claim the rows they both read(5 messages, each handled twice). Left untouched per ruling 7250307515; the same set-write CAS would close it.maxBatchrows, notmaxBatch * 3: a single CAS write gains nothing from over-fetching. A batch that loses rows to another node comes back short and its loop waits as for any short batch.runningunder this worker. Before, a batch whose lease was reclaimed underneath overwrote the new state; now it does not, and the message runs again where it went (at-least-once, as before).db-queue-batch-writes-38548.test.ts; ruling record 6583487846 puts a new pin for a component with a shared harness into that file. The claim amendment accepts this.Verification
Read first (risk order):
claimSetandsettleCompletedindb-queue-adapter.ts, then the newdescribeat the end ofdb-queue-adapter.test.ts.Two-minute check:
pnpm --filter @objectstack/service-queue exec vitest run --maxWorkers=2 src/db-queue-adapter.test.ts -t 'set writes'should show 4 passed, includingdrains N batch messages with O(N / maxBatch) claim and settle writes, not 2N.Local gates
node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstackderived 65 commands for the 3 changed paths (merge based08d2ae97). Each was run with its exit code captured before any pipe.e0c5953f74(64 after the census re-run), among themcheck:engine-double-contract("OK — 1403 pinned, 119 in the DEBT ledger, 3 exempt"),check:nul-bytes,check:type-check-coverage,check:cross-package-test-inputs,check:where-matcher.node scripts/check-tenant-audit-census.mjsand its--self-test: exit 0 on head1515a3ea7d("OK -- 354 write call sites certified across 19 package shard(s)"; self-test "29 cases pass"). The first run one0c5953f74was red (the committed census counted 11 write call sites against 13 in the tree, from the two new set writes). The census was regenerated bynode scripts/tenant-audit-census.mjs --writealone and committed by itself as1515a3ea7d:docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md, 8 lines, counts 11 to 13 andupdate8 to 10. The claim amendment added that file to the surface.pnpm check:dual-build-cjs-loads, exit 3 PREREQUISITE NOT MET (65 published packages have nodist; it needs a full build). CI runs it.--ran: "65 derived famil(ies) accounted for — 64 run, 1 NOT-MEASURED".node scripts/pm/overlap-check.mjs --branch=HEADon1515a3ea7d, before its push: "origin/main: merges cleanly" (a133c8ad1b), VERDICT clean exit 0.Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
🤖 Generated with Claude Code