Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/38578-db-queue-main-loop-cas.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 |
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}`);
});
}
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}`);
});
}
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}`);
});
}
Expand Down Expand Up @@ -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);
Expand Down
44 changes: 36 additions & 8 deletions packages/services/service-queue/src/db-queue-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number>();
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);
});
});
98 changes: 57 additions & 41 deletions packages/services/service-queue/src/db-queue-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any[]> {
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
Expand All @@ -1095,13 +1078,46 @@ export class DbQueueAdapter implements IQueueService {
private async claimSet(queue: string, max: number, inFlight: Set<string>): Promise<any[]> {
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<string> | null,
failureMessage: string,
): Promise<any[]> {
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<string>;
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down
Loading
Loading