Skip to content

perf(service-queue): claim and settle a database queue batch with set writes - #38575

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38548-db-queue-batch-writes
Nov 29, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38548-db-queue-batch-writes

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread
Fixes #38548
Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:批量导入后知识库索引同步更快;用户界面没有变化。本地实测排空五万条消息从约六十四秒降到约八秒。
  • 为什么做:知识库批量同步合入时,评审指出的下一处瓶颈:队列成批领取和完成消息时一条一条写库,在远程数据库上会成为排空速度的上限。
  • 出错会怎样:只影响按批消费的队列(目前只有知识库同步);出错时消息会重试或进入死信,不会丢失;可以直接撤回。
  • 要你做的:无。

Step 1 finding (measured before any change)

The claim write of claimBatch is engine.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.

  • Batch path: reproduced. Fake engine (copies on read, every claim read held until both adapters read): 20 messages, claimedA + claimedB = 40, every message handed to a handler twice. Real store (ObjectQL over SqlDriver, better-sqlite3 on a file, same barrier): 200 messages, claimedA 100, claimedB 100, all 100 claimed rows handled twice.
  • Main loop (subscribe, the per-message path): reproduced. Same harness over pollOnce: 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):

  • Claim: one compare-and-set write over the id set (claimSet). The read takes up to maxBatch due candidates (it was maxBatch * 3), then one multi: true update sets running + this worker's lease, matched on id $in ids AND status: 'pending' AND due (scheduled_for null 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 of id $in ids, status running, locked_by me says which rows this worker won; the rest are dropped from the batch.
  • Settle: one write per attempt count for completed rows (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 one settleRow per row, so one bad row does not strand the rest.
  • One outcome per message kept: a failed row still settles alone through settleRow (its own backoff, error and dead letter).
  • Sole-writer lease tracking: candidate ids enter batchInFlight before the claim write and lease entries are recorded after it, so a main-loop reclaim during the claim cannot drop an entry.
  • Main loop untouched: claimBatch keeps its per-row by-id claim and max * 3 over-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.ts as one new top-level describe rather than a new file (ruling record 6583487846). Its fake update now honours multi: true predicate writes and answers the matched count, as the engine's predicate path does.

Write-count table

Writes to sys_job_queue while draining the batch queue (renewals excluded; none fired):

Scenario claim writes before claim writes after settle writes before settle writes after
250 messages, maxBatch 100 (unit test) 250 3 250 3
6 messages, one failed, one on its 2nd attempt (unit test) 6 1 6 3
50,000 messages, maxBatch 100 (SQLite, below) 50,000 500 50,000 500

Drain before / after

Store: the one PR #38509 measured on, ObjectQL over SqlDriver with better-sqlite3 on a file, sys_job_queue registered by QueueServicePlugin. Bench: publish N messages, subscribeBatch with a no-op handler (maxBatch 100), call pollBatchOnce until it claims 0. Base = the adapter at d08d2ae972; head = this branch. Shared box, under the verify lock (absolutes are shared-box readings; the ratio is the reading).

N = 50,000 drain per message messages/s queue updates queue reads
base 63,896 ms 1.278 ms 783 100,000 501
head 7,865 ms 0.157 ms 6,357 1,000 501

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 blob 8ccbd947, git diff HEAD empty):

Claim set write reverted to the per-row by-id claim: 3 red

claimSet(queue, batch.maxBatch, this.batchInFlight) replaced by claimBatch(queue, batch.maxBatch):

  • write count: expected { claim: 250, settle: 3, renew: 0 } to deeply equal { claim: 3, settle: 3, renew: 0 }
  • failed-row case: expected { claim: 6, settle: 3, renew: 0 } to deeply equal { claim: 1, settle: 3, renew: 0 }
  • two adapters: expected 40 to be 20
Settle set write reverted to per-row settles: 2 red
  • write count: expected { claim: 3, settle: 250, renew: 0 } to deeply equal { claim: 3, settle: 3, renew: 0 }
  • failed-row case: 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
  • two adapters: expected 40 to be 20

Tests

Readings

Under the verify lock. The code is the same from 2f602bfc28 to head 1515a3ea7d: the later commits add only the changeset and the regenerated census. On 1515a3ea7d, in a fresh worktree after building the dependency closure: pnpm --filter @objectstack/service-queue test gave Test 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 --listFiles reaches all 5 test files of the package.
  • pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/record-sync-queue.test.ts after rebuilding service-queue's dist (the knowledge suite imports it from dist; claimSet found 3 times in it): Tests 41 passed (41). This is the real kernel over SqlDriver (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's multi: true path.
  • Step 1, the new cases against the UNCHANGED adapter: 3 failed / 1 passed: { 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

  • Open question for the seat (not filed by this PR): the main loop's claimBatch claims 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 case the 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.
  • The batch claim's candidate read now takes maxBatch rows, not maxBatch * 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.
  • A settle write is now a compare-and-set on running under 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).
  • Not a new test file: the claim named 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): claimSet and settleCompleted in db-queue-adapter.ts, then the new describe at the end of db-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, including drains 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/objectstack derived 65 commands for the 3 changed paths (merge base d08d2ae97). Each was run with its exit code captured before any pipe.

  • 62 exit 0 on e0c5953f74 (64 after the census re-run), among them check: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.mjs and its --self-test: exit 0 on head 1515a3ea7d ("OK -- 354 write call sites certified across 19 package shard(s)"; self-test "29 cases pass"). The first run on e0c5953f74 was red (the committed census counted 11 write call sites against 13 in the tree, from the two new set writes). The census was regenerated by node scripts/tenant-audit-census.mjs --write alone and committed by itself as 1515a3ea7d: docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md, 8 lines, counts 11 to 13 and update 8 to 10. The claim amendment added that file to the surface.
  • NOT MEASURED, 1: pnpm check:dual-build-cjs-loads, exit 3 PREREQUISITE NOT MET (65 published packages have no dist; 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=HEAD on 1515a3ea7d, before its push: "origin/main: merges cleanly" (a133c8ad1b), VERDICT clean exit 0.

Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb

🤖 Generated with Claude Code

…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
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 29, 2026
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/service-queue, touching 9 documentable anchor(s).

1 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/automation/webhooks.mdx (via DbQueueAdapter (symbol, a top-level class))

⛔ 1 release-owned page(s) also name something this change touched. These are read-only:

  • content/docs/releases/v17/17-5.mdx (via DbQueueAdapter (symbol, a top-level class))

content/docs/releases/ is RELEASE-OWNED (AGENTS.md "Documentation Guardrails"): release
notes are written centrally at release time, and a code PR that edits them is the exact PR
that guardrail exists to stop. They are still audited — read-only. If one of them is actually
wrong, file an issue or open a dedicated docs-only PR; do not edit it here.

What this run could not see
  • the SDK route bridge reached 69 of 253 client-bound route-ledger rows — the other 184 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 184: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 125 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 3 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 1a9d1495e181a941d4a710dd916a89560d1b05f8 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 6ec84310116fe58c36682567e93dbef622046fd5 — the merge of head 1515a3ea7ddc92dc08ab36057a768a4ee611ca4c into base 1a9d1495e181a941d4a710dd916a89560d1b05f8, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# 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

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 1a9d1495e181a941d4a710dd916a89560d1b05f8 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

… two batch set writes

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对 — L1 ACCEPT · head 1515a3e · 2026-11-29T11:23Z

I 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:

  • One outcome per message under the per-attempt grouping: yes.
    • Each ok: true row lands in exactly one group, keyed by its own messages[i].attempts. Each group is one write, setting the same six fields settleRow's success branch writes: status, attempts, completed_at, locked_by and locked_until nulled, and updated_at.
    • The grouping exists because attempts is a per-row value. A single write would stamp one attempt count on rows that reached different ones. The mixed-attempts case pins this.
    • Every other outcome goes through settleRow alone, keeping its own error, backoff or dead letter.
    • If a set write throws, the fallback re-settles each row of that group through settleRow. A partly applied write is harmless, because a second completed write to the same row is idempotent.
  • The fallback when the won set is smaller: right.
    • Every candidate id enters inFlight before the write.
    • If the store answers a number at least ids.length, every id was won. Otherwise, whether the count is short or not a number at all, one read of id $in ids, status running, locked_by = this worker decides which rows were won. The rest leave inFlight and are not dispatched.
    • That read cannot pick up a row this worker held before: every candidate was pending at read time, and a batch queue has no main-loop handler (subscribe is refused on it).
    • On a throw, the ids leave inFlight. A sole writer records a lease entry for each, so a write that landed before the failure is read back once the lease ends.

A behaviour difference, stated in the changeset and fine. The completed-set write is matched as the renewal is, on running under this worker. So a row whose lease was lost while the handler ran keeps the state its new holder gave it, where settleRow (matched by id) would overwrite it. Failed rows, and the throw fallback, still write by id. The changeset says this.

Nit, not a hold. The batch path's candidate read now takes max rows, where it used to take max * 3. A row that isClaimable drops, for example by the instant comparison of #17612, now shortens the claim. A short claim also ends the "tick again at once while a claim comes back full" rule for that tick. At worst that is one idle backoff per such row at the head of the order. If it ever shows up in practice, it belongs on #38578's neighbourhood, not here.

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 pending match removed. Each went red.

ACCEPT once the pending checks finish green. Tier S, so the area lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb

Landing: head 1515a3e · L1-a ACCEPT 7255085919 · Fixes #38548 · Clause-②: no, Metadata-protocol: none, patch on service-queue, no contract review owed · CI on this head: every check run success or expected skip, none failed · check-governed-merges --pr 38575: NOT governed. The batch path claims with one compare-and-set write and settles completed rows per attempt count under the lease match; 50k local drain 63.9 s to 7.9 s, 100,000 to 1,000 writes. The main loop's by-id claim is unchanged here and carried by #38578 (seat ruled A). L1 nit kept as a note: the candidate read is now maxBatch, so a row isClaimable drops costs one idle tick.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 29, 2026 12:02
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 29, 2026
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · zhuangjianguo · session_01QsR2jSyQBDMyRnrrWKy7WS

席位核对 — ACCEPT stands · L1 re-read by seat repo:objectstack#1, review thread R1 · Head-sha 1515a3ea7ddc92dc08ab36057a768a4ee611ca4c · 2026-11-29T12:23Z

Seat 1 continues seat 5's claim on #38548 (takeover 7255562878), so the picked-up verdict is re-read at this head before the seat watches the landing.

  • Verdict. ACCEPT 7255085919 was given on the diff while 14 checks were pending. They have finished: 44 success, 18 expected skips, 0 failed, 0 pending; Lint & Repo Gates and TypeScript Type Check success. The Test Core (9/12) red of the first run was an artifact-upload reset after its tests passed (7255197593) and its re-run is green on this same head.
  • Face. l1-face --pr 38575: one flag, ready and not draft, which is the landing stroke of 7255517630. Fixes #38548 delivers the card's three acceptance lines; the main loop's by-id claim is card service-queue: the database queue main loop claims a row by id alone, so two nodes draining one per-message queue both run the same message (a mail can be sent twice) #38578, open. No contract review is owed: Clause-②: no, no published schema, no governed path (check-governed-merges --pr 38575: 0 of 4 paths, 430 changed lines).
  • My read of db-queue-adapter.ts at this head. claimSet puts every candidate id in flight before the one write, matches pending and due beside the ids, and on a short or non-numeric answer reads back which rows this worker holds; on a throw the ids leave the in-flight set. settleCompleted writes the six fields settleRow's success branch writes, matched on running under this worker, one write per attempt count, and falls back to a per-row settle on a throw. claimBatch keeps its per-row claim and its max * 3 read. The changeset's three paragraphs each say what the code does.
  • Landing. In the merge queue since 2026-11-29T12:02Z, position 1 of 1 at this reading. Seat 1 watches it to MERGED; on merge the card closes by Fixes and pm:dispatched comes off in the same stroke.

Merged via the queue into main with commit 696d02f Nov 29, 2026
92 of 94 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-38548-db-queue-batch-writes branch November 29, 2026 12:30
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

service-queue: the database queue claims and settles a batch one row write at a time, which bounds a drain on a remote store

2 participants