Skip to content

fix(service-queue): the database queue main loop claims with one compare-and-set write - #38820

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38578-db-queue-main-loop-cas
Dec 1, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38578-db-queue-main-loop-cas

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

Fixes #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 perf(service-queue): claim and settle a database queue batch with set writes #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.
Ablation: drop status pending from the claim match

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
Package runs at 4700c4a (code identical to b14de17)
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).

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

@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 Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/service-queue, touching 4 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 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 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; 124 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 47bfc944a766e245e5684c8b9f2a1e2eecd31b34 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 0d061c03f325a919358bc1f9f7aceea4a87d7278 — the merge of head e7992991b885692f51b63d0edd1a886f9a01b4b6 into base 47bfc944a766e245e5684c8b9f2a1e2eecd31b34, 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 0d061c03f325a919358bc1f9f7aceea4a87d7278 && git checkout 0d061c03f325a919358bc1f9f7aceea4a87d7278
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 47bfc944a766e245e5684c8b9f2a1e2eecd31b34 e7992991b885692f51b63d0edd1a886f9a01b4b6 && git checkout -B drift-repro 47bfc944a766e245e5684c8b9f2a1e2eecd31b34 && git merge --no-ff e7992991b885692f51b63d0edd1a886f9a01b4b6

node scripts/docs-audit/affected-docs.mjs --json 47bfc944a766e245e5684c8b9f2a1e2eecd31b34

⚠️ 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 47bfc944a766e245e5684c8b9f2a1e2eecd31b34 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

…e engine-double pinned ledger

Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

L1 ACCEPT · PR #38820 (#38578) · head e7992991b885692f51b63d0edd1a886f9a01b4b6 · read 2026-12-01T03:03Z

席位核对

  1. Shape. Draft, base main, Fixes #38578 is the first line after the seat signature; no keyword binds another card. The PR delivers the card's three asks, so Fixes is right.
  2. Premise measured. At d97aaae, claimBatch claimed each candidate with a by-id engine.update, and its own comment said concurrent workers overwrite each other. The diff replaces that loop with the shared claimCandidates compare-and-set (multi: true over id $in, matched on status: 'pending' and due). Read by the seat, not from the report.
  3. Gates (check-runs at this head). 43 success · 20 expected skip · 0 failed · 0 pending; Lint & Repo Gates and TypeScript Type Check both success. Ablation in the PR body: dropping status: 'pending' from the match turns both two-adapter cases red (10 vs 5, 40 vs 20). No L2 owed: Clause-②: no, no narrowing, no packages/spec/src/**, no governed path.
  4. Accepted deviations. (a) The claim's file surface was widened twice in place (claim 7297237967): first to the four by-id-only engine doubles, then to the three generated ledgers; the maintainer approved the second, path-specific retry after a classifier refusal of a compound git add -A command. (b) @objectstack/plugin-email has no changeset entry: its three files are *.test.ts, and the package ships dist only. (c) Behaviour note: under contention the main loop can now claim fewer than batchSize rows in a tick (the old loop backfilled from the 3× over-fetch); the next tick takes the rest. That is the intended trade, never a message run twice. (d) seams.json is unchanged by --write; four RECONCILED rows stay in the off-surface shrink-only baseline (Acceptance notes).
  5. Out of scope. None filed. The docs-drift page content/docs/automation/webhooks.mdx describes the HTTP delivery outbox (sys_http_delivery, its own claim), not this adapter's main loop; its at-least-once promise still holds. Skills-docs: not owed.
  6. Landing. Not governed (check-governed-merges --pr 38820: 0 of 9 paths, +185/-65). K = 1 (landing-k). main is at 7625001f: git merge-tree clean; main also changed scripts/engine-double-contract.pinned.json, so the seat ran both ledger gates on the merged tree locally: check-engine-double-contract exit 0 and check-tenant-audit-census exit 0 (362 sites certified). Ready + auto-merge now.

Clause-②: no · Metadata-protocol: none

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

2 participants