diff --git a/.changeset/38578-db-queue-main-loop-cas.md b/.changeset/38578-db-queue-main-loop-cas.md new file mode 100644 index 00000000000..05372cb5bdb --- /dev/null +++ b/.changeset/38578-db-queue-main-loop-cas.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-queue': patch +--- + +fix(service-queue): the database queue's main loop claims a tick's rows with one compare-and-set write, so two nodes never both run a per-message message + +Clause-②: no +Metadata-protocol: none + +The database queue adapter's main loop (every per-message `subscribe()` queue: mail send, mail attachment reclaim, API-flow subscriptions) claimed each due row with a write matched by id alone. On a deployment with more than one node, two nodes that both read a row as `pending` both claimed it, the second overwriting the first's lease, and both ran it — a mail could be sent twice. The main loop now claims its candidate rows the way the batch path already does: one `multi: true` write over the 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 loser of a row matches nothing and does not run it. Pacing is unchanged: at most `batchSize` messages per `pollIntervalMs` tick, each handed to its handler alone. No configuration change is needed. diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md index 6b212481cd7..f81dee8ce43 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 13 | -| Object name statically decidable | 13 | +| Write call sites | 12 | +| Object name statically decidable | 12 | | Object name chosen at run time | 0 | | Object name spelled inline | 0 | -| Object name spelled through a `const` | 13 | +| Object name spelled through a `const` | 12 | | Object name is an `object: string` parameter | 0 | | Object name is some other run-time expression | 0 | -| Against a tenancy-enabled object | 13 | +| Against a tenancy-enabled object | 12 | | Against an object declaring tenancy off | 0 | -| Threading a tenant context | 13 | +| Threading a tenant context | 12 | | Provably carrying none (options read, no context key) | 0 | | …and decidably tenancy-enabled | 0 | | Options argument unreadable | 0 | | …and decidably tenancy-enabled | 0 | | Threading a decidably elevated (`isSystem`) context | 0 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 13 | -| Receiver carried a readable engine type | 13 | +| Threading a context of undecidable elevation | 12 | +| Receiver carried a readable engine type | 12 | | Receiver erased, placed by the object NAME | 0 | | Receiver erased, placed by an `object: string` PARAMETER | 0 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 | @@ -49,4 +49,4 @@ a row or a number here — fix the code, or the census, and regenerate. |---|---|---|---|---|---:| | `packages/services/service-queue/src/db-queue-adapter.ts` | `delete` | `sys_job_queue` | enabled | context, elevation undecidable | 2 | | `packages/services/service-queue/src/db-queue-adapter.ts` | `insert` | `sys_job_queue` | enabled | context, elevation undecidable | 1 | -| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 10 | +| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 9 | diff --git a/packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts b/packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts index f802f627da5..028c7cc0812 100644 --- a/packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts +++ b/packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts @@ -17,7 +17,7 @@ // reclaimed rather than orphaned. import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { assertEngineDeleteDispatch } from '@objectstack/objectql'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; import { DbQueueAdapter } from '@objectstack/service-queue'; import { EmailServicePlugin } from './email-plugin.js'; import type { EmailService } from './email-service.js'; @@ -57,6 +57,8 @@ function fakeEngine() { if (op === '$lt') return row[k] < (target as any); // NULL-safe like SQL: a row with no value never satisfies `$lte`. if (op === '$lte') return row[k] != null && row[k] <= (target as any); + // [#38578] `$in` — the claim write's id set (`id: { $in: ids }`). + if (op === '$in') return (target as unknown[]).includes(row[k]); throw new Error(`fakeEngine: unsupported operator ${op}`); }); } @@ -92,7 +94,17 @@ function fakeEngine() { for (const fn of hooks.afterInsert ?? []) await fn({ object: table, result: row }); return { id: data.id }; }, - async update(table: string, patch: any) { + async update(table: string, patch: any, options?: any) { + // [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the + // queue's claim, settle and lease writes are predicate writes + // (`multi: true`) that rewrite the rows their `where` matches and report + // how many — a by-id-only double turns them unconditional or refuses them. + const dispatch = assertEngineUpdateDispatch(patch, options); + if (dispatch.kind === 'multi') { + const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {})); + for (const x of hit) Object.assign(x, patch); + return hit.length; + } const r = rowsOf(table).find((x) => x.id === patch.id); if (!r) throw new Error(`row ${patch.id} not found in ${table}`); Object.assign(r, patch); diff --git a/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts b/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts index 1c7273ddd16..e55bf3b15be 100644 --- a/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts +++ b/packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts @@ -13,7 +13,7 @@ // round trip: sweep → job → worker poll → the same row at `sent`. import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { assertEngineDeleteDispatch } from '@objectstack/objectql'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; import { DbQueueAdapter } from '@objectstack/service-queue'; import { LiteKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; @@ -68,6 +68,8 @@ function fakeEngine(opts: EngineOpts = {}) { if (op === '$lt') return row[k] < (target as any); // NULL-safe like SQL: a row with no value never satisfies `$lte`. if (op === '$lte') return row[k] != null && row[k] <= (target as any); + // [#38578] `$in` — the claim write's id set (`id: { $in: ids }`). + if (op === '$in') return (target as unknown[]).includes(row[k]); throw new Error(`fakeEngine: unsupported operator ${op}`); }); } @@ -116,7 +118,17 @@ function fakeEngine(opts: EngineOpts = {}) { for (const fn of hooks.afterInsert ?? []) await fn({ object: table, result: row }); return { id: row.id }; }, - async update(table: string, patch: any) { + async update(table: string, patch: any, options?: any) { + // [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the + // queue's claim, settle and lease writes are predicate writes + // (`multi: true`) that rewrite the rows their `where` matches and report + // how many — a by-id-only double turns them unconditional or refuses them. + const dispatch = assertEngineUpdateDispatch(patch, options); + if (dispatch.kind === 'multi') { + const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {})); + for (const x of hit) Object.assign(x, patch); + return hit.length; + } const r = rowsOf(table).find((x) => x.id === patch.id); if (!r) throw new Error(`row ${patch.id} not found in ${table}`); Object.assign(r, patch); diff --git a/packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts b/packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts index ea4cc6b9a5d..5545bd3fa87 100644 --- a/packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts +++ b/packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts @@ -12,7 +12,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { createMemoryQueue } from '@objectstack/core'; -import { assertEngineDeleteDispatch } from '@objectstack/objectql'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql'; import { DbQueueAdapter } from '@objectstack/service-queue'; import { EmailServicePlugin, resolveDurableQueue } from './email-plugin.js'; import { EmailService, EMAIL_SEND_QUEUE, LogTransport } from './email-service.js'; @@ -72,6 +72,8 @@ function fakeEngine() { return Object.entries(v).every(([op, target]) => { // NULL-safe like SQL: a row with no value never satisfies `$lte`. if (op === '$lte') return row[k] != null && row[k] <= (target as any); + // [#38578] `$in` — the claim write's id set (`id: { $in: ids }`). + if (op === '$in') return (target as unknown[]).includes(row[k]); throw new Error(`fakeEngine: unsupported operator ${op}`); }); } @@ -105,7 +107,17 @@ function fakeEngine() { tables.set(table, t); return { id: data.id }; }, - async update(table: string, patch: any) { + async update(table: string, patch: any, options?: any) { + // [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the + // queue's claim, settle and lease writes are predicate writes + // (`multi: true`) that rewrite the rows their `where` matches and report + // how many — a by-id-only double turns them unconditional or refuses them. + const dispatch = assertEngineUpdateDispatch(patch, options); + if (dispatch.kind === 'multi') { + const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {})); + for (const x of hit) Object.assign(x, patch); + return hit.length; + } const r = rowsOf(table).find((x) => x.id === patch.id); if (!r) throw new Error(`row ${patch.id} not found in ${table}`); Object.assign(r, patch); diff --git a/packages/services/service-queue/src/db-queue-adapter.test.ts b/packages/services/service-queue/src/db-queue-adapter.test.ts index 5eb3e7b5edd..d4668174722 100644 --- a/packages/services/service-queue/src/db-queue-adapter.test.ts +++ b/packages/services/service-queue/src/db-queue-adapter.test.ts @@ -876,23 +876,51 @@ describe('DbQueueAdapter — the batch path claims and settles with set writes', expect(rowsOf(engine, 'kb').every((r) => r.status === 'completed')).toBe(true); }); - it('CONTROL — the main loop\'s claim, matched by id alone and unchanged here, lets both adapters claim the rows they both read', async () => { - // The same race over the per-message path. It reproduces the double claim - // on the main loop, which this change leaves alone on purpose (per-message - // queues keep their behaviour and pacing); it also shows the harness above - // can produce the interleaving the batch-path case is safe against. + it('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', async () => { + // [#38578] The same race over the per-message path. Its claim used to be + // one write per row matched by id alone, and both adapters claimed and ran + // every row they both read (each message handled twice). It now takes the + // tick's rows with the batch path's claim: one write over the id set, + // matched on `pending` and due, so the loser of each row matches nothing. const engine = makeFakeEngine(); const a = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, workerId: 'node-a' } }); const b = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, workerId: 'node-b' } }); for (let i = 0; i < 5; i++) await a.publish('mail', { i }); const handled = new Map(); - const handler = async (m: { id: string }) => { handled.set(m.id, (handled.get(m.id) ?? 0) + 1); }; + const handlerCalls: number[] = []; + const handler = async (m: { id: string; data: unknown }) => { + handlerCalls.push((m.data as { i: number }).i); + handled.set(m.id, (handled.get(m.id) ?? 0) + 1); + }; await a.subscribe('mail', handler); await b.subscribe('mail', handler); + const writes = countWrites(engine); raceClaimReads(engine, 2); - await Promise.all([a.pollOnce(), b.pollOnce()]); + const [movedA, movedB] = await Promise.all([a.pollOnce(), b.pollOnce()]); + expect(movedA + movedB).toBe(5); expect(handled.size).toBe(5); - expect([...handled.values()]).toEqual([2, 2, 2, 2, 2]); + expect([...handled.values()]).toEqual([1, 1, 1, 1, 1]); + // One message per handler call, as before. + expect(handlerCalls).toHaveLength(5); + // One claim write per adapter tick, not one per row. + expect(writes.claim).toBe(2); + expect(rowsOf(engine, 'mail').every((r) => r.status === 'completed')).toBe(true); + }); + + it('the main loop keeps its pacing: at most batchSize messages per tick, in claim order', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, batchSize: 2 } }); + for (let i = 0; i < 5; i++) await adapter.publish('mail', { i }); + const seen: number[] = []; + await adapter.subscribe('mail', async (m: { data: unknown }) => { seen.push((m.data as { i: number }).i); }); + const writes = countWrites(engine); + + expect(await adapter.pollOnce()).toBe(2); + expect(await adapter.pollOnce()).toBe(2); + expect(await adapter.pollOnce()).toBe(1); + expect(await adapter.pollOnce()).toBe(0); + expect(seen).toEqual([0, 1, 2, 3, 4]); + expect(writes.claim).toBe(3); }); }); diff --git a/packages/services/service-queue/src/db-queue-adapter.ts b/packages/services/service-queue/src/db-queue-adapter.ts index 8ccbd94760a..097e5849d48 100644 --- a/packages/services/service-queue/src/db-queue-adapter.ts +++ b/packages/services/service-queue/src/db-queue-adapter.ts @@ -1042,49 +1042,32 @@ export class DbQueueAdapter implements IQueueService { /** * Claim up to `max` due rows of `queue` for the main loop's per-message - * dispatch, one claim write per row. + * dispatch. + * + * [#38578] The claim is the same compare-and-set as the batch path's + * ({@link claimCandidates}): ONE write over the candidate ids, matched on + * `status: 'pending'` and due as well as id. A claim matched by id alone + * let two nodes that both read a row as pending both claim it — the second + * write overwrote the first node's lease — and both dispatch it, so a + * per-message consumer (a mail send) ran twice. Pacing is unchanged: at + * most `max` rows per tick, each handed to its handler alone by + * {@link pollOnce}. */ private async claimBatch(queue: string, max: number): Promise { const now = this.now(); - const candidates = await this.readClaimCandidates(queue, max * 3, now); // over-fetch in case of CAS contention - - const out: any[] = []; - for (const row of candidates ?? []) { - if (out.length >= max) break; - if (!this.isClaimable(row, now.getTime())) continue; - - // CAS — only update if still pending (best-effort with engine.update which - // typically does row-level update by id; concurrent workers will overwrite - // each other but the dispatcher tolerates duplicate delivery via attempts). - try { - await this.engine.update(QUEUE_TABLE, { - id: row.id, - status: 'running', - locked_by: this.opts.workerId, - locked_until: new Date(now.getTime() + this.opts.leaseMs).toISOString(), - updated_at: now.toISOString(), - }, { context: SYSTEM_CTX }); - out.push({ ...row, status: 'running' }); - if (this.opts.soleWriter) this.unsettledLeases.set(String(row.id), now.getTime() + this.opts.leaseMs); - } catch (err) { - this.logger?.warn?.('DbQueueAdapter: claim CAS failed', err as any); - } - } - return out; + const nowMs = now.getTime(); + // The read over-fetches so rows {@link isClaimable} turns away do not + // shorten the tick; the write takes at most `max` of the rest. + const candidates = (await this.readClaimCandidates(queue, max * 3, now) ?? []) + .filter((row: any) => this.isClaimable(row, nowMs)) + .slice(0, max); + return this.claimCandidates(candidates, now, null, 'DbQueueAdapter: claim CAS failed'); } /** * [#38548] The batch path's claim ({@link pollBatchOnce}): up to `max` due - * rows of `queue`, taken with ONE compare-and-set write over their id set. - * - * The write is matched on the unclaimed state as well as the ids — - * `status: 'pending'` and due — so a row another adapter claimed between - * this read and this write matches nothing, and two nodes draining one - * store never both run it. (A claim matched by id alone overwrites the - * other node's lease and both dispatch the row.) It is a `multi: true` - * write for the reason {@link reclaimExpired} gives. When the store answers - * fewer matched rows than were asked for, one read of the ids this worker - * now holds says which rows it won. + * rows of `queue`, taken with ONE compare-and-set write over their id set + * ({@link claimCandidates}). * * `inFlight` receives every candidate id BEFORE the write, and keeps the * won ones: a sole writer's lease entry is recorded only after the write, so @@ -1095,13 +1078,46 @@ export class DbQueueAdapter implements IQueueService { private async claimSet(queue: string, max: number, inFlight: Set): Promise { const now = this.now(); const nowMs = now.getTime(); - const nowIsoText = now.toISOString(); const candidates = (await this.readClaimCandidates(queue, max, now) ?? []) .filter((row: any) => this.isClaimable(row, nowMs)) .slice(0, max); + return this.claimCandidates(candidates, now, inFlight, 'DbQueueAdapter: batch claim CAS failed'); + } + + /** + * [#38548][#38578] The claim write shared by {@link claimBatch} (main loop) + * and {@link claimSet} (batch path): take `candidates` with ONE + * compare-and-set write over their id set, and answer the rows won, in + * candidate order, marked `running`. + * + * The write is matched on the unclaimed state as well as the ids — + * `status: 'pending'` and due — so a row another adapter claimed between + * the candidate read and this write matches nothing, and two nodes draining + * one store never both run it. (A claim matched by id alone overwrites the + * other node's lease and both dispatch the row.) It is a `multi: true` + * write for the reason {@link reclaimExpired} gives. When the store answers + * fewer matched rows than were asked for, one read of the ids this worker + * now holds says which rows it won. + * + * A sole writer's lease entry ({@link unsettledLeases}) is recorded for won + * rows only, after the write; when the write fails it is recorded for every + * candidate, since a write that landed before the failure leaves rows + * `running` under this worker's lease and the sole writer reads again once + * that lease ends. `inFlight` (the batch path's) receives every candidate + * id before the write and keeps the won ones; the main loop passes none, + * as no reclaim runs while its own tick claims. + */ + private async claimCandidates( + candidates: any[], + now: Date, + inFlight: Set | null, + failureMessage: string, + ): Promise { if (candidates.length === 0) return []; + const nowMs = now.getTime(); + const nowIsoText = now.toISOString(); const ids = candidates.map((row: any) => String(row.id)); - for (const id of ids) inFlight.add(id); + if (inFlight) for (const id of ids) inFlight.add(id); const leaseUntilMs = nowMs + this.opts.leaseMs; let won: Set; @@ -1132,8 +1148,8 @@ export class DbQueueAdapter implements IQueueService { won = new Set((held ?? []).map((row: any) => String(row.id))); } } catch (err) { - this.logger?.warn?.('DbQueueAdapter: batch claim CAS failed', err as any); - for (const id of ids) inFlight.delete(id); + this.logger?.warn?.(failureMessage, err as any); + if (inFlight) for (const id of ids) inFlight.delete(id); // A write that landed before the failure leaves rows `running` under // this worker's lease; a sole writer reads again once that lease ends. if (this.opts.soleWriter) for (const id of ids) this.unsettledLeases.set(id, leaseUntilMs); @@ -1143,7 +1159,7 @@ export class DbQueueAdapter implements IQueueService { const out: any[] = []; for (const row of candidates) { const id = String(row.id); - if (!won.has(id)) { inFlight.delete(id); continue; } + if (!won.has(id)) { inFlight?.delete(id); continue; } out.push({ ...row, status: 'running' }); if (this.opts.soleWriter) this.unsettledLeases.set(id, leaseUntilMs); } diff --git a/packages/services/service-queue/src/job-queue-retention.test.ts b/packages/services/service-queue/src/job-queue-retention.test.ts index 75e567b2eb7..3801f72b9e7 100644 --- a/packages/services/service-queue/src/job-queue-retention.test.ts +++ b/packages/services/service-queue/src/job-queue-retention.test.ts @@ -26,7 +26,7 @@ // the engine. import { describe, it, expect, beforeEach } from 'vitest'; -import { assertEngineDeleteDispatch, LifecycleService } from '@objectstack/objectql'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, LifecycleService } from '@objectstack/objectql'; import { SysJobQueue } from '@objectstack/platform-objects/audit'; import { DbQueueAdapter, completedRetentionWindowMs } from './db-queue-adapter.js'; import { QueueServicePlugin } from './queue-service-plugin.js'; @@ -109,7 +109,17 @@ function makeFakeEngine() { tables.set(table, t); return { id: data.id }; }, - async update(table: string, patch: Row) { + async update(table: string, patch: Row, options?: any) { + // [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the + // queue's claim, settle and lease writes are predicate writes + // (`multi: true`) that rewrite the rows their `where` matches and report + // how many — a by-id-only double turns them unconditional or refuses them. + const dispatch = assertEngineUpdateDispatch(patch, options); + if (dispatch.kind === 'multi') { + const hit = (tables.get(table) ?? []).filter((x) => matches(x, options?.where ?? {})); + for (const x of hit) Object.assign(x, patch); + return hit.length; + } const r = (tables.get(table) ?? []).find((x) => x.id === patch.id); if (!r) throw new Error(`row ${patch.id} not found in ${table}`); Object.assign(r, patch); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index b786b2c981f..fc742809d5e 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -4431,16 +4431,31 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts", "verb": "delete", "pinned": 1 }, + { + "file": "packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts", "verb": "delete", "pinned": 1 }, + { + "file": "packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/plugins/plugin-email/src/email-plugin.template-runtime-write.test.ts", "verb": "update", @@ -6331,6 +6346,11 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/services/service-queue/src/job-queue-retention.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/services/service-settings/src/settings-engine-id-fold-wins.test.ts", "verb": "update",