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
14 changes: 14 additions & 0 deletions .changeset/38548-db-queue-batch-writes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/service-queue': patch
---

perf(service-queue): the database queue claims and settles a batch with set writes

Clause-②: no
Metadata-protocol: none

A queue consumed with `subscribeBatch` on the database adapter used to cost two single-row writes per message: one claim write and one settling write. It now claims each batch with one compare-and-set write over the selected ids, and marks the completed messages done with one write (one per attempt count when retried messages are mixed in). Draining 50,000 messages on a local SQLite store went from 100,000 queue writes to 1,000, and from about 64 s to about 8 s; on a remote store the saving is a network round trip per write.

The claim now matches the rows' unclaimed state as well as their ids. Before, two nodes draining the same batch queue could both claim a message they had both read as pending, and both ran it. Now the second node's write matches nothing and each message is handled once.

A failed message still settles alone: it keeps its own error, its own backoff and its own dead letter. A settling write for a message whose lease was lost while the handler ran no longer overwrites the state its new holder gave it. Per-message queues (`subscribe`) are unchanged.
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 | 11 |
| Object name statically decidable | 11 |
| Write call sites | 13 |
| Object name statically decidable | 13 |
| Object name chosen at run time | 0 |
| Object name spelled inline | 0 |
| Object name spelled through a `const` | 11 |
| Object name spelled through a `const` | 13 |
| Object name is an `object: string` parameter | 0 |
| Object name is some other run-time expression | 0 |
| Against a tenancy-enabled object | 11 |
| Against a tenancy-enabled object | 13 |
| Against an object declaring tenancy off | 0 |
| Threading a tenant context | 11 |
| Threading a tenant context | 13 |
| 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 | 11 |
| Receiver carried a readable engine type | 11 |
| Threading a context of undecidable elevation | 13 |
| Receiver carried a readable engine type | 13 |
| 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 | 8 |
| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 10 |
173 changes: 163 additions & 10 deletions packages/services/service-queue/src/db-queue-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,16 @@ function makeFakeEngine() {
tables.set(table, t);
return { id: data.id };
},
async update(table: string, patch: any) {
async update(table: string, patch: any, options?: any) {
// A predicate write (`multi: true`) rewrites the rows its `where`
// matches and reports how many — the compare-and-set the batch claim,
// the batch settle and the lease renewal ride on; a by-id write is
// unconditional, as the engine's by-id path is.
if (options?.multi) {
const hit = (tables.get(table) ?? []).filter((r) => matches(r, options.where ?? {}));
for (const r of hit) Object.assign(r, patch);
return hit.length;
}
const r = row(table, patch.id);
if (!r) throw new Error(`row ${patch.id} not found in ${table}`);
Object.assign(r, patch);
Expand Down Expand Up @@ -630,8 +639,9 @@ describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => {
const renewals: any[] = [];
const inner = engine.update.bind(engine);
engine.update = async (table: string, patch: any, opts?: any) => {
if (opts?.multi) { renewals.push(opts.where); return 3; }
return inner(table, patch);
// A renewal moves no status; the batch claim and settle do.
if (opts?.multi && patch?.status === undefined) { renewals.push(opts.where); return 3; }
return inner(table, patch, opts);
};
await adapter.subscribeBatch('kb', async (messages) => {
await new Promise((r) => setTimeout(r, 60));
Expand Down Expand Up @@ -711,9 +721,9 @@ describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => {
const inner = engine.update.bind(engine);
let claims = 0;
engine.update = async (table: string, patch: any, opts?: any) => {
// The second claim write: a main-loop reclaim runs its read meanwhile.
if (!opts?.multi && patch?.status === 'running' && ++claims === 2) await internals.reclaimExpired();
return inner(table, patch);
// The batch's one claim write: a main-loop reclaim runs its read meanwhile.
if (patch?.status === 'running') { claims++; await internals.reclaimExpired(); }
return inner(table, patch, opts);
};
const heldDuringBatch: boolean[] = [];
await adapter.subscribeBatch('kb', async (messages) => {
Expand All @@ -722,7 +732,7 @@ describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => {
}, { maxBatch: 10 });

expect(await adapter.pollBatchOnce('kb')).toBe(3);
expect(claims).toBe(3);
expect(claims).toBe(1);
expect(heldDuringBatch).toEqual([true, true, true]);
expect(internals.unsettledLeases.size).toBe(0);
});
Expand All @@ -733,13 +743,156 @@ describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => {
for (let i = 0; i < 3; i++) await adapter.publish('kb', { i });
const second = rowsOf(engine, 'kb')[1]!.id;
const inner = engine.update.bind(engine);
engine.update = async (table: string, patch: any) => {
if (patch?.status === 'completed' && patch.id === second) throw new Error('write refused');
return inner(table, patch);
engine.update = async (table: string, patch: any, opts?: any) => {
// The completed set's one write is refused, and so is the second row's
// own write when the batch falls back to settling each row.
if (patch?.status === 'completed' && (opts?.multi || patch.id === second)) throw new Error('write refused');
return inner(table, patch, opts);
};
await adapter.subscribeBatch('kb', async (messages) => messages.map(() => ({ ok: true as const })), { maxBatch: 10 });

await adapter.pollBatchOnce('kb');
expect(rowsOf(engine, 'kb').map((r) => r.status)).toEqual(['completed', 'running', 'completed']);
});
});

/**
* The batch path's claim and settle writes (the database queue's batch loop).
*
* A batch used to cost two single-row writes per message: one claim write per
* row, matched by id alone, and one settling write per row. On a remote store
* that is two sequential round trips per message, and a claim matched by id
* alone lets two adapters over one store both claim a row they both read as
* pending. The batch path now claims its rows with ONE compare-and-set write
* over the id set, matched on the unclaimed state too, and settles its
* completed rows with one write per attempt count, matched as the lease
* renewal is. A failed row still settles alone: its own backoff, its own
* error, its own dead letter.
*/
describe('DbQueueAdapter — the batch path claims and settles with set writes', () => {
const QUEUE = 'sys_job_queue';
const rowsOf = (engine: ReturnType<typeof makeFakeEngine>, queue: string) =>
(engine.tables.get(QUEUE) ?? []).filter((r) => r.queue === queue);

/** Tallies the queue's writes by what they do: claim, settle, or renew (a write that moves no status). */
function countWrites(engine: ReturnType<typeof makeFakeEngine>) {
const writes = { claim: 0, settle: 0, renew: 0 };
const inner = engine.update.bind(engine);
engine.update = async (table: string, patch: any, opts?: any) => {
if (table === QUEUE) {
if (patch?.status === 'running') writes.claim++;
else if (patch?.status === undefined) writes.renew++;
else writes.settle++;
}
return inner(table, patch, opts);
};
return writes;
}

/**
* Holds every claim read (the due `pending` candidate read) until `parties`
* adapters have made theirs, so they all read the same rows before any of
* them writes — the interleaving two nodes draining one store at once can
* meet. Each read answers copies, as a driver answers rows, not the stored
* objects a later write mutates.
*/
function raceClaimReads(engine: ReturnType<typeof makeFakeEngine>, parties: number) {
const inner = engine.find.bind(engine);
const waiting: Array<() => void> = [];
let armed = true;
engine.find = async (table: string, opts: any = {}) => {
const rows = (await inner(table, opts)).map((r: any) => ({ ...r }));
if (armed && table === QUEUE && opts?.where?.status === 'pending' && opts?.where?.$or) {
await new Promise<void>((resolve) => {
waiting.push(resolve);
if (waiting.length === parties) {
armed = false;
for (const go of waiting) go();
}
});
}
return rows;
};
}

it('drains N batch messages with O(N / maxBatch) claim and settle writes, not 2N', async () => {
const engine = makeFakeEngine();
const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000 } });
for (let i = 0; i < 250; i++) await adapter.publish('kb', { i });
const writes = countWrites(engine);
await adapter.subscribeBatch('kb', async (messages) => messages.map(() => ({ ok: true as const })), { maxBatch: 100 });

expect(await adapter.pollBatchOnce('kb')).toBe(100);
expect(await adapter.pollBatchOnce('kb')).toBe(100);
expect(await adapter.pollBatchOnce('kb')).toBe(50);
expect(await adapter.pollBatchOnce('kb')).toBe(0);

expect(rowsOf(engine, 'kb').every((r) => r.status === 'completed' && r.attempts === 1 && r.locked_by === null)).toBe(true);
// One claim write and one settle write per batch of 100: 3 + 3, where the
// per-row writes were 250 + 250.
expect(writes).toEqual({ claim: 3, settle: 3, renew: 0 });
});

it('a failed row still settles alone, and completed rows settle with the attempt count each one reached', async () => {
const engine = makeFakeEngine();
const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, defaultMaxAttempts: 3 } });
for (let i = 0; i < 6; i++) await adapter.publish('kb', { i });
const byI = (i: number) => rowsOf(engine, 'kb').find((r) => JSON.parse(r.payload_json).i === i)!;
// Message 5 already failed once: it completes on its second attempt.
byI(5).attempts = 1;
const writes = countWrites(engine);
await adapter.subscribeBatch('kb', async (messages) =>
messages.map((m) => ((m.data as { i: number }).i === 2 ? { ok: false as const, error: new Error('poisoned') } : { ok: true as const })),
{ maxBatch: 10 });

expect(await adapter.pollBatchOnce('kb')).toBe(6);
expect([0, 1, 3, 4].map((i) => [byI(i).status, byI(i).attempts])).toEqual([
['completed', 1], ['completed', 1], ['completed', 1], ['completed', 1],
]);
expect([byI(5).status, byI(5).attempts]).toEqual(['completed', 2]);
expect([byI(2).status, byI(2).attempts, byI(2).last_error, byI(2).locked_by]).toEqual(['pending', 1, 'poisoned', null]);
// One claim; completed rows by attempt count (1 and 2); the failed row alone.
expect(writes).toEqual({ claim: 1, settle: 3, renew: 0 });
});

it('two adapters over one store that read the same pending rows hand each batch message to one handler call', async () => {
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 < 20; i++) await a.publish('kb', { i });
const handled = new Map<string, number>();
const handler = async (messages: Array<{ id: string }>) => {
for (const m of messages) handled.set(m.id, (handled.get(m.id) ?? 0) + 1);
return messages.map(() => ({ ok: true as const }));
};
await a.subscribeBatch('kb', handler, { maxBatch: 50 });
await b.subscribeBatch('kb', handler, { maxBatch: 50 });
raceClaimReads(engine, 2);

const [claimedA, claimedB] = await Promise.all([a.pollBatchOnce('kb'), b.pollBatchOnce('kb')]);
expect(claimedA + claimedB).toBe(20);
expect(handled.size).toBe(20);
expect([...handled.values()].every((n) => n === 1)).toBe(true);
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.
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); };
await a.subscribe('mail', handler);
await b.subscribe('mail', handler);
raceClaimReads(engine, 2);

await Promise.all([a.pollOnce(), b.pollOnce()]);
expect(handled.size).toBe(5);
expect([...handled.values()]).toEqual([2, 2, 2, 2, 2]);
});
});
Loading
Loading