diff --git a/.changeset/38548-db-queue-batch-writes.md b/.changeset/38548-db-queue-batch-writes.md new file mode 100644 index 00000000000..e62eb4528b7 --- /dev/null +++ b/.changeset/38548-db-queue-batch-writes.md @@ -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. 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 2a1ba6b06ea..6b212481cd7 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 | 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 | @@ -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 | 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 2e54018b24c..5eb3e7b5edd 100644 --- a/packages/services/service-queue/src/db-queue-adapter.test.ts +++ b/packages/services/service-queue/src/db-queue-adapter.test.ts @@ -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); @@ -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)); @@ -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) => { @@ -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); }); @@ -733,9 +743,11 @@ 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 }); @@ -743,3 +755,144 @@ describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => { 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, 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) { + 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, 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((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(); + 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(); + 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]); + }); +}); diff --git a/packages/services/service-queue/src/db-queue-adapter.ts b/packages/services/service-queue/src/db-queue-adapter.ts index e3ce2220bfa..8ccbd94760a 100644 --- a/packages/services/service-queue/src/db-queue-adapter.ts +++ b/packages/services/service-queue/src/db-queue-adapter.ts @@ -706,7 +706,7 @@ export class DbQueueAdapter implements IQueueService { if (!batch) return 0; // Each row is in flight from its claim on, so a main-loop reclaim whose // read was in flight during this claim keeps its lease entry. - const claimed = await this.claimBatch(queue, batch.maxBatch, this.batchInFlight); + const claimed = await this.claimSet(queue, batch.maxBatch, this.batchInFlight); if (claimed.length === 0) return 0; await this.dispatchBatch(batch, claimed); return claimed.length; @@ -985,16 +985,11 @@ export class DbQueueAdapter implements IQueueService { } /** - * Claim up to `max` due rows of `queue`. `inFlight`, when given (the batch - * path, {@link pollBatchOnce}), receives each row's id as it is claimed, - * before its sole-writer lease entry is recorded, so - * {@link reclaimExpired} never drops the entry of a row claimed while its - * read was in flight; {@link dispatchBatch} takes the ids out once the - * batch is settled. + * The claim read: up to `limit` due `pending` rows of `queue`, in claim + * order. Shared by {@link claimBatch} and {@link claimSet}. */ - private async claimBatch(queue: string, max: number, inFlight?: Set): Promise { - const now = this.now(); - const candidates = await this.engine.find(QUEUE_TABLE, { + private async readClaimCandidates(queue: string, limit: number, now: Date): Promise { + return this.engine.find(QUEUE_TABLE, { where: { queue, status: 'pending', @@ -1016,29 +1011,47 @@ export class DbQueueAdapter implements IQueueService { // `SqlOutboxStore.claim`'s `next_attempt_at` predicate. $or: [{ scheduled_for: null }, { scheduled_for: { $lte: now.toISOString() } }], }, - limit: max * 3, // over-fetch in case of CAS contention + limit, orderBy: [ { field: 'priority', order: 'asc' }, { field: 'scheduled_for', order: 'asc' }, ], context: SYSTEM_CTX, }); + } + + /** + * Whether a candidate row of {@link readClaimCandidates} may be claimed at + * `nowMs`. + * + * [#17612] Kept as the AUTHORITY on due-ness, not as a fallback for an + * engine that ignored the read's predicate. `scheduled_for` is a declared + * `Field.datetime`, and the dialects materialize it differently (canonical + * ISO text on SQLite/turso, a JS `Date` on Postgres/MySQL — the domain + * #13993 measured for `created_at` above); comparing INSTANTS here is what + * makes the verdict independent of that. The predicate decides WHICH rows + * `LIMIT` sees; this decides whether a row is due. + */ + private isClaimable(row: any, nowMs: number): boolean { + const sched = row.scheduled_for ? new Date(row.scheduled_for).getTime() : 0; + if (sched > nowMs) return false; + // Honor existing lease + const lockedUntil = row.locked_until ? new Date(row.locked_until).getTime() : 0; + return !(row.locked_by && lockedUntil > nowMs); + } + + /** + * Claim up to `max` due rows of `queue` for the main loop's per-message + * dispatch, one claim write per row. + */ + 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; - // [#17612] Kept as the AUTHORITY on due-ness, not as a fallback for an - // engine that ignored the predicate above. `scheduled_for` is a declared - // `Field.datetime`, and the dialects materialize it differently (canonical - // ISO text on SQLite/turso, a JS `Date` on Postgres/MySQL — the domain - // #13993 measured for `created_at` right above); comparing INSTANTS here - // is what makes the verdict independent of that. The predicate decides - // WHICH rows `LIMIT` sees; this decides whether a row is due. - const sched = row.scheduled_for ? new Date(row.scheduled_for).getTime() : 0; - if (sched > now.getTime()) continue; - // Honor existing lease - const lockedUntil = row.locked_until ? new Date(row.locked_until).getTime() : 0; - if (row.locked_by && lockedUntil > now.getTime()) continue; + 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 @@ -1052,7 +1065,6 @@ export class DbQueueAdapter implements IQueueService { updated_at: now.toISOString(), }, { context: SYSTEM_CTX }); out.push({ ...row, status: 'running' }); - inFlight?.add(String(row.id)); 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); @@ -1061,6 +1073,83 @@ export class DbQueueAdapter implements IQueueService { return out; } + /** + * [#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. + * + * `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 + * a main-loop {@link reclaimExpired} whose read was in flight during the + * claim never drops the entry of a row this batch holds; + * {@link dispatchBatch} takes the ids out once the batch is settled. + */ + 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); + if (candidates.length === 0) return []; + const ids = candidates.map((row: any) => String(row.id)); + for (const id of ids) inFlight.add(id); + const leaseUntilMs = nowMs + this.opts.leaseMs; + + let won: Set; + try { + const res = await this.engine.update(QUEUE_TABLE, { + status: 'running', + locked_by: this.opts.workerId, + locked_until: new Date(leaseUntilMs).toISOString(), + updated_at: nowIsoText, + }, { + where: { + id: { $in: ids }, + status: 'pending', + $or: [{ scheduled_for: null }, { scheduled_for: { $lte: nowIsoText } }], + }, + multi: true, + context: SYSTEM_CTX, + }); + if (typeof res === 'number' && res >= ids.length) { + won = new Set(ids); + } else { + const held = await this.engine.find(QUEUE_TABLE, { + where: { id: { $in: ids }, status: 'running', locked_by: this.opts.workerId }, + fields: ['id'], + limit: ids.length, + context: SYSTEM_CTX, + }); + 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); + // 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); + return []; + } + + const out: any[] = []; + for (const row of candidates) { + const id = String(row.id); + if (!won.has(id)) { inFlight.delete(id); continue; } + out.push({ ...row, status: 'running' }); + if (this.opts.soleWriter) this.unsettledLeases.set(id, leaseUntilMs); + } + return out; + } + private async dispatch(row: any): Promise { const handlers = this.handlers.get(row.queue) ?? []; if (handlers.length === 0) { @@ -1150,7 +1239,8 @@ export class DbQueueAdapter implements IQueueService { /** * [#38413] Hand claimed rows of a batch-consumed queue to its handler in * one call, renewing every row's lease while it runs, then settle each row - * by its own outcome ({@link settleRow}). A handler that throws, or answers + * by its own outcome: completed rows in set writes ({@link settleCompleted}), + * a failed row alone ({@link settleRow}). A handler that throws, or answers * a number of outcomes other than the number of messages, fails every row * of the batch — the same verdict a throwing per-message handler gets. */ @@ -1180,26 +1270,91 @@ export class DbQueueAdapter implements IQueueService { stopRenewing(); } try { + // [#38548] Completed rows settle in one write per attempt count (a + // fresh backlog is one write per batch); a failed row settles alone, on + // its own backoff, error and dead letter. + const completedByAttempts = new Map(); for (let i = 0; i < rows.length; i++) { const outcome = outcomes[i]; - const success = outcome?.ok === true; - const error = success ? undefined : (outcome as { error?: unknown } | undefined)?.error; - const lastError = success - ? undefined - : error instanceof Error ? error.message : error === undefined ? 'batch handler answered no outcome' : String(error); - // One settling write that throws does not leave the rest of an - // already-handled batch to the lease reclaim: each row is settled. - try { - await this.settleRow(rows[i], messages[i]!.attempts, success, lastError); - } catch (err) { - this.logger?.warn?.(`DbQueueAdapter: settling message ${messages[i]!.id} of ${batch.queue} failed`, err as any); + if (outcome?.ok === true) { + const group = completedByAttempts.get(messages[i]!.attempts) ?? []; + group.push(i); + completedByAttempts.set(messages[i]!.attempts, group); + continue; } + const error = (outcome as { error?: unknown } | undefined)?.error; + const lastError = error instanceof Error ? error.message : error === undefined ? 'batch handler answered no outcome' : String(error); + await this.settleOne(batch, rows[i], messages[i]!, false, lastError); + } + for (const [attempts, indexes] of completedByAttempts) { + await this.settleCompleted(batch, indexes.map((i) => rows[i]), indexes.map((i) => messages[i]!), attempts); } } finally { for (const id of ids) this.batchInFlight.delete(id); } } + /** + * One row of a batch through {@link settleRow}. A settling write that + * throws does not leave the rest of an already-handled batch to the lease + * reclaim: it is logged and the next row is settled. + */ + private async settleOne( + batch: RegisteredBatchHandler, + row: any, + message: QueueMessage, + success: boolean, + lastError: string | undefined, + ): Promise { + try { + await this.settleRow(row, message.attempts, success, lastError); + } catch (err) { + this.logger?.warn?.(`DbQueueAdapter: settling message ${message.id} of ${batch.queue} failed`, err as any); + } + } + + /** + * [#38548] Mark completed rows of a batch that reached the same attempt + * count in ONE write over their id set, matched as the lease renewal is + * ({@link renewLease}: `running` under this worker), so a row whose lease + * was reclaimed underneath keeps the state its new holder gave it. Fewer + * rows matched than were written is a lease lost while the handler ran, + * logged as the renewal logs it. A set write that throws falls back to one + * {@link settleRow} per row, so one bad row does not strand the others. + */ + private async settleCompleted( + batch: RegisteredBatchHandler, + rows: any[], + messages: QueueMessage[], + attempts: number, + ): Promise { + const ids = messages.map((m) => m.id); + const now = this.now(); + let res: unknown; + try { + res = await this.engine.update(QUEUE_TABLE, { + status: 'completed', + attempts, + completed_at: now.toISOString(), + locked_by: null, + locked_until: null, + updated_at: now.toISOString(), + }, { + where: { id: { $in: ids }, status: 'running', locked_by: this.opts.workerId }, + multi: true, + context: SYSTEM_CTX, + }); + } catch (err) { + this.logger?.warn?.(`DbQueueAdapter: settling ${ids.length} completed message(s) of ${batch.queue} in one write failed; settling each`, err as any); + for (let i = 0; i < rows.length; i++) await this.settleOne(batch, rows[i], messages[i]!, true, undefined); + return; + } + if (typeof res === 'number' && res < ids.length) { + this.logger?.warn?.('DbQueueAdapter: lease lost while the handler was still running', { queue: batch.queue, ids } as any); + } + for (const id of ids) this.settled(id); + } + private computeBackoff(row: any, attempt: number): number { const base = row.backoff_delay_ms ?? 1000; const cap = row.backoff_max_delay_ms ?? undefined;