Skip to content

Commit 00f97b3

Browse files
fix(service-queue): the database queue main loop claims with one compare-and-set write (#38820)
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 #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>
1 parent 4d9d12a commit 00f97b3

9 files changed

Lines changed: 185 additions & 65 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-queue': patch
3+
---
4+
5+
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
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.

‎docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate.
1414

1515
| Measure | Value |
1616
|---|---:|
17-
| Write call sites | 13 |
18-
| Object name statically decidable | 13 |
17+
| Write call sites | 12 |
18+
| Object name statically decidable | 12 |
1919
| Object name chosen at run time | 0 |
2020
| Object name spelled inline | 0 |
21-
| Object name spelled through a `const` | 13 |
21+
| Object name spelled through a `const` | 12 |
2222
| Object name is an `object: string` parameter | 0 |
2323
| Object name is some other run-time expression | 0 |
24-
| Against a tenancy-enabled object | 13 |
24+
| Against a tenancy-enabled object | 12 |
2525
| Against an object declaring tenancy off | 0 |
26-
| Threading a tenant context | 13 |
26+
| Threading a tenant context | 12 |
2727
| Provably carrying none (options read, no context key) | 0 |
2828
| …and decidably tenancy-enabled | 0 |
2929
| Options argument unreadable | 0 |
3030
| …and decidably tenancy-enabled | 0 |
3131
| Threading a decidably elevated (`isSystem`) context | 0 |
3232
| Threading a decidably non-elevated context | 0 |
33-
| Threading a context of undecidable elevation | 13 |
34-
| Receiver carried a readable engine type | 13 |
33+
| Threading a context of undecidable elevation | 12 |
34+
| Receiver carried a readable engine type | 12 |
3535
| Receiver erased, placed by the object NAME | 0 |
3636
| Receiver erased, placed by an `object: string` PARAMETER | 0 |
3737
| 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.
4949
|---|---|---|---|---|---:|
5050
| `packages/services/service-queue/src/db-queue-adapter.ts` | `delete` | `sys_job_queue` | enabled | context, elevation undecidable | 2 |
5151
| `packages/services/service-queue/src/db-queue-adapter.ts` | `insert` | `sys_job_queue` | enabled | context, elevation undecidable | 1 |
52-
| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 10 |
52+
| `packages/services/service-queue/src/db-queue-adapter.ts` | `update` | `sys_job_queue` | enabled | context, elevation undecidable | 9 |

‎packages/plugins/plugin-email/src/email-plugin.attachment-storage.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
// reclaimed rather than orphaned.
1818

1919
import { describe, it, expect, vi, beforeEach } from 'vitest';
20-
import { assertEngineDeleteDispatch } from '@objectstack/objectql';
20+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql';
2121
import { DbQueueAdapter } from '@objectstack/service-queue';
2222
import { EmailServicePlugin } from './email-plugin.js';
2323
import type { EmailService } from './email-service.js';
@@ -57,6 +57,8 @@ function fakeEngine() {
5757
if (op === '$lt') return row[k] < (target as any);
5858
// NULL-safe like SQL: a row with no value never satisfies `$lte`.
5959
if (op === '$lte') return row[k] != null && row[k] <= (target as any);
60+
// [#38578] `$in` — the claim write's id set (`id: { $in: ids }`).
61+
if (op === '$in') return (target as unknown[]).includes(row[k]);
6062
throw new Error(`fakeEngine: unsupported operator ${op}`);
6163
});
6264
}
@@ -92,7 +94,17 @@ function fakeEngine() {
9294
for (const fn of hooks.afterInsert ?? []) await fn({ object: table, result: row });
9395
return { id: data.id };
9496
},
95-
async update(table: string, patch: any) {
97+
async update(table: string, patch: any, options?: any) {
98+
// [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the
99+
// queue's claim, settle and lease writes are predicate writes
100+
// (`multi: true`) that rewrite the rows their `where` matches and report
101+
// how many — a by-id-only double turns them unconditional or refuses them.
102+
const dispatch = assertEngineUpdateDispatch(patch, options);
103+
if (dispatch.kind === 'multi') {
104+
const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {}));
105+
for (const x of hit) Object.assign(x, patch);
106+
return hit.length;
107+
}
96108
const r = rowsOf(table).find((x) => x.id === patch.id);
97109
if (!r) throw new Error(`row ${patch.id} not found in ${table}`);
98110
Object.assign(r, patch);

‎packages/plugins/plugin-email/src/email-plugin.outbox-sweep.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// round trip: sweep → job → worker poll → the same row at `sent`.
1414

1515
import { describe, it, expect, vi, beforeEach } from 'vitest';
16-
import { assertEngineDeleteDispatch } from '@objectstack/objectql';
16+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql';
1717
import { DbQueueAdapter } from '@objectstack/service-queue';
1818
import { LiteKernel } from '@objectstack/core';
1919
import type { Plugin, PluginContext } from '@objectstack/core';
@@ -68,6 +68,8 @@ function fakeEngine(opts: EngineOpts = {}) {
6868
if (op === '$lt') return row[k] < (target as any);
6969
// NULL-safe like SQL: a row with no value never satisfies `$lte`.
7070
if (op === '$lte') return row[k] != null && row[k] <= (target as any);
71+
// [#38578] `$in` — the claim write's id set (`id: { $in: ids }`).
72+
if (op === '$in') return (target as unknown[]).includes(row[k]);
7173
throw new Error(`fakeEngine: unsupported operator ${op}`);
7274
});
7375
}
@@ -116,7 +118,17 @@ function fakeEngine(opts: EngineOpts = {}) {
116118
for (const fn of hooks.afterInsert ?? []) await fn({ object: table, result: row });
117119
return { id: row.id };
118120
},
119-
async update(table: string, patch: any) {
121+
async update(table: string, patch: any, options?: any) {
122+
// [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the
123+
// queue's claim, settle and lease writes are predicate writes
124+
// (`multi: true`) that rewrite the rows their `where` matches and report
125+
// how many — a by-id-only double turns them unconditional or refuses them.
126+
const dispatch = assertEngineUpdateDispatch(patch, options);
127+
if (dispatch.kind === 'multi') {
128+
const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {}));
129+
for (const x of hit) Object.assign(x, patch);
130+
return hit.length;
131+
}
120132
const r = rowsOf(table).find((x) => x.id === patch.id);
121133
if (!r) throw new Error(`row ${patch.id} not found in ${table}`);
122134
Object.assign(r, patch);

‎packages/plugins/plugin-email/src/email-plugin.queue-delivery.test.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
import { describe, it, expect, vi, beforeEach } from 'vitest';
1414
import { createMemoryQueue } from '@objectstack/core';
15-
import { assertEngineDeleteDispatch } from '@objectstack/objectql';
15+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/objectql';
1616
import { DbQueueAdapter } from '@objectstack/service-queue';
1717
import { EmailServicePlugin, resolveDurableQueue } from './email-plugin.js';
1818
import { EmailService, EMAIL_SEND_QUEUE, LogTransport } from './email-service.js';
@@ -72,6 +72,8 @@ function fakeEngine() {
7272
return Object.entries(v).every(([op, target]) => {
7373
// NULL-safe like SQL: a row with no value never satisfies `$lte`.
7474
if (op === '$lte') return row[k] != null && row[k] <= (target as any);
75+
// [#38578] `$in` — the claim write's id set (`id: { $in: ids }`).
76+
if (op === '$in') return (target as unknown[]).includes(row[k]);
7577
throw new Error(`fakeEngine: unsupported operator ${op}`);
7678
});
7779
}
@@ -105,7 +107,17 @@ function fakeEngine() {
105107
tables.set(table, t);
106108
return { id: data.id };
107109
},
108-
async update(table: string, patch: any) {
110+
async update(table: string, patch: any, options?: any) {
111+
// [#38578] Opened with ObjectQL.update's OWN dispatch predicate: the
112+
// queue's claim, settle and lease writes are predicate writes
113+
// (`multi: true`) that rewrite the rows their `where` matches and report
114+
// how many — a by-id-only double turns them unconditional or refuses them.
115+
const dispatch = assertEngineUpdateDispatch(patch, options);
116+
if (dispatch.kind === 'multi') {
117+
const hit = rowsOf(table).filter((x) => matches(x, options?.where ?? {}));
118+
for (const x of hit) Object.assign(x, patch);
119+
return hit.length;
120+
}
109121
const r = rowsOf(table).find((x) => x.id === patch.id);
110122
if (!r) throw new Error(`row ${patch.id} not found in ${table}`);
111123
Object.assign(r, patch);

‎packages/services/service-queue/src/db-queue-adapter.test.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -876,23 +876,51 @@ describe('DbQueueAdapter — the batch path claims and settles with set writes',
876876
expect(rowsOf(engine, 'kb').every((r) => r.status === 'completed')).toBe(true);
877877
});
878878

879-
it('CONTROL — the main loop\'s claim, matched by id alone and unchanged here, lets both adapters claim the rows they both read', async () => {
880-
// The same race over the per-message path. It reproduces the double claim
881-
// on the main loop, which this change leaves alone on purpose (per-message
882-
// queues keep their behaviour and pacing); it also shows the harness above
883-
// can produce the interleaving the batch-path case is safe against.
879+
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 () => {
880+
// [#38578] The same race over the per-message path. Its claim used to be
881+
// one write per row matched by id alone, and both adapters claimed and ran
882+
// every row they both read (each message handled twice). It now takes the
883+
// tick's rows with the batch path's claim: one write over the id set,
884+
// matched on `pending` and due, so the loser of each row matches nothing.
884885
const engine = makeFakeEngine();
885886
const a = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, workerId: 'node-a' } });
886887
const b = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, workerId: 'node-b' } });
887888
for (let i = 0; i < 5; i++) await a.publish('mail', { i });
888889
const handled = new Map<string, number>();
889-
const handler = async (m: { id: string }) => { handled.set(m.id, (handled.get(m.id) ?? 0) + 1); };
890+
const handlerCalls: number[] = [];
891+
const handler = async (m: { id: string; data: unknown }) => {
892+
handlerCalls.push((m.data as { i: number }).i);
893+
handled.set(m.id, (handled.get(m.id) ?? 0) + 1);
894+
};
890895
await a.subscribe('mail', handler);
891896
await b.subscribe('mail', handler);
897+
const writes = countWrites(engine);
892898
raceClaimReads(engine, 2);
893899

894-
await Promise.all([a.pollOnce(), b.pollOnce()]);
900+
const [movedA, movedB] = await Promise.all([a.pollOnce(), b.pollOnce()]);
901+
expect(movedA + movedB).toBe(5);
895902
expect(handled.size).toBe(5);
896-
expect([...handled.values()]).toEqual([2, 2, 2, 2, 2]);
903+
expect([...handled.values()]).toEqual([1, 1, 1, 1, 1]);
904+
// One message per handler call, as before.
905+
expect(handlerCalls).toHaveLength(5);
906+
// One claim write per adapter tick, not one per row.
907+
expect(writes.claim).toBe(2);
908+
expect(rowsOf(engine, 'mail').every((r) => r.status === 'completed')).toBe(true);
909+
});
910+
911+
it('the main loop keeps its pacing: at most batchSize messages per tick, in claim order', async () => {
912+
const engine = makeFakeEngine();
913+
const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 600_000, batchSize: 2 } });
914+
for (let i = 0; i < 5; i++) await adapter.publish('mail', { i });
915+
const seen: number[] = [];
916+
await adapter.subscribe('mail', async (m: { data: unknown }) => { seen.push((m.data as { i: number }).i); });
917+
const writes = countWrites(engine);
918+
919+
expect(await adapter.pollOnce()).toBe(2);
920+
expect(await adapter.pollOnce()).toBe(2);
921+
expect(await adapter.pollOnce()).toBe(1);
922+
expect(await adapter.pollOnce()).toBe(0);
923+
expect(seen).toEqual([0, 1, 2, 3, 4]);
924+
expect(writes.claim).toBe(3);
897925
});
898926
});

‎packages/services/service-queue/src/db-queue-adapter.ts‎

Lines changed: 57 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,49 +1042,32 @@ export class DbQueueAdapter implements IQueueService {
10421042

10431043
/**
10441044
* Claim up to `max` due rows of `queue` for the main loop's per-message
1045-
* dispatch, one claim write per row.
1045+
* dispatch.
1046+
*
1047+
* [#38578] The claim is the same compare-and-set as the batch path's
1048+
* ({@link claimCandidates}): ONE write over the candidate ids, matched on
1049+
* `status: 'pending'` and due as well as id. A claim matched by id alone
1050+
* let two nodes that both read a row as pending both claim it — the second
1051+
* write overwrote the first node's lease — and both dispatch it, so a
1052+
* per-message consumer (a mail send) ran twice. Pacing is unchanged: at
1053+
* most `max` rows per tick, each handed to its handler alone by
1054+
* {@link pollOnce}.
10461055
*/
10471056
private async claimBatch(queue: string, max: number): Promise<any[]> {
10481057
const now = this.now();
1049-
const candidates = await this.readClaimCandidates(queue, max * 3, now); // over-fetch in case of CAS contention
1050-
1051-
const out: any[] = [];
1052-
for (const row of candidates ?? []) {
1053-
if (out.length >= max) break;
1054-
if (!this.isClaimable(row, now.getTime())) continue;
1055-
1056-
// CAS — only update if still pending (best-effort with engine.update which
1057-
// typically does row-level update by id; concurrent workers will overwrite
1058-
// each other but the dispatcher tolerates duplicate delivery via attempts).
1059-
try {
1060-
await this.engine.update(QUEUE_TABLE, {
1061-
id: row.id,
1062-
status: 'running',
1063-
locked_by: this.opts.workerId,
1064-
locked_until: new Date(now.getTime() + this.opts.leaseMs).toISOString(),
1065-
updated_at: now.toISOString(),
1066-
}, { context: SYSTEM_CTX });
1067-
out.push({ ...row, status: 'running' });
1068-
if (this.opts.soleWriter) this.unsettledLeases.set(String(row.id), now.getTime() + this.opts.leaseMs);
1069-
} catch (err) {
1070-
this.logger?.warn?.('DbQueueAdapter: claim CAS failed', err as any);
1071-
}
1072-
}
1073-
return out;
1058+
const nowMs = now.getTime();
1059+
// The read over-fetches so rows {@link isClaimable} turns away do not
1060+
// shorten the tick; the write takes at most `max` of the rest.
1061+
const candidates = (await this.readClaimCandidates(queue, max * 3, now) ?? [])
1062+
.filter((row: any) => this.isClaimable(row, nowMs))
1063+
.slice(0, max);
1064+
return this.claimCandidates(candidates, now, null, 'DbQueueAdapter: claim CAS failed');
10741065
}
10751066

10761067
/**
10771068
* [#38548] The batch path's claim ({@link pollBatchOnce}): up to `max` due
1078-
* rows of `queue`, taken with ONE compare-and-set write over their id set.
1079-
*
1080-
* The write is matched on the unclaimed state as well as the ids —
1081-
* `status: 'pending'` and due — so a row another adapter claimed between
1082-
* this read and this write matches nothing, and two nodes draining one
1083-
* store never both run it. (A claim matched by id alone overwrites the
1084-
* other node's lease and both dispatch the row.) It is a `multi: true`
1085-
* write for the reason {@link reclaimExpired} gives. When the store answers
1086-
* fewer matched rows than were asked for, one read of the ids this worker
1087-
* now holds says which rows it won.
1069+
* rows of `queue`, taken with ONE compare-and-set write over their id set
1070+
* ({@link claimCandidates}).
10881071
*
10891072
* `inFlight` receives every candidate id BEFORE the write, and keeps the
10901073
* won ones: a sole writer's lease entry is recorded only after the write, so
@@ -1095,13 +1078,46 @@ export class DbQueueAdapter implements IQueueService {
10951078
private async claimSet(queue: string, max: number, inFlight: Set<string>): Promise<any[]> {
10961079
const now = this.now();
10971080
const nowMs = now.getTime();
1098-
const nowIsoText = now.toISOString();
10991081
const candidates = (await this.readClaimCandidates(queue, max, now) ?? [])
11001082
.filter((row: any) => this.isClaimable(row, nowMs))
11011083
.slice(0, max);
1084+
return this.claimCandidates(candidates, now, inFlight, 'DbQueueAdapter: batch claim CAS failed');
1085+
}
1086+
1087+
/**
1088+
* [#38548][#38578] The claim write shared by {@link claimBatch} (main loop)
1089+
* and {@link claimSet} (batch path): take `candidates` with ONE
1090+
* compare-and-set write over their id set, and answer the rows won, in
1091+
* candidate order, marked `running`.
1092+
*
1093+
* The write is matched on the unclaimed state as well as the ids —
1094+
* `status: 'pending'` and due — so a row another adapter claimed between
1095+
* the candidate read and this write matches nothing, and two nodes draining
1096+
* one store never both run it. (A claim matched by id alone overwrites the
1097+
* other node's lease and both dispatch the row.) It is a `multi: true`
1098+
* write for the reason {@link reclaimExpired} gives. When the store answers
1099+
* fewer matched rows than were asked for, one read of the ids this worker
1100+
* now holds says which rows it won.
1101+
*
1102+
* A sole writer's lease entry ({@link unsettledLeases}) is recorded for won
1103+
* rows only, after the write; when the write fails it is recorded for every
1104+
* candidate, since a write that landed before the failure leaves rows
1105+
* `running` under this worker's lease and the sole writer reads again once
1106+
* that lease ends. `inFlight` (the batch path's) receives every candidate
1107+
* id before the write and keeps the won ones; the main loop passes none,
1108+
* as no reclaim runs while its own tick claims.
1109+
*/
1110+
private async claimCandidates(
1111+
candidates: any[],
1112+
now: Date,
1113+
inFlight: Set<string> | null,
1114+
failureMessage: string,
1115+
): Promise<any[]> {
11021116
if (candidates.length === 0) return [];
1117+
const nowMs = now.getTime();
1118+
const nowIsoText = now.toISOString();
11031119
const ids = candidates.map((row: any) => String(row.id));
1104-
for (const id of ids) inFlight.add(id);
1120+
if (inFlight) for (const id of ids) inFlight.add(id);
11051121
const leaseUntilMs = nowMs + this.opts.leaseMs;
11061122

11071123
let won: Set<string>;
@@ -1132,8 +1148,8 @@ export class DbQueueAdapter implements IQueueService {
11321148
won = new Set((held ?? []).map((row: any) => String(row.id)));
11331149
}
11341150
} catch (err) {
1135-
this.logger?.warn?.('DbQueueAdapter: batch claim CAS failed', err as any);
1136-
for (const id of ids) inFlight.delete(id);
1151+
this.logger?.warn?.(failureMessage, err as any);
1152+
if (inFlight) for (const id of ids) inFlight.delete(id);
11371153
// A write that landed before the failure leaves rows `running` under
11381154
// this worker's lease; a sole writer reads again once that lease ends.
11391155
if (this.opts.soleWriter) for (const id of ids) this.unsettledLeases.set(id, leaseUntilMs);
@@ -1143,7 +1159,7 @@ export class DbQueueAdapter implements IQueueService {
11431159
const out: any[] = [];
11441160
for (const row of candidates) {
11451161
const id = String(row.id);
1146-
if (!won.has(id)) { inFlight.delete(id); continue; }
1162+
if (!won.has(id)) { inFlight?.delete(id); continue; }
11471163
out.push({ ...row, status: 'running' });
11481164
if (this.opts.soleWriter) this.unsettledLeases.set(id, leaseUntilMs);
11491165
}

0 commit comments

Comments
 (0)