diff --git a/.changeset/38413-knowledge-batch-sync.md b/.changeset/38413-knowledge-batch-sync.md new file mode 100644 index 00000000000..caeb075efe2 --- /dev/null +++ b/.changeset/38413-knowledge-batch-sync.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a bulk import or bulk update reaches search in batches, and a large backlog is reconciled instead of chased + +Clause-②: yes (widening) +Metadata-protocol: none + +Record sync used to read, embed and write one record per queue message, and the database queue handed those messages over ten a second, one at a time, so search trailed a bulk import of tens of thousands of records by hours. Where the composed queue has `IQueueService.subscribeBatch` (the platform's database queue does), the record-sync worker now takes up to 100 messages per call: the messages of one source are synced with one re-read of their rows under the source's `where`, one split, one store `upsert` (the embedder splits it into its provider's requests) and one `delete` for the records no row matches, under one index fingerprint. Several messages for one record sync it once. If a batch's write fails, its records are synced again one by one, so a record that cannot be synced is retried and dead-lettered alone while its neighbours are indexed. A queue without `subscribeBatch` keeps per-message delivery, unchanged. Messages stay identifiers only. + +When a source's estimated backlog reaches 5,000 waiting record syncs and 5 % of the source's rows (the estimate is the queue's waiting count times the source's share of the batch in hand), the worker schedules one reconcile of that source (the complete build with skip and purge) and keeps syncing while it walks; it never waits for it. Once a complete build of the source (that reconcile or any other) ends `done` with its purge run, a waiting message published more than 5 seconds before it began completes without a read, as `covered`. A build that ended `done` without purging (a store that does not list its documents, or a listing that failed) covers no message, so a waiting delete is still synced. After a backlog reconcile ends `done`, the next one for that source waits at least 10 minutes; after one that does not, the next waits 5 minutes, doubling to an hour. A source whose store does not list its documents is never reconciled for a backlog. `KnowledgeRecordSyncOutcome` gains `covered`, also answered by the per-message path. `KnowledgeService` gains `processRecordSyncBatch` (the worker's batch body), and `processRecordSync` takes the message's publish time as an optional second argument. The batch item and result types, `KnowledgeRecordSyncBatchItem` and `KnowledgeRecordSyncBatchResult`, are exported. + +The waiting count the `index_status` action and `os knowledge status` show is now exact above 10,000 messages (the database queue's `getQueueSize`). diff --git a/.changeset/38413-queue-batch-consume.md b/.changeset/38413-queue-batch-consume.md new file mode 100644 index 00000000000..d6cfe93a57e --- /dev/null +++ b/.changeset/38413-queue-batch-consume.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-queue': patch +--- + +feat(queue): an optional batch-consume member on `IQueueService`, implemented by the database queue + +Clause-②: yes (widening) +Metadata-protocol: none + +`IQueueService` gains an optional `subscribeBatch(queue, handler, { maxBatch })`, with the new exported types `QueueBatchHandler`, `QueueBatchOutcome` and `QueueBatchSubscribeOptions`. The handler receives up to `maxBatch` messages of one queue in one call and answers one outcome per message (`{ ok: true }`, or `{ ok: false, error }`), so a message that fails takes the retry and dead-letter path alone while its neighbours complete. A queue takes either per-message handlers or one batch handler. The member is optional: a consumer that finds it absent subscribes per message with `subscribe`, which stays correct, only slower. No existing member changes, and an `IQueueService` implementation that does not add the member keeps compiling and working. + +`DbQueueAdapter` implements it. A batch-consumed queue is drained by a loop of its own: each tick claims up to `maxBatch` due rows, renews every claimed row's lease in one write while the handler runs, settles each row by its own outcome (a settling write that fails does not stop the others), and ticks again at once while a claim comes back full. A row the lease reclaim returns to a batch-consumed queue wakes that queue's loop. Every per-message queue keeps the main loop exactly as before: one message per handler call, at most `batchSize` per `pollIntervalMs`. A publish wakes only the loop of its own queue. `DbQueueAdapter.pollBatchOnce(queue)` is the test-friendly poll of one batch queue, like `pollOnce`. + +`DbQueueAdapter.getQueueSize` now counts pending rows through the engine's `count` when the engine has one (the ObjectQL engine does), so a backlog larger than 10,000 messages is answered exactly instead of stopping at 10,000. An engine without `count` is read as before. diff --git a/content/docs/kernel/runtime-services/queue-service.mdx b/content/docs/kernel/runtime-services/queue-service.mdx index 71699fe6789..b86952df697 100644 --- a/content/docs/kernel/runtime-services/queue-service.mdx +++ b/content/docs/kernel/runtime-services/queue-service.mdx @@ -13,6 +13,7 @@ description: Publish and subscribe to async job queues with services.queue — q ```ts services.queue.publish(queue: string, data: T, options?: QueuePublishOptions): Promise services.queue.subscribe(queue: string, handler: QueueHandler): Promise +services.queue.subscribeBatch?(queue: string, handler: QueueBatchHandler, options: QueueBatchSubscribeOptions): Promise services.queue.unsubscribe(queue: string): Promise services.queue.getQueueSize?(queue: string): Promise services.queue.purge?(queue: string): Promise @@ -21,6 +22,8 @@ services.queue.replay?(messageId: string): Promise services.queue.purgeFailed?(messageId: string): Promise ``` +`subscribeBatch` is optional. It hands the handler up to `options.maxBatch` messages of one queue per call, and the handler answers one `QueueBatchOutcome` per message, in order: `{ ok: true }`, or `{ ok: false, error }`. A failed message takes the same retry and dead-letter path alone, while its neighbours complete. A handler that throws, or answers a different number of outcomes, fails every message of that call. A queue takes either per-message handlers or one batch handler, and `unsubscribe` removes either. A queue service without `subscribeBatch` is consumed one message at a time with `subscribe`. The database queue implements it. + ## Typical Errors - `MESSAGE_NOT_FOUND` — `replay` called with an unknown message id. (`purgeFailed` is idempotent — an unknown id is a silent no-op.) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts index c4db4e0e2c3..f3b812fd5c0 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build.test.ts @@ -46,7 +46,7 @@ type Row = Record; const SYSTEM = { executionContext: { positions: [], permissions: [], systemPermissions: [], isSystem: true } }; -/** Rows of one object; `find` applies scalar equality, `$and` and `id: { $gt }`, ordered by id. */ +/** Rows of one object; `find` applies scalar equality, `$and`, `id: { $gt }` and `id: { $in }`, ordered by id. */ function makeEngine(initial: Row[]) { const rows = new Map(initial.map((r) => [String(r.id), { ...r }])); const matches = (row: Row, where: Record | undefined): boolean => { @@ -57,6 +57,11 @@ function makeEngine(initial: Row[]) { continue; } if (value !== null && typeof value === 'object') { + const among = (value as { $in?: unknown[] }).$in; + if (among !== undefined) { + if (!among.includes(row[key])) return false; + continue; + } const gt = (value as { $gt?: unknown }).$gt; if (gt === undefined) throw new Error(`engine double: condition on '${key}' is not implemented`); if (!(String(row[key]) > String(gt))) return false; @@ -914,3 +919,225 @@ describe('KnowledgeServicePlugin — the reconcile job and the predicate-write r }); }); }); + +/** + * [#38413] Ask 2 of the record-sync batch: a source whose estimated backlog + * (the queue's waiting count times its share of the batch) reaches the + * threshold and a share of its rows gets one reconcile SCHEDULED next to its + * syncs, never awaited; once it ends `done` the messages it covers complete + * without a read. + */ +describe('processRecordSyncBatch — a backlog schedules one reconcile of its source (#38413)', () => { + const many = Array.from({ length: 60 }, (_, i) => ({ + id: `r${String(i).padStart(3, '0')}`, + title: `Clause ${i}`, + body: `Body of clause ${i}`, + })); + const queueView = (pending: number) => ({ + getQueueSize: async () => pending, + listFailed: async () => [], + purgeFailed: async () => undefined, + }); + const messages = (publishedAt: number, rows: Row[] = many, sourceName = 'kb') => + rows.map((row) => ({ data: { source: sourceName, object: 'kb_article', recordId: String(row.id), reason: 'event' }, publishedAt })); + const batchReads = (find: ReturnType['find']) => + find.mock.calls.filter(([, query]) => JSON.stringify(query?.where ?? {}).includes('$in')).length; + const reconciles = (service: KnowledgeService) => (service.buildRecord('kb')?.trigger === 'reconcile' ? 1 : 0); + const scheduled = (logger: ReturnType) => + logger.info.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('one reconcile of the source is scheduled')); + const settled = async (service: KnowledgeService, key = 'kb') => + vi.waitFor(() => { + const status = service.buildRecord(key)?.status; + if (status === undefined || status === 'running') throw new Error(`build of '${key}' not finished (${status})`); + }, { timeout: 5000, interval: 5 }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('over the threshold: the batch is synced without waiting, one reconcile runs beside it, and the next batch of older messages completes as covered with no re-read', async () => { + const db = makeEngine(many); + const { adapter, docs } = makeAdapter(); + // Hold the walk at its listing until the batch has answered. + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const list = adapter.listDocuments!.bind(adapter); + adapter.listDocuments = async (ctx, page) => { await gate; return list(ctx, page); }; + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + service.useRecordSyncQueue(queueView(6_000)); + const publishedAt = Date.now() - 60_000; + + const first = await service.processRecordSyncBatch(messages(publishedAt)); + expect(first.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + // The batch answered while the walk is still held at its listing. + await vi.waitFor(() => expect(service.buildRecord('kb')).toMatchObject({ trigger: 'reconcile', status: 'running' })); + expect(scheduled(logger)).toHaveLength(1); + release(); + await settled(service); + expect(service.buildRecord('kb')).toMatchObject({ trigger: 'reconcile', status: 'done', result: { purged: 0 } }); + expect(docs.size).toBe(60); + + const readsBefore = batchReads(db.find); + const again = await service.processRecordSyncBatch(messages(publishedAt)); + expect(again.every((r) => r.ok && r.outcome === 'covered')).toBe(true); + expect(batchReads(db.find)).toBe(readsBefore); + // Still over the threshold, but inside the re-walk wait: no second reconcile. + expect(scheduled(logger)).toHaveLength(1); + + // A message published after the reconcile began is not covered: it is synced. + const late = await service.processRecordSyncBatch([messages(Date.now() + 60_000)[0]!]); + expect(late).toEqual([{ ok: true, outcome: 'synced' }]); + }); + + it('under the threshold: the batch is synced in one re-read and one upsert, and no reconcile runs', async () => { + const db = makeEngine(many); + const { adapter, docs } = makeAdapter(); + const upserts = vi.spyOn(adapter, 'upsert'); + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + service.useRecordSyncQueue(queueView(4_999)); + + const results = await service.processRecordSyncBatch(messages(Date.now() - 60_000)); + expect(results.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + expect(reconciles(service)).toBe(0); + expect(scheduled(logger)).toHaveLength(0); + expect(batchReads(db.find)).toBe(1); + expect(upserts).toHaveBeenCalledTimes(1); + expect(docs.size).toBe(60); + }); + + it('per source: a backlog small against the source\'s rows is drained, not walked', async () => { + const db = makeEngine(many); + db.engine.count = vi.fn(async () => 1_000_000) as never; + const { adapter } = makeAdapter(); + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + // 40,000 waiting is over the threshold, but under 5 % of a million rows (50,000). + service.useRecordSyncQueue(queueView(40_000)); + + const results = await service.processRecordSyncBatch(messages(Date.now() - 60_000)); + expect(results.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + expect(reconciles(service)).toBe(0); + expect(scheduled(logger)).toHaveLength(0); + }); + + it('per source: a source with one message in another source\'s backlog is synced, while the other source is reconciled', async () => { + const db = makeEngine(many); + const { adapter } = makeAdapter(); + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + service.registerSource(source({ name: 'kb2', label: 'Second' })); + service.useRecordSyncQueue(queueView(6_000)); + const publishedAt = Date.now() - 60_000; + + // 59 of 60 messages are kb's (estimate about 5,900); kb2 has one (estimate 100). + const results = await service.processRecordSyncBatch([ + ...messages(publishedAt, many.slice(0, 59)), + ...messages(publishedAt, many.slice(59), 'kb2'), + ]); + expect(results.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + await settled(service); + expect(scheduled(logger)).toHaveLength(1); + expect(scheduled(logger)[0]).toContain("source 'kb'"); + expect(service.buildRecord('kb2')).toBeUndefined(); + }); + + it('a reconcile that does not end done is remembered: it is not scheduled again before its backoff', async () => { + const db = makeEngine(many); + const { adapter } = makeAdapter(); + // The listing fails, so the walk ends `done` with no purge: it covers nothing. + adapter.listDocuments = async () => { throw new Error('listing unavailable'); }; + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + service.useRecordSyncQueue(queueView(6_000)); + const publishedAt = Date.now() - 60_000; + + await service.processRecordSyncBatch(messages(publishedAt)); + await settled(service); + expect(service.buildRecord('kb')).toMatchObject({ trigger: 'reconcile', status: 'done', result: { purged: null } }); + const said = () => logger.warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('another is not scheduled for 5 min')); + await vi.waitFor(() => expect(said()).toHaveLength(1)); + + const again = await service.processRecordSyncBatch(messages(publishedAt)); + expect(again.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + expect(scheduled(logger)).toHaveLength(1); + + // Past the backoff the backlog may ask again. + const now = Date.now(); + vi.spyOn(Date, 'now').mockReturnValue(now + 5 * 60_000 + 1); + await service.processRecordSyncBatch(messages(publishedAt)); + expect(scheduled(logger)).toHaveLength(2); + }); + + it('a source whose store lists no documents is synced, not reconciled, even over the threshold', async () => { + const db = makeEngine(many); + const { adapter, docs } = makeAdapter({ omit: ['listDocuments'] }); + const { service, logger } = makeService(db.engine, adapter); + service.registerSource(source()); + service.useRecordSyncQueue(queueView(6_000)); + + const results = await service.processRecordSyncBatch(messages(Date.now() - 60_000)); + expect(results.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + expect(reconciles(service)).toBe(0); + expect(scheduled(logger)).toHaveLength(0); + expect(docs.size).toBe(60); + }); +}); + +/** + * [#38413] `covered` is answered only for what a build actually did: a build + * that ended `done` without purging (no `listDocuments`, or a listing that + * failed) deleted nothing, so a waiting delete or where-exit message is + * still synced, on the per-message path and the batch path alike. + */ +describe('record sync — a build that purged nothing covers no delete (#38413)', () => { + const rows = (): Row[] => [ + { id: 'a1', title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }, + { id: 'a2', title: 'Travel policy', body: 'Economy class under six hours', status: 'published' }, + { id: 'a3', title: 'Expense policy', body: 'Receipts within thirty days', status: 'published' }, + ]; + const message = (recordId: string) => ({ source: 'kb', object: 'kb_article', recordId, reason: 'event' }); + + /** Build once, then delete a1 and move a2 out of `where`; both messages were published a minute before the build. */ + async function afterUnpurgedBuild(build: 'rebuild-unlisted' | 'reconcile-listing-failed') { + const db = makeEngine(rows()); + const made = makeAdapter(build === 'rebuild-unlisted' ? { omit: ['listDocuments'] } : {}); + if (build === 'reconcile-listing-failed') made.adapter.listDocuments = async () => { throw new Error('listing unavailable'); }; + const { service } = makeService(db.engine, made.adapter); + service.registerSource(source({}, { status: 'published' })); + const publishedAt = Date.now() - 60_000; + // The documents exist before the build, as the per-message path left them. + await service.processRecordSync(message('a1')); + await service.processRecordSync(message('a2')); + db.rows.delete('a1'); + db.rows.get('a2')!.status = 'draft'; + if (build === 'rebuild-unlisted') await service.rebuildSource('kb', { trigger: 'operator' }); + else await service.reconcileSources({ sources: ['kb'] }); + expect(service.buildRecord('kb')).toMatchObject({ status: 'done', result: { purged: null } }); + return { service, docs: made.docs, publishedAt }; + } + + for (const build of ['rebuild-unlisted', 'reconcile-listing-failed'] as const) { + it(`per-message path, ${build}: the delete and the where-exit still remove their documents`, async () => { + const { service, docs, publishedAt } = await afterUnpurgedBuild(build); + expect(await service.processRecordSync(message('a1'), publishedAt)).toBe('synced'); + expect(await service.processRecordSync(message('a2'), publishedAt)).toBe('synced'); + expect(docs.has('kb:a1')).toBe(false); + expect(docs.has('kb:a2')).toBe(false); + expect(docs.has('kb:a3')).toBe(true); + }); + + it(`batch path, ${build}: the delete and the where-exit still remove their documents`, async () => { + const { service, docs, publishedAt } = await afterUnpurgedBuild(build); + const results = await service.processRecordSyncBatch([ + { data: message('a1'), publishedAt }, + { data: message('a2'), publishedAt }, + ]); + expect(results).toEqual([{ ok: true, outcome: 'synced' }, { ok: true, outcome: 'synced' }]); + expect(docs.has('kb:a1')).toBe(false); + expect(docs.has('kb:a2')).toBe(false); + expect(docs.has('kb:a3')).toBe(true); + }); + } +}); diff --git a/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts b/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts index aa073e8aba2..7013137dc00 100644 --- a/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts +++ b/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts @@ -43,7 +43,7 @@ import { ObjectKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { QueueServicePlugin, type DbQueueAdapter } from '@objectstack/service-queue'; +import { QueueServicePlugin, DbQueueAdapter } from '@objectstack/service-queue'; import { SysRecycleBin } from '@objectstack/platform-objects'; import type { IKnowledgeAdapter, @@ -630,3 +630,133 @@ describe('record sync without a durable queue, and the switches', () => { expect(stored?.status).toBe('pending'); }); }); + +/** + * [#38413] The record sync over a queue that consumes in batches + * (`IQueueService.subscribeBatch`, the database adapter): each batch is one + * re-read, one `upsert` and one `delete`; a record that cannot be synced + * fails alone; deletes and rows outside `where` leave the index as the + * per-message path leaves it. + */ +describe('record sync through the queue — batches (#38413)', () => { + /** Insert `n` rows with the worker stopped, so their messages wait together; every tenth is a draft (outside `where`). */ + async function backlog(t: Awaited>, n: number, body = (i: number) => `Body of clause ${i}`): Promise { + await t.queue.stop(); + const rows: Row[] = []; + for (let i = 0; i < n; i++) { + rows.push(await t.insert({ title: `Clause ${i}`, body: body(i), status: i % 10 === 9 ? 'draft' : 'published' })); + } + await vi.waitFor(async () => expect(await t.queueRows()).toHaveLength(n), { timeout: 10_000, interval: 20 }); + return rows; + } + + it('1,000 record syncs of one source cost batches of embedder calls and adapter writes, and the index equals a rebuild', async () => { + const t = await boot(); + expect(t.logger.info.mock.calls.map((c) => String(c[0])).some((l) => l.includes('in batches of up to 100 messages'))).toBe(true); + await backlog(t, 1_000); + t.queue.start(); + await vi.waitFor(async () => { + const open = (await t.queueRows()).filter((r) => r.status !== 'completed'); + if (open.length > 0) throw new Error(`${open.length} record-sync message(s) not completed`); + }, { timeout: 20_000, interval: 20 }); + + const upserts = vi.mocked(t.adapter.upsert).mock.calls.length; + const deletes = vi.mocked(t.adapter.delete).mock.calls.length; + // 1,000 messages in batches of 100: one upsert and one delete per batch. + expect(upserts).toBeLessThanOrEqual(10); + expect(deletes).toBeLessThanOrEqual(10); + // Each published row's document embedded once; the 100 drafts embedded never. + expect(t.embedCalls).toHaveLength(900); + expect(t.docs.size).toBe(900); + + const synced = new Map([...t.docs].map(([id, doc]) => [id, { content: doc.content, docHash: doc.docHash }])); + t.docs.clear(); + const rebuilt = await t.service.reindexSource('kb'); + expect(rebuilt).toMatchObject({ ok: true, indexed: 900 }); + expect(new Map([...t.docs].map(([id, doc]) => [id, { content: doc.content, docHash: doc.docHash }]))).toEqual(synced); + }, 60_000); + + it('a poisoned record in a batch dead-letters alone; its neighbours are indexed', async () => { + const t = await boot(); + const write = vi.mocked(t.adapter.upsert).getMockImplementation()!; + vi.mocked(t.adapter.upsert).mockImplementation(async (batch, ctx) => { + if (batch.some((doc) => doc.content.includes('POISON'))) throw new Error('the embedding provider refused one input'); + return write(batch, ctx); + }); + const rows = await backlog(t, 8, (i) => (i === 3 ? 'POISON clause' : `Body of clause ${i}`)); + t.queue.start(); + await t.drained(8); + + const failed = await t.queue.listFailed(KNOWLEDGE_RECORD_SYNC_QUEUE); + expect(failed.map((m) => (m.data as { recordId: string }).recordId)).toEqual([String(rows[3]!.id)]); + expect(failed[0]!.attempts).toBe(FAST_RETRY.maxAttempts); + const published = rows.filter((_, i) => i !== 3 && i % 10 !== 9).map((r) => `kb:${String(r.id)}`).sort(); + expect([...t.docs.keys()].sort()).toEqual(published); + const statuses = (await t.queueRows()).map((r) => r.status); + expect(statuses.filter((s) => s === 'completed')).toHaveLength(7); + expect(t.logger.error.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is now a dead letter'))).toHaveLength(1); + }, 30_000); + + it('a held service syncs nothing on the batch path: every waiting message completes and no store is called', async () => { + const t = await boot(); + expect(t.logger.info.mock.calls.map((c) => String(c[0])).some((l) => l.includes('in batches of up to 100 messages'))).toBe(true); + await backlog(t, 30); + // Messages published while enabled, then a boot reads the service as not + // enabled (ADR-0161 K8, ruling 7248214179): the worker still drains them. + t.service.settleEnablement({ embedder: 'no embedder provider is saved' }); + t.queue.start(); + await t.drained(30); + + const statuses = (await t.queueRows()).map((r) => r.status); + expect(statuses.filter((s) => s === 'completed')).toHaveLength(30); + expect(await t.queue.listFailed(KNOWLEDGE_RECORD_SYNC_QUEUE)).toEqual([]); + expect(t.adapter.upsert).not.toHaveBeenCalled(); + expect(t.adapter.delete).not.toHaveBeenCalled(); + expect(t.embedCalls).toHaveLength(0); + expect(t.docs.size).toBe(0); + await expect( + t.service.processRecordSyncBatch([{ data: { source: 'kb', object: 'kb_article', recordId: 'r1', reason: 'event' } }]), + ).resolves.toEqual([{ ok: true, outcome: 'not-synced' }]); + }, 30_000); + + /** Deletes, a row moved out of `where`, an edit, a new draft and a new row, all in one batch: the index's contents after. */ + async function mixedBatch(t: Awaited>): Promise { + const [a, b, c] = [ + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }), + await t.insert({ title: 'Travel policy', body: 'Economy class under six hours', status: 'published' }), + await t.insert({ title: 'Expense policy', body: 'Receipts within thirty days', status: 'published' }), + await t.insert({ title: 'Remote policy', body: 'Two days a week at home', status: 'published' }), + ]; + await t.drained(4); + await t.queue.stop(); + await t.remove(a!.id); + await t.update(b!.id, { status: 'draft' }); + await t.update(c!.id, { body: 'Receipts within sixty days' }); + await t.insert({ title: 'Draft policy', body: 'Not yet', status: 'draft' }); + await t.insert({ title: 'Parking policy', body: 'First come first served', status: 'published' }); + await vi.waitFor(async () => expect(await t.queueRows()).toHaveLength(9), { timeout: 3000, interval: 10 }); + t.queue.start(); + await t.drained(9); + return [...t.docs.values()].map((doc) => doc.content).sort(); + } + + it('deletes and rows outside where in a batch leave the index exactly as the per-message path leaves it', async () => { + const batched = await mixedBatch(await boot()); + expect(batched).toHaveLength(3); + expect(batched.some((content) => content.includes('sixty days'))).toBe(true); + expect(batched.some((content) => content.includes('paid leave') || content.includes('Economy class') || content.includes('Not yet'))).toBe(false); + + // The same writes over a queue without subscribeBatch: the per-message fallback. + const own = Object.getOwnPropertyDescriptor(DbQueueAdapter.prototype, 'subscribeBatch')!; + Object.defineProperty(DbQueueAdapter.prototype, 'subscribeBatch', { value: undefined, configurable: true, writable: true }); + let perMessage: string[]; + try { + const t = await boot(); + expect(t.logger.info.mock.calls.map((c) => String(c[0])).some((l) => l.includes('one message at a time'))).toBe(true); + perMessage = await mixedBatch(t); + } finally { + Object.defineProperty(DbQueueAdapter.prototype, 'subscribeBatch', own); + } + expect(batched).toEqual(perMessage); + }, 30_000); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index b8fc4a96ee8..7b6e8f6ac82 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -94,6 +94,8 @@ export type { } from './knowledge-settings-contribution.js'; export { KNOWLEDGE_RECORD_SYNC_QUEUE, RECORD_SYNC_RETRY_DEFAULTS } from './knowledge-record-sync-queue.js'; export type { + KnowledgeRecordSyncBatchItem, + KnowledgeRecordSyncBatchResult, KnowledgeRecordSyncMessage, KnowledgeRecordSyncOutcome, KnowledgeRecordSyncReason, diff --git a/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts b/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts index 509c844fa54..6ea891a66b8 100644 --- a/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts +++ b/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts @@ -137,6 +137,97 @@ export function resolveRecordSyncQueue(getService: (name: string) => unknown): I * - `not-synced` — the source no longer indexes the message's object on * record change (`refresh.onRecordChange: false`, or another object), or * no data engine is bound to re-read the row; - * - `malformed` — the message is not a record-sync message. + * - `malformed` — the message is not a record-sync message; + * - `covered` — a complete build of the source that finished on this node + * (`done`, with its purge run) began at least + * {@link RECORD_SYNC_COVER_MARGIN_MS} after the message was published, so + * its walk wrote the record's document or its purge deleted it: nothing is + * read, embedded or written. A build that purged nothing covers nothing. */ -export type KnowledgeRecordSyncOutcome = 'synced' | 'source-gone' | 'not-synced' | 'malformed'; +export type KnowledgeRecordSyncOutcome = 'synced' | 'source-gone' | 'not-synced' | 'malformed' | 'covered'; + +/** + * The most record-sync messages the worker takes in one call where the queue + * consumes in batches (`IQueueService.subscribeBatch`): the reindex page size + * (`REINDEX_PAGE_SIZE`), so a batch is one re-read, one split, one `upsert` + * the embedder splits into its provider's requests, and one `delete` — about + * what one page of a rebuild costs. The adapter renews the lease of every + * claimed message while the batch runs; a batch that settles in seconds also + * leaves a crashed worker's messages to come back one lease (30 s by + * default) later, not after a long batch. + */ +export const RECORD_SYNC_BATCH_SIZE = 100; + +/** + * The smallest estimated backlog of one source, in waiting record-sync + * messages, for which the worker schedules one reconcile of that source (the + * complete build, trigger `reconcile`) beside its syncs. The estimate is the + * queue's waiting count (`IQueueService.getQueueSize`) times the source's + * share of the batch in hand. Measured (#38413, a local model: SQLite, a + * 50,000-row source, an embedder at 200 ms per request + 0.5 ms per input), + * the batch worker drains 214 changed records per second, so 5,000 messages + * are about 23 s of draining; a smaller backlog is gone about as soon as a + * walk could start. + */ +export const RECORD_SYNC_BACKLOG_THRESHOLD = 5_000; + +/** + * The share of a source's rows (its `where`, counted) that its estimated + * backlog must also reach ({@link RECORD_SYNC_BACKLOG_THRESHOLD}), so a small + * write to a large source is drained, not walked. In the same local model a + * reconcile walk reads 50,000 unchanged rows in 1.4 s (no embedding), and + * draining costs 2.1 ms per message for an unchanged record and 4.7 ms for a + * changed one; at 5 % of the rows the walk's own reading is about a quarter + * of the drain it runs beside, or less. Measured on a 50,000-message backlog + * of a 50,000-row source: 217 s against 233 s draining alone with every + * record changed, 91 s against 106 s with none changed. + */ +export const RECORD_SYNC_BACKLOG_ROW_SHARE = 0.05; + +/** + * After a backlog reconcile of a source ended `done`, the next one for that + * source waits at least this long: a source under sustained writes is + * drained between walks, not walked back to back. + */ +export const RECORD_SYNC_BACKLOG_REWALK_MS = 10 * 60_000; + +/** + * After a backlog reconcile of a source did not end `done` (failed, lease + * lost, timed out, purge not run), the next one waits this long, doubling + * per failure up to {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS}. + */ +export const RECORD_SYNC_BACKLOG_RETRY_MS = 5 * 60_000; + +/** The ceiling of {@link RECORD_SYNC_BACKLOG_RETRY_MS}'s doubling. */ +export const RECORD_SYNC_BACKLOG_RETRY_MAX_MS = 60 * 60_000; + +/** How long the worker keeps a source's counted rows ({@link RECORD_SYNC_BACKLOG_ROW_SHARE}) before it counts again. */ +export const RECORD_SYNC_SOURCE_ROWS_TTL_MS = 10 * 60_000; + +/** How often the worker reads the queue's backlog at most: one count per interval, not one per batch. */ +export const RECORD_SYNC_BACKLOG_READ_INTERVAL_MS = 30_000; + +/** + * How much earlier than a build's start a message must have been published + * for that build to cover it (`covered`). The publish time is stamped by the + * publishing node's queue and the build's start by the building node's clock; + * the margin absorbs the skew between two nodes' clocks. A message inside the + * margin is synced as usual. + */ +export const RECORD_SYNC_COVER_MARGIN_MS = 5_000; + +/** One message handed to `KnowledgeService.processRecordSyncBatch`: its payload, and when the queue says it was published (epoch ms). */ +export interface KnowledgeRecordSyncBatchItem { + data: unknown; + publishedAt?: number; +} + +/** + * What `KnowledgeService.processRecordSyncBatch` answers for one message, in + * the batch's order: an outcome that completes it, or the error that fails + * it (the queue retries it, and keeps it as a dead letter once its attempts + * are spent). + */ +export type KnowledgeRecordSyncBatchResult = + | { ok: true; outcome: KnowledgeRecordSyncOutcome } + | { ok: false; error: unknown }; diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 2d6c3dfd738..db57d22e7a8 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -9,6 +9,7 @@ import type { IQueueService, IRealtimeService, JobRunOutcome, + QueueBatchOutcome, QueueMessage, } from '@objectstack/spec/contracts'; import type { KnowledgeSource } from '@objectstack/spec/ai'; @@ -37,6 +38,7 @@ import { createKnowledgeReapGuard, guardedObjectsFor } from './knowledge-reap-gu import { KnowledgeRecordHooks, recordHookEngineOf } from './knowledge-record-hooks.js'; import { KNOWLEDGE_RECORD_SYNC_QUEUE, + RECORD_SYNC_BATCH_SIZE, readRecordSyncMessage, recordSyncPublishOptions, resolveRecordSyncQueue, @@ -918,6 +920,13 @@ export class KnowledgeServicePlugin implements Plugin { * The worker throws what a retry can change, so the queue retries it on the * {@link KnowledgeServicePluginOptions.recordSyncRetry} budget; on the last * attempt it also says, at `error`, that the message is now a dead letter. + * + * [#38413] Where the queue has `IQueueService.subscribeBatch` (the database + * queue), the worker subscribes with it and takes up to + * `RECORD_SYNC_BATCH_SIZE` messages per call + * (`KnowledgeService.processRecordSyncBatch`), answering one outcome per + * message, so a failed message is retried and dead-lettered alone. Any + * other durable queue keeps per-message `subscribe`. */ private async startRecordSyncQueue(ctx: PluginContext, service: KnowledgeService): Promise { const hasEngine = this.dataEngineBound; @@ -937,32 +946,61 @@ export class KnowledgeServicePlugin implements Plugin { return; } const retry = resolveRecordSyncRetry(this.options.recordSyncRetry); - await queue.subscribe(KNOWLEDGE_RECORD_SYNC_QUEUE, async (message: QueueMessage) => { - try { - await service.processRecordSync(message.data); - } catch (err) { - if (message.attempts >= retry.maxAttempts) { - // [ADR-0161] One failure per dead letter, never one per attempt. - await service.recordSyncFailure(message.data, err, { attempt: message.attempts, maxAttempts: retry.maxAttempts }); - const named = readRecordSyncMessage(message.data); - const report = - `KnowledgeServicePlugin: the sync of record '${named?.recordId ?? '?'}' of source '${named?.source ?? '?'}' ` + - `failed its last attempt (${message.attempts} of ${retry.maxAttempts}: ${err instanceof Error ? err.message : String(err)}) ` + - `and is now a dead letter on queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}'. The record's document stays as it was ` + - 'until the record\'s next save or the reconcile; replay the message, or rebuild the source with os knowledge rebuild.'; - if (ctx.logger.error) ctx.logger.error(report); - else ctx.logger.warn?.(report); + // [ADR-0161] One failure per dead letter, never one per attempt. + const lastAttempt = async (message: QueueMessage, err: unknown): Promise => { + if (message.attempts < retry.maxAttempts) return; + await service.recordSyncFailure(message.data, err, { attempt: message.attempts, maxAttempts: retry.maxAttempts }); + const named = readRecordSyncMessage(message.data); + const report = + `KnowledgeServicePlugin: the sync of record '${named?.recordId ?? '?'}' of source '${named?.source ?? '?'}' ` + + `failed its last attempt (${message.attempts} of ${retry.maxAttempts}: ${err instanceof Error ? err.message : String(err)}) ` + + `and is now a dead letter on queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}'. The record's document stays as it was ` + + 'until the record\'s next save or the reconcile; replay the message, or rebuild the source with os knowledge rebuild.'; + if (ctx.logger.error) ctx.logger.error(report); + else ctx.logger.warn?.(report); + }; + // [#38413] A queue that consumes in batches hands the worker up to + // RECORD_SYNC_BATCH_SIZE messages per call, each settled by its own + // result; any other durable queue keeps per-message delivery, which is + // correct, only slower. + const batched = typeof queue.subscribeBatch === 'function'; + if (batched) { + await queue.subscribeBatch!(KNOWLEDGE_RECORD_SYNC_QUEUE, async (messages: QueueMessage[]) => { + const results = await service.processRecordSyncBatch( + messages.map((message) => ({ data: message.data, publishedAt: message.timestamp })), + ); + const outcomes: QueueBatchOutcome[] = []; + for (let i = 0; i < messages.length; i++) { + const result = results[i]; + if (result?.ok) { + outcomes.push({ ok: true }); + continue; + } + const error = result ? result.error : new Error('the batch answered no result for this message'); + await lastAttempt(messages[i]!, error); + outcomes.push({ ok: false, error }); } - throw err; - } - }); + return outcomes; + }, { maxBatch: RECORD_SYNC_BATCH_SIZE }); + } else { + await queue.subscribe(KNOWLEDGE_RECORD_SYNC_QUEUE, async (message: QueueMessage) => { + try { + await service.processRecordSync(message.data, message.timestamp); + } catch (err) { + await lastAttempt(message, err); + throw err; + } + }); + } this.syncQueue = queue; service.useRecordSyncQueue(queue); service.routeRecordSyncs((message) => queue.publish(KNOWLEDGE_RECORD_SYNC_QUEUE, message, recordSyncPublishOptions(message, retry)), ); ctx.logger.info?.( - `KnowledgeServicePlugin: record sync runs through queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (up to ` + + `KnowledgeServicePlugin: record sync runs through queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}'` + + (batched ? ` in batches of up to ${RECORD_SYNC_BATCH_SIZE} messages` : ', one message at a time') + + ' (up to ' + `${retry.maxAttempts} attempts, backoff ${retry.backoffMs} ms doubling to ${retry.maxBackoffMs} ms): a save ` + "publishes once its unit of work commits and does not wait for the embedder.", ); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 23f4a6029ce..3d9f3acea64 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -97,6 +97,16 @@ import { import { KNOWLEDGE_RECORD_SYNC_QUEUE, readRecordSyncMessage, + RECORD_SYNC_BACKLOG_READ_INTERVAL_MS, + RECORD_SYNC_BACKLOG_RETRY_MAX_MS, + RECORD_SYNC_BACKLOG_RETRY_MS, + RECORD_SYNC_BACKLOG_REWALK_MS, + RECORD_SYNC_BACKLOG_ROW_SHARE, + RECORD_SYNC_BACKLOG_THRESHOLD, + RECORD_SYNC_SOURCE_ROWS_TTL_MS, + RECORD_SYNC_COVER_MARGIN_MS, + type KnowledgeRecordSyncBatchItem, + type KnowledgeRecordSyncBatchResult, type KnowledgeRecordSyncMessage, type KnowledgeRecordSyncOutcome, type KnowledgeRecordSyncReason, @@ -261,6 +271,15 @@ export class KnowledgeService implements IKnowledgeService { * lives only while a sync for it is pending. */ private readonly recordSyncTails = new Map>(); + /** [#38413] The last waiting-count reading of the record-sync queue ({@link recordSyncWaiting}). */ + private recordSyncBacklog: { at: number; waiting: number | undefined } | undefined; + /** + * [#38413] Per source (index key): the backlog reconcile running for it, and + * when the next may be scheduled ({@link considerBacklogReconcile}). + */ + private readonly backlogReconciles = new Map(); + /** [#38413] Per source (index key): its counted rows and when they were counted ({@link sourceRowCount}). */ + private readonly sourceRows = new Map(); /** * The tail of each source's reindex chain, keyed by its index key — see * {@link reindexSource}. A key lives only while a walk of it is pending. @@ -3400,47 +3419,353 @@ export class KnowledgeService implements IKnowledgeService { * embedding call, the store write — is THROWN, so the queue retries the * message on its backoff and, once its attempts are spent, keeps it as a * dead letter. Every other outcome completes the message and is answered - * ({@link KnowledgeRecordSyncOutcome}). + * ({@link KnowledgeRecordSyncOutcome}). `publishedAt` is when the queue + * says the message was published (epoch ms): a message that a finished + * complete build which purged began after is answered `covered` without a + * read ({@link coveredByBuild}). + */ + async processRecordSync(data: unknown, publishedAt?: number): Promise { + const resolved = this.resolveRecordSync(data, publishedAt); + if ('outcome' in resolved) return resolved.outcome; + const { source, message, engine } = resolved; + // The source's adapter is resolved now ({@link adapterFor}): the one it + // names, else the deployment's store, else the only one registered. Where + // none can be resolved it throws its coded refusal — the named adapter is + // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or + // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so + // the message is retried: a store that registers late is met by a later + // attempt, and one that never does leaves a dead letter naming the source + // and the record. + const adapter = this.adapterFor(source); + await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => + this.syncRow(source, adapter, message.object, message.recordId, engine), + ); + return 'synced'; + } + + /** + * What every record-sync message is checked for before its row is read, + * on both of the worker's paths ({@link processRecordSync}, + * {@link processRecordSyncBatch}): an outcome that completes it without a + * sync — not a record-sync message, the service held, its source gone, its object no longer + * synced on record change, no data engine to re-read the row, or covered + * by a complete build that purged and began after it was published + * ({@link coveredByBuild}) — or the source, + * the message and the engine to sync it with. */ - async processRecordSync(data: unknown): Promise { + private resolveRecordSync( + data: unknown, + publishedAt: number | undefined, + ): + | { outcome: KnowledgeRecordSyncOutcome } + | { source: KnowledgeSource; message: KnowledgeRecordSyncMessage; engine: IDataEngine } { const message = readRecordSyncMessage(data); if (!message) { this.options.logger?.warn?.( `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, ); - return 'malformed'; + return { outcome: 'malformed' }; } - // Held: completed without a sync, and no store is called. - if (this.held) return 'not-synced'; + // Held (ADR-0161 K8, ruling 7248214179): completed without a sync, and no + // store is called, on the per-message and the batch path alike. + if (this.held) return { outcome: 'not-synced' }; const source = this.handed(message.source); if (!source) { this.options.logger?.debug?.( `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, ); - return 'source-gone'; + return { outcome: 'source-gone' }; } - if (objectSourcesFor([source], message.object).length === 0) return 'not-synced'; + if (objectSourcesFor([source], message.object).length === 0) return { outcome: 'not-synced' }; const engine = this.options.dataEngine; if (!engine) { this.options.logger?.warn?.( `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + 'bound to re-read the row.', ); - return 'not-synced'; + return { outcome: 'not-synced' }; } - // The source's adapter is resolved now ({@link adapterFor}): the one it - // names, else the deployment's store, else the only one registered. Where - // none can be resolved it throws its coded refusal — the named adapter is - // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or - // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so - // the message is retried: a store that registers late is met by a later - // attempt, and one that never does leaves a dead letter naming the source - // and the record. - const adapter = this.adapterFor(source); - await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => - this.syncRow(source, adapter, message.object, message.recordId, engine), + if (this.coveredByBuild(source.name, publishedAt)) return { outcome: 'covered' }; + return { source, message, engine }; + } + + /** + * [#38413] Whether a complete build of the source under `key` already did + * what a message published at `publishedAt` asks for, so the message can + * complete without a read. All of these must hold: + * + * - the source's last build on this node finished `done` and its PURGE RAN + * (`result.purged` is a number). The walk writes the document of every + * row it reads and the purge deletes the document of every row it did + * not, so a message for a deleted row, or for a row that left `where`, is + * covered only by a build that purged. A build that ends `done` with + * `purged: null` (an adapter without `listDocuments`, or a listing that + * failed and the walk went on) deleted nothing, and covers nothing; + * - the reconcile walks the source ({@link reconcileExclusion}): a source + * whose index an external indexer owns, or whose store lists nothing, is + * never covered; + * - the build began at least {@link RECORD_SYNC_COVER_MARGIN_MS} after + * `publishedAt`. A message is published once its write committed, and + * the walk reads every row after it starts. + * + * A build running now, or one that did not finish, covers nothing. + */ + private coveredByBuild(key: string, publishedAt: number | undefined): boolean { + if (publishedAt === undefined || !Number.isFinite(publishedAt)) return false; + const build = this.builds.get(key); + if (build?.status !== 'done' || typeof build.result?.purged !== 'number' || build.result.ok === false) return false; + const entry = this.registry.byIndexKey(key); + if (!entry || this.reconcileExclusion(entry) !== undefined) return false; + const startedAt = Date.parse(build.startedAt); + return Number.isFinite(startedAt) && publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS; + } + + /** + * [#38413] The worker's body where the queue consumes in batches + * (`IQueueService.subscribeBatch`): answer one result per message, in + * order ({@link KnowledgeRecordSyncBatchResult}). Each message is checked + * as {@link processRecordSync} checks it; the rest are grouped by source + * and object, and each group is synced at once — one re-read of its rows + * (`where` AND id in the group), one split, one `upsert` (the embedder + * splits it into its provider's requests) and one `delete` for the ids no + * row matches, all under one index plan, so one fingerprint (ADR-0161 K7). + * Several messages for one record sync it once. The group holds the + * per-document chain of every record in it, so a sync of one of them on + * the per-message path or another batch waits for it, as before. + * + * A group whose write fails is synced again record by record, so a record + * that cannot be synced fails alone and its neighbours are written: its + * message answers its own error, and the queue retries it and keeps it as a + * dead letter once its attempts are spent. + * + * A source whose estimated backlog is large against its rows gets one + * reconcile scheduled next to its syncs ({@link considerBacklogReconcile}); + * the batch never waits for it, and once it ends `done` the messages it + * covers complete without a read. Never rejects. + */ + async processRecordSyncBatch( + batch: readonly KnowledgeRecordSyncBatchItem[], + ): Promise { + const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); + const groups = new Map(); + batch.forEach((item, index) => { + const resolved = this.resolveRecordSync(item?.data, item?.publishedAt); + if ('outcome' in resolved) { + results[index] = { ok: true, outcome: resolved.outcome }; + return; + } + const key = JSON.stringify([resolved.source.name, resolved.message.object]); + let group = groups.get(key); + if (!group) { + group = { source: resolved.source, object: resolved.message.object, engine: resolved.engine, items: [] }; + groups.set(key, group); + } + group.items.push({ index, recordId: resolved.message.recordId, publishedAt: item.publishedAt }); + }); + for (const group of groups.values()) { + await this.considerBacklogReconcile(group, batch.length); + } + for (const group of groups.values()) { + try { + await this.syncRecordGroup(group, results); + } catch (err) { + for (const item of group.items) results[item.index] ??= { ok: false, error: err }; + } + } + return results; + } + + /** One group of {@link processRecordSyncBatch}: writes each of its items' result. */ + private async syncRecordGroup(group: RecordSyncGroup, results: KnowledgeRecordSyncBatchResult[]): Promise { + const { source, object, engine } = group; + let adapter: IKnowledgeAdapter; + try { + adapter = this.adapterFor(source); + } catch (err) { + for (const item of group.items) results[item.index] = { ok: false, error: err }; + return; + } + const open: RecordSyncGroup['items'] = []; + for (const item of group.items) { + if (this.coveredByBuild(source.name, item.publishedAt)) results[item.index] = { ok: true, outcome: 'covered' }; + else open.push(item); + } + if (open.length === 0) return; + const recordIds = [...new Set(open.map((item) => item.recordId))]; + const failures = new Map(); + await chainAfterAll(this.recordSyncTails, recordIds.map((id) => documentIdFor(source.name, id)), async () => { + if (recordIds.length > 1) { + try { + await this.syncRows(source, adapter, object, recordIds, engine); + return; + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] a batch of ${recordIds.length} record syncs of source '${this.label(source)}' failed (${errorText(err)}); ` + + 'syncing them one by one, so a record that cannot be synced fails alone.', + ); + } + } + for (const recordId of recordIds) { + try { + await this.syncRow(source, adapter, object, recordId, engine); + } catch (err) { + failures.set(recordId, err); + } + } + }); + for (const item of open) { + results[item.index] = failures.has(item.recordId) + ? { ok: false, error: failures.get(item.recordId) } + : { ok: true, outcome: 'synced' }; + } + } + + /** + * [#38413] The record-sync queue's waiting count (`getQueueSize`), read at + * most once per {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}. `undefined` + * when the queue cannot count or the count failed. + */ + private async recordSyncWaiting(): Promise { + const now = Date.now(); + const last = this.recordSyncBacklog; + if (last && now - last.at < RECORD_SYNC_BACKLOG_READ_INTERVAL_MS) return last.waiting; + let waiting: number | undefined; + try { + waiting = await this.pendingRecordSyncs(); + } catch { + waiting = undefined; + } + this.recordSyncBacklog = { at: now, waiting }; + return waiting; + } + + /** + * [#38413] The rows of the source under `key` (its `where`, counted as the + * system identity), kept for {@link RECORD_SYNC_SOURCE_ROWS_TTL_MS}. + * `undefined` when the count failed. + */ + private async sourceRowCount(key: string, objSource: ObjectKnowledgeSource, engine: IDataEngine): Promise { + const now = Date.now(); + const last = this.sourceRows.get(key); + if (last && now - last.at < RECORD_SYNC_SOURCE_ROWS_TTL_MS) return last.rows; + let rows: number | undefined; + try { + const counted = await engine.count(objSource.object, { where: objSource.where }, { context: systemContext() }); + rows = typeof counted === 'number' && Number.isFinite(counted) ? counted : undefined; + } catch { + rows = undefined; + } + this.sourceRows.set(key, { at: now, rows }); + return rows; + } + + /** + * [#38413] Ask 2 of the batch path: schedule one reconcile of the group's + * source when its backlog is large enough that a walk beside the drain + * pays. The source's backlog is estimated as the queue's waiting count + * times the group's share of the batch in hand (the batch is the head of + * the queue). A reconcile is scheduled when that estimate reaches both + * {@link RECORD_SYNC_BACKLOG_THRESHOLD} and + * {@link RECORD_SYNC_BACKLOG_ROW_SHARE} of the source's rows, no backlog + * reconcile of the source is running, and the source is past its wait: + * {@link RECORD_SYNC_BACKLOG_REWALK_MS} after one that ended `done`, or a + * backoff from {@link RECORD_SYNC_BACKLOG_RETRY_MS} doubling to + * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} after one that did not. + * + * It is scheduled, never awaited: the batch, and every other source's + * syncs, go on while it walks, and the messages its build covers + * ({@link coveredByBuild}) complete without a read once it ends. A source + * the reconcile does not walk ({@link reconcileExclusion}) is never + * scheduled. Never rejects. + */ + private async considerBacklogReconcile(group: RecordSyncGroup, batchLength: number): Promise { + const key = group.source.name; + const objSource = group.source.source; + if (objSource.kind !== 'object' || batchLength <= 0) return; + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) return; + const state = this.backlogReconciles.get(key); + if (state && (state.running || Date.now() < state.notBefore)) return; + const waiting = await this.recordSyncWaiting(); + if (waiting === undefined) return; + const estimate = Math.round((waiting * group.items.length) / batchLength); + if (estimate < RECORD_SYNC_BACKLOG_THRESHOLD) return; + const rows = await this.sourceRowCount(key, objSource, group.engine); + if (rows === undefined || estimate < rows * RECORD_SYNC_BACKLOG_ROW_SHARE) return; + + const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; + this.backlogReconciles.set(key, next); + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + + 'reconcile of the source is scheduled; record syncs go on meanwhile, and those it covers complete without a ' + + 'read once it ends.', ); - return 'synced'; + void this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }) + .then(() => undefined, () => undefined) + .then(() => { + next.running = false; + const build = this.builds.get(key); + if (build?.status === 'done' && typeof build.result?.purged === 'number') { + next.failures = 0; + next.notBefore = Date.now() + RECORD_SYNC_BACKLOG_REWALK_MS; + return; + } + next.failures++; + const wait = Math.min(RECORD_SYNC_BACKLOG_RETRY_MS * 2 ** (next.failures - 1), RECORD_SYNC_BACKLOG_RETRY_MAX_MS); + next.notBefore = Date.now() + wait; + this.options.logger?.warn?.( + `[knowledge] source '${entry.face}': the reconcile scheduled for its record-sync backlog ended ` + + `${build?.status ?? 'without a build'}${build?.status === 'done' ? ' with no purge' : ''}, so its record syncs are ` + + `drained one by one; another is not scheduled for ${Math.round(wait / 60_000)} min.`, + ); + }); + } + + /** + * [#38413] The batch twin of {@link syncRow}: re-read the rows `recordIds` + * name under the source's `where` as the system identity, in one read + * ({@link rereadRows}), write the documents of the rows that came back in + * one `upsert` and delete those of the ids no row matched in one `delete`, + * under one index plan. A document the split cannot index is removed and + * reported, as {@link writeSynced} does. Throws what the re-read, a + * document build, the split, the embedding call or the store throws. + */ + private async syncRows( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordIds: string[], + engine: IDataEngine, + ): Promise { + const objSource = source.source; + const rows = await rereadRows(engine, objSource, recordIds); + const byId = new Map>(); + for (const row of rows) if (isRecordId(row.id)) byId.set(String(row.id), row); + const schema = this.schemaFor(object); + const posture = await this.readTenancyPosture(); + const docs: KnowledgeDocument[] = []; + const gone: string[] = []; + const recordOf = new Map(); + for (const recordId of recordIds) { + const row = byId.get(recordId); + if (row) { + const doc = recordToDocument(source, objSource, row, schema, posture); + recordOf.set(doc.id, recordId); + docs.push(doc); + } else { + gone.push(documentIdFor(source.name, recordId)); + } + } + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, docs); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); + const removed = [...gone, ...prepared.failed.map((f) => f.documentId)]; + if (removed.length > 0) await adapter.delete(removed, ctx); + for (const f of prepared.failed) this.reportUnindexable(source, adapter, f, recordOf.get(f.documentId) ?? f.documentId); } /** @@ -3602,19 +3927,29 @@ export class KnowledgeService implements IKnowledgeService { if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); for (const f of prepared.failed) { await adapter.delete([f.documentId], ctx); - const limit = adapter.embedding?.maxInputTokens; - const message = - `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + - `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + - `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + - `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; - // `warn` is the guaranteed channel when a host injects no `error`. - const logger = this.options.logger; - if (logger?.error) logger.error(message); - else logger?.warn?.(message); + this.reportUnindexable(source, adapter, f, recordId); } } + /** Say, at `error`, that a record's document left the index because its split cannot index it ({@link writeSynced}, {@link syncRows}). */ + private reportUnindexable( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + f: { estimate: number; budget: number }, + recordId: unknown, + ): void { + const limit = adapter.embedding?.maxInputTokens; + const message = + `[knowledge] record '${String(recordId)}' of source '${this.label(source)}' is no longer in the index and search ` + + `will not find it: its whole document estimates ${f.estimate} tokens, over the budget of ${f.budget} ` + + `(80% of the embedder's ${String(limit)}-token input limit), and split 'whole' does not truncate. ` + + `Fix: give source '${this.label(source)}' split strategy 'recursive' or 'markdown', or shorten the record.`; + // `warn` is the guaranteed channel when a host injects no `error`. + const logger = this.options.logger; + if (logger?.error) logger.error(message); + else logger?.warn?.(message); + } + /** The no-engine path cannot judge `where`: say so once per source, never once per event. */ private reportWhereUnenforceable(source: KnowledgeSource): void { if (this.whereUnenforceableReported.has(source.name)) return; @@ -4533,6 +4868,37 @@ function chainAfter( return outcome; } +/** + * [#38413] {@link chainAfter} over several keys at once: run `task` after + * every earlier task chained on any of `keys` has settled, and hold each of + * them until `task` settles. A record-sync batch holds the chain of every + * document it writes. + */ +function chainAfterAll( + tails: Map>, + keys: readonly string[], + task: () => Promise, +): Promise { + const previous = Promise.all(keys.map((key) => tails.get(key) ?? Promise.resolve())); + const outcome = previous.then(task); + const settled = outcome.then(() => undefined, () => undefined); + for (const key of new Set(keys)) { + const tail: Promise = settled.finally(() => { + if (tails.get(key) === tail) tails.delete(key); + }); + tails.set(key, tail); + } + return outcome; +} + +/** [#38413] One group of a record-sync batch: the messages of one source over one object. */ +interface RecordSyncGroup { + source: KnowledgeSource; + object: string; + engine: IDataEngine; + items: Array<{ index: number; recordId: string; publishedAt?: number }>; +} + /** * The sources whose per-record projection of `object` is kept in step * with row changes — i.e. those the service may upsert into, delete from, or @@ -4598,6 +4964,30 @@ async function rereadRow( return rows[0] as Record | undefined; } +/** + * [#38413] {@link rereadRow} for many records in one read: + * `find(object, { where: where AND id in ids, limit: ids.length })` under the + * system context. An id no row came back for does not match (none exists, or + * it does not match `where`). Throws what `find` throws, and throws when + * `find` answers no list. + */ +async function rereadRows( + engine: IDataEngine, + objSource: ObjectKnowledgeSource, + recordIds: readonly string[], +): Promise>> { + const byIds = { id: { $in: [...recordIds] } }; + const rows = await engine.find( + objSource.object, + { where: objSource.where !== undefined ? { $and: [objSource.where, byIds] } : byIds, limit: recordIds.length }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) { + throw new Error(`the re-read of ${recordIds.length} records answered ${describeValue(rows)} instead of a list of rows`); + } + return rows as Array>; +} + /** * Entries one `listDocuments` call asks for. A memory bound per call, not a * contract limit: the adapter may answer fewer. 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 082d1cfa458..2e54018b24c 100644 --- a/packages/services/service-queue/src/db-queue-adapter.test.ts +++ b/packages/services/service-queue/src/db-queue-adapter.test.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ENGINE_DELETE_DISPATCH_CASES, ENGINE_DELETE_REJECT_MESSAGE, @@ -543,3 +543,203 @@ describe('DbQueueAdapter — the claim query and the declared index are held tog expect(declared.some((index) => index.includes(PAGING_TIE_BREAKER))).toBe(false); }); }); + +/** + * [#38413] `IQueueService.subscribeBatch` on the database adapter: a + * batch-consumed queue is claimed up to its `maxBatch`, handed over in one + * call, settled message by message, and drained on a loop of its own — while + * every per-message queue keeps one message per handler call and its + * `batchSize`-per-`pollIntervalMs` pace. + */ +describe('DbQueueAdapter — batch consumption (subscribeBatch)', () => { + const rowsOf = (engine: ReturnType, queue: string) => + (engine.tables.get('sys_job_queue') ?? []).filter((r) => r.queue === queue); + + it('hands up to maxBatch claimed messages to ONE call and settles each by its own outcome', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, defaultMaxAttempts: 2 } }); + for (let i = 0; i < 7; i++) await adapter.publish('kb', { i }); + const calls: number[][] = []; + await adapter.subscribeBatch('kb', async (messages) => { + calls.push(messages.map((m) => (m.data as { i: number }).i)); + return messages.map((m) => ((m.data as { i: number }).i === 3 ? { ok: false as const, error: new Error('poisoned') } : { ok: true as const })); + }, { maxBatch: 5 }); + + expect(await adapter.pollBatchOnce('kb')).toBe(5); + expect(calls).toEqual([[0, 1, 2, 3, 4]]); + const byI = (i: number) => rowsOf(engine, 'kb').find((r) => JSON.parse(r.payload_json).i === i)!; + expect(byI(0).status).toBe('completed'); + expect(byI(4).status).toBe('completed'); + // The failed one alone: back to pending on its backoff, one attempt spent, its error kept. + expect(byI(3).status).toBe('pending'); + expect(byI(3).attempts).toBe(1); + expect(byI(3).last_error).toBe('poisoned'); + expect(byI(5).status).toBe('pending'); + expect(byI(5).attempts).toBe(0); + + // Its last attempt makes it a dead letter; its neighbours are untouched. + byI(3).scheduled_for = new Date(0).toISOString(); + await adapter.pollBatchOnce('kb'); + expect(byI(3).status).toBe('dlq'); + expect(byI(3).attempts).toBe(2); + expect(byI(5).status).toBe('completed'); + expect(byI(6).status).toBe('completed'); + expect((await adapter.listFailed('kb')).map((r) => (r.data as { i: number }).i)).toEqual([3]); + }); + + it('a batch handler that throws, or answers the wrong number of outcomes, fails every message of the batch', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false } }); + for (let i = 0; i < 3; i++) await adapter.publish('kb', { i }); + let mode: 'throw' | 'short' = 'throw'; + await adapter.subscribeBatch('kb', async (messages) => { + if (mode === 'throw') throw new Error('store down'); + return messages.slice(1).map(() => ({ ok: true as const })); + }, { maxBatch: 10 }); + await adapter.pollBatchOnce('kb'); + expect(rowsOf(engine, 'kb').map((r) => [r.status, r.attempts, r.last_error])).toEqual([ + ['pending', 1, 'store down'], ['pending', 1, 'store down'], ['pending', 1, 'store down'], + ]); + for (const r of rowsOf(engine, 'kb')) r.scheduled_for = new Date(0).toISOString(); + mode = 'short'; + await adapter.pollBatchOnce('kb'); + expect(rowsOf(engine, 'kb').map((r) => [r.status, r.attempts])).toEqual([['pending', 2], ['pending', 2], ['pending', 2]]); + expect(rowsOf(engine, 'kb')[0].last_error).toBe('batch handler answered 2 outcome(s) for 3 message(s)'); + }); + + it('a queue takes either per-message handlers or one batch handler; maxBatch must be a positive integer', async () => { + const adapter = new DbQueueAdapter({ engine: makeFakeEngine(), options: { autoStart: false } }); + await adapter.subscribe('mail', async () => {}); + await expect(adapter.subscribeBatch('mail', async (m) => m.map(() => ({ ok: true as const })), { maxBatch: 10 })) + .rejects.toThrow("queue 'mail' already has per-message handlers"); + await adapter.subscribeBatch('kb', async (m) => m.map(() => ({ ok: true as const })), { maxBatch: 10 }); + await expect(adapter.subscribe('kb', async () => {})).rejects.toThrow("queue 'kb' already has a batch handler"); + await expect(adapter.subscribeBatch('kb', async (m) => m.map(() => ({ ok: true as const })), { maxBatch: 10 })) + .rejects.toThrow('a queue takes one'); + await expect(adapter.subscribeBatch('other', async (m) => m.map(() => ({ ok: true as const })), { maxBatch: 0 })) + .rejects.toThrow('maxBatch must be a positive integer, got 0'); + // unsubscribe removes the batch handler: the queue takes per-message handlers again. + await adapter.unsubscribe('kb'); + await adapter.subscribe('kb', async () => {}); + }); + + it('renews every claimed row of a running batch in one compare-and-set write', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, leaseMs: 30 } }); + for (let i = 0; i < 3; i++) await adapter.publish('kb', { i }); + 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); + }; + await adapter.subscribeBatch('kb', async (messages) => { + await new Promise((r) => setTimeout(r, 60)); + return messages.map(() => ({ ok: true as const })); + }, { maxBatch: 10 }); + await adapter.pollBatchOnce('kb'); + expect(renewals.length).toBeGreaterThan(0); + const ids = rowsOf(engine, 'kb').map((r) => r.id); + expect(renewals[0]).toMatchObject({ id: { $in: ids }, status: 'running' }); + expect(rowsOf(engine, 'kb').every((r) => r.status === 'completed')).toBe(true); + }); + + it('drains a backlog without waiting out the poll interval while each claim comes back full', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 1000 } }); + for (let i = 0; i < 250; i++) await adapter.publish('kb', { i }); + const calls: number[] = []; + await adapter.subscribeBatch('kb', async (messages) => { + calls.push(messages.length); + return messages.map(() => ({ ok: true as const })); + }, { maxBatch: 100 }); + // Three claims (100, 100, 50) in well under one poll interval. + await vi.waitFor(() => expect(calls).toEqual([100, 100, 50]), { timeout: 800, interval: 5 }); + await adapter.stop(); + expect(rowsOf(engine, 'kb').every((r) => r.status === 'completed')).toBe(true); + }); + + it('a per-message queue keeps one message per handler call and batchSize per poll interval while a batch queue drains', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 1000 } }); + for (let i = 0; i < 200; i++) await adapter.publish('mail', { i }); + for (let i = 0; i < 1000; i++) await adapter.publish('kb', { i }); + let inFlight = 0; + let maxInFlight = 0; + let mailDone = 0; + await adapter.subscribe('mail', async () => { + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + await new Promise((r) => setImmediate(r)); + inFlight--; + mailDone++; + }); + let kbDone = 0; + await adapter.subscribeBatch('kb', async (messages) => { + kbDone += messages.length; + return messages.map(() => ({ ok: true as const })); + }, { maxBatch: 100 }); + await new Promise((r) => setTimeout(r, 2_500)); + await adapter.stop(); + // Today's pace for the per-message queue: 10 at t=0, 10 at 1 s, 10 at 2 s. + expect(mailDone).toBe(30); + expect(maxInFlight).toBe(1); + expect(kbDone).toBe(1000); + }, 10_000); + + it('getQueueSize counts through the engine when it can count, past the 10,000-row read', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { autoStart: false } }); + const rows = Array.from({ length: 12_000 }, (_, i) => ({ id: `m${i}`, queue: 'kb', status: 'pending' })); + engine.tables.set('sys_job_queue', [...rows, { id: 'done', queue: 'kb', status: 'completed' }, { id: 'x', queue: 'mail', status: 'pending' }]); + // Without `count`, the read stops at 10,000 (the engine double has none). + expect(await adapter.getQueueSize('kb')).toBe(10_000); + const counted: any[] = []; + (engine as any).count = async (table: string, query: any, opts: any) => { + counted.push({ table, query, opts }); + return (engine.tables.get(table) ?? []).filter((r) => r.queue === query.where.queue && r.status === query.where.status).length; + }; + expect(await adapter.getQueueSize('kb')).toBe(12_000); + expect(counted[0]).toMatchObject({ table: 'sys_job_queue', query: { where: { queue: 'kb', status: 'pending' } }, opts: { context: { isSystem: true } } }); + }); + + it('a sole writer keeps the lease entry of every batch row claimed while a main-loop reclaim reads', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false, soleWriter: true } }); + for (let i = 0; i < 3; i++) await adapter.publish('kb', { i }); + const internals = adapter as unknown as { reclaimExpired(): Promise; unsettledLeases: Map }; + 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); + }; + const heldDuringBatch: boolean[] = []; + await adapter.subscribeBatch('kb', async (messages) => { + for (const m of messages) heldDuringBatch.push(internals.unsettledLeases.has(m.id)); + return messages.map(() => ({ ok: true as const })); + }, { maxBatch: 10 }); + + expect(await adapter.pollBatchOnce('kb')).toBe(3); + expect(claims).toBe(3); + expect(heldDuringBatch).toEqual([true, true, true]); + expect(internals.unsettledLeases.size).toBe(0); + }); + + it('one settling write that throws does not stop the rest of the batch from settling', async () => { + const engine = makeFakeEngine(); + const adapter = new DbQueueAdapter({ engine, options: { pollIntervalMs: 60_000, autoStart: false } }); + 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); + }; + 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']); + }); +}); diff --git a/packages/services/service-queue/src/db-queue-adapter.ts b/packages/services/service-queue/src/db-queue-adapter.ts index 07da340e1c7..e3ce2220bfa 100644 --- a/packages/services/service-queue/src/db-queue-adapter.ts +++ b/packages/services/service-queue/src/db-queue-adapter.ts @@ -6,6 +6,9 @@ import type { QueueMessage, QueueMessageRecord, QueueHandler, + QueueBatchHandler, + QueueBatchOutcome, + QueueBatchSubscribeOptions, } from '@objectstack/spec/contracts'; import { SysJobQueue } from '@objectstack/platform-objects/audit'; import { DispatchLoop, DEFAULT_MAX_IDLE_INTERVAL_MS, wakeAfterOpenUnitsCommit } from '@objectstack/core'; @@ -205,6 +208,17 @@ interface RegisteredHandler { fn: QueueHandler; } +/** + * [#38413] The one batch handler of a queue ({@link DbQueueAdapter.subscribeBatch}) + * and the loop that drains that queue alone. + */ +interface RegisteredBatchHandler { + queue: string; + fn: QueueBatchHandler; + maxBatch: number; + loop?: DispatchLoop; +} + /** * DbQueueAdapter — durable, polling, DB-backed IQueueService. * @@ -237,6 +251,14 @@ export class DbQueueAdapter implements IQueueService { private readonly opts: Required> & { workerId: string }; private readonly handlers = new Map(); + /** [#38413] Batch-consumed queues ({@link subscribeBatch}), each drained by its own loop. */ + private readonly batchHandlers = new Map(); + /** + * [#38413] Ids of the rows a batch dispatch holds right now. A batch runs on + * its queue's own loop, so it can be in flight while the main loop's tick + * reclaims ({@link reclaimExpired}); that read must not forget their leases. + */ + private readonly batchInFlight = new Set(); private loop?: DispatchLoop; /** * [#30228] Adapter-clock instant (ms) before which no `running` row can @@ -430,24 +452,84 @@ export class DbQueueAdapter implements IQueueService { // ceiling, rather than up to a backed-off interval late. const untilDueMs = Date.parse(scheduledFor) - now.getTime(); // [#37705] A row written in a unit is visible to the tick once that unit commits. - if (untilDueMs <= 0) wakeAfterOpenUnitsCommit(this.engine, () => this.wake()); - else this.loop?.wakeAt(Date.now() + untilDueMs); + // [#38413] The loop that delivers THIS queue: a batch-consumed queue has + // its own, so a publish to it neither ticks nor paces any other queue. + const loop = (): DispatchLoop | undefined => this.batchHandlers.get(queue)?.loop ?? this.loop; + if (untilDueMs <= 0) wakeAfterOpenUnitsCommit(this.engine, () => loop()?.wake()); + else loop()?.wakeAt(Date.now() + untilDueMs); return id; } async subscribe(queue: string, handler: QueueHandler): Promise { + if (this.batchHandlers.has(queue)) { + throw new Error( + `[service-queue] queue '${queue}' already has a batch handler (subscribeBatch); a queue takes either ` + + 'per-message handlers or one batch handler. Unsubscribe the batch handler first.', + ); + } const existing = this.handlers.get(queue) ?? []; existing.push({ queue, fn: handler as QueueHandler }); this.handlers.set(queue, existing); if (this.opts.autoStart) this.start(); } + /** + * [#38413] `IQueueService.subscribeBatch`: the queue is drained by a loop of + * its own, which claims up to `maxBatch` due rows per tick, hands them to + * `handler` in one call while renewing every claimed row's lease, settles + * each row by its own outcome (completed, another attempt on its backoff, + * or `dlq` once its attempts are spent — the per-message path's settling), + * and ticks again at once while a claim comes back full. Every other queue + * keeps the main loop: its handlers are still called one message at a time, + * at most `batchSize` per `pollIntervalMs`, exactly as before. + */ + async subscribeBatch( + queue: string, + handler: QueueBatchHandler, + options: QueueBatchSubscribeOptions, + ): Promise { + const maxBatch = options?.maxBatch; + if (typeof maxBatch !== 'number' || !Number.isInteger(maxBatch) || maxBatch < 1) { + throw new Error(`[service-queue] subscribeBatch on queue '${queue}': maxBatch must be a positive integer, got ${String(maxBatch)}.`); + } + if (this.handlers.has(queue)) { + throw new Error( + `[service-queue] queue '${queue}' already has per-message handlers (subscribe); a queue takes either ` + + 'per-message handlers or one batch handler. Unsubscribe them first.', + ); + } + if (this.batchHandlers.has(queue)) { + throw new Error(`[service-queue] queue '${queue}' already has a batch handler; a queue takes one. Unsubscribe it first.`); + } + this.batchHandlers.set(queue, { queue, fn: handler as QueueBatchHandler, maxBatch }); + if (this.opts.autoStart) this.start(); + } + async unsubscribe(queue: string): Promise { this.handlers.delete(queue); + const batch = this.batchHandlers.get(queue); + if (batch) { + this.batchHandlers.delete(queue); + const loop = batch.loop; + batch.loop = undefined; + await loop?.stop(); + } } + /** + * The pending messages of `queue`. [#38413] Counted by the engine's `count` + * when it has one (the ObjectQL engine does), so a backlog larger than any + * page is answered exactly; an engine without it is read up to 10,000 rows, + * and the answer then stops at 10,000. + */ async getQueueSize(queue: string): Promise { + // `count` is not on `JobEngine` (a narrow seam every engine double fills); + // the engine the plugin hands in carries it (`IDataEngine.count`). + const counter = (this.engine as JobEngine & { count?: (object: string, query?: unknown, options?: unknown) => Promise }); + if (typeof counter.count === 'function') { + return counter.count(QUEUE_TABLE, { where: { queue, status: 'pending' } }, { context: SYSTEM_CTX }); + } const rows = await this.engine.find(QUEUE_TABLE, { where: { queue, status: 'pending' }, limit: 10_000, @@ -523,6 +605,8 @@ export class DbQueueAdapter implements IQueueService { // ── Worker lifecycle ───────────────────────────────────────────── start(): void { + // [#38413] Each batch-consumed queue drains on its own loop. + for (const batch of this.batchHandlers.values()) this.startBatchLoop(batch); if (this.loop) return; // [#17612] The shared polling loop (`@objectstack/core`), not a bare // `setInterval`: it coalesces overlapping ticks — the job the `running` @@ -543,10 +627,40 @@ export class DbQueueAdapter implements IQueueService { } async stop(): Promise { - if (!this.loop) return; - const loop = this.loop; + const loops: DispatchLoop[] = []; + for (const batch of this.batchHandlers.values()) { + if (batch.loop) loops.push(batch.loop); + batch.loop = undefined; + } + if (this.loop) loops.push(this.loop); this.loop = undefined; - await loop.stop(); + await Promise.all(loops.map((loop) => loop.stop())); + } + + /** + * [#38413] The loop of one batch-consumed queue: the main loop's backoff + * and due-time reads, over that queue alone. A tick that claimed a full + * batch asks for the next at once (a backlog drains at the handler's + * speed); a short or empty one waits as the main loop waits. Reclaiming + * expired leases stays with the main loop, which runs while any queue is + * subscribed. + */ + private startBatchLoop(batch: RegisteredBatchHandler): void { + if (batch.loop) return; + const loop = new DispatchLoop({ + intervalMs: this.opts.pollIntervalMs, + maxIdleIntervalMs: this.opts.maxIdleIntervalMs, + soleWriter: this.opts.soleWriter, + nextDueAt: () => this.dueAt([batch.queue], false), + runTick: async () => { + const claimed = await this.pollBatchOnce(batch.queue); + if (claimed >= batch.maxBatch) loop.wake(); + return claimed; + }, + onTickError: (err) => { this.logger?.warn?.(`DbQueueAdapter: batch poll of ${batch.queue} failed`, err); }, + }); + batch.loop = loop; + loop.start(); } /** @@ -557,6 +671,7 @@ export class DbQueueAdapter implements IQueueService { */ wake(): void { this.loop?.wake(); + for (const batch of this.batchHandlers.values()) batch.loop?.wake(); } /** @@ -566,7 +681,9 @@ export class DbQueueAdapter implements IQueueService { */ async pollOnce(): Promise { const queues = [...this.handlers.keys()]; - if (queues.length === 0) return 0; + // [#38413] A batch-consumed queue is claimed by its own loop + // ({@link pollBatchOnce}), never here; this tick still reclaims for it. + if (queues.length === 0 && this.batchHandlers.size === 0) return 0; let processed = await this.reclaimExpired(); for (const queue of queues) { @@ -579,6 +696,22 @@ export class DbQueueAdapter implements IQueueService { return processed; } + /** + * [#38413] Test-friendly synchronous poll of one batch-consumed queue: + * claim up to its `maxBatch` due rows, hand them to its handler in one + * call, settle each by its own outcome. Answers how many rows it claimed. + */ + async pollBatchOnce(queue: string): Promise { + const batch = this.batchHandlers.get(queue); + 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); + if (claimed.length === 0) return 0; + await this.dispatchBatch(batch, claimed); + return claimed.length; + } + /** * [#29919] When the earliest deferred `pending` row of a subscribed queue * comes due, on the loop's clock (`Date.now()`), or `null` when none is @@ -600,9 +733,18 @@ export class DbQueueAdapter implements IQueueService { */ private async nextDueAt(): Promise { const queues = [...this.handlers.keys()]; - if (queues.length === 0) return null; + if (queues.length === 0 && this.batchHandlers.size === 0) return null; + return this.dueAt(queues, true); + } + + /** + * The due-time read of {@link nextDueAt} over `queues`; `leases` folds in + * the lease expiries only the main loop acts on ([#38413]: a batch loop + * passes `false`, reclaiming stays with the main loop). + */ + private async dueAt(queues: string[], leases: boolean): Promise { const now = this.now(); - const rows = await this.engine.find(QUEUE_TABLE, { + const rows = queues.length === 0 ? [] : await this.engine.find(QUEUE_TABLE, { where: { queue: { $in: queues }, status: 'pending', @@ -617,10 +759,9 @@ export class DbQueueAdapter implements IQueueService { // Instants, not strings — the dialects materialize `scheduled_for` // differently (ISO text on SQLite/turso, a `Date` on Postgres/MySQL). const scheduledMs = cell ? new Date(cell).getTime() : NaN; - const leaseMs = Math.min( - this.earliestLiveLeaseMs ?? Infinity, - this.earliestUnsettledLeaseMs() ?? Infinity, - ); + const leaseMs = leases + ? Math.min(this.earliestLiveLeaseMs ?? Infinity, this.earliestUnsettledLeaseMs() ?? Infinity) + : Infinity; const dueMs = Math.min( Number.isFinite(scheduledMs) ? scheduledMs : Infinity, leaseMs, @@ -695,7 +836,7 @@ export class DbQueueAdapter implements IQueueService { const rows = await this.engine.find(QUEUE_TABLE, { where: { status: 'running' }, fields: [ - 'id', 'locked_by', 'locked_until', 'attempts', 'max_attempts', + 'id', 'queue', 'locked_by', 'locked_until', 'attempts', 'max_attempts', 'backoff_type', 'backoff_delay_ms', 'backoff_max_delay_ms', ], orderBy: [{ field: 'locked_until', order: 'asc' }], @@ -715,12 +856,22 @@ export class DbQueueAdapter implements IQueueService { earliestLive = earliestLive === null ? leaseMs : Math.min(earliestLive, leaseMs); continue; } - if (await this.reclaimRow(row, now)) reclaimed++; + if (await this.reclaimRow(row, now)) { + reclaimed++; + // [#38413] A reclaimed row of a batch-consumed queue is due again on + // that queue's own loop: wake it rather than leave the row to its + // idle backoff. + this.batchHandlers.get(row.queue)?.loop?.wake(); + } } this.earliestLiveLeaseMs = earliestLive; // The read is the truth about every `running` row, this process's own - // included: no dispatch is in flight while a tick reclaims. - this.unsettledLeases.clear(); + // included: no per-message dispatch is in flight while a tick reclaims. + // [#38413] A batch dispatch may be (it runs on its queue's own loop): its + // rows keep their entries, renewed by that dispatch. + for (const id of [...this.unsettledLeases.keys()]) { + if (!this.batchInFlight.has(id)) this.unsettledLeases.delete(id); + } const windowMs = this.opts.soleWriter ? Infinity : nowMs + this.opts.leaseMs; // A full page may hide more expired rows behind it: read again next tick. this.reclaimNotBeforeMs = (rows?.length ?? 0) >= max @@ -795,8 +946,14 @@ export class DbQueueAdapter implements IQueueService { * {@link reclaimExpired} gives — so a lease that was reclaimed underneath * (this worker stalled past it) is not silently taken back. Returns the * stop function {@link dispatch} calls once the handler settles. + * + * [#38413] A batch dispatch renews all its rows in one write + * (`id: { $in: ids }`); fewer rows matched than it holds means a lease was + * lost underneath. */ - private renewLease(id: string): () => void { + private renewLease(idOrIds: string | string[]): () => void { + const ids = typeof idOrIds === 'string' ? [idOrIds] : idOrIds; + const id = typeof idOrIds === 'string' ? idOrIds : { $in: ids }; let inFlight = false; const timer = setInterval(() => { if (inFlight) return; @@ -812,10 +969,12 @@ export class DbQueueAdapter implements IQueueService { context: SYSTEM_CTX, })) .then((res) => { - if (typeof res === 'number' && res === 0) { + if (typeof res === 'number' && res < ids.length) { this.logger?.warn?.('DbQueueAdapter: lease lost while the handler was still running', { id } as any); - } else if (this.unsettledLeases.has(id)) { - this.unsettledLeases.set(id, now.getTime() + this.opts.leaseMs); + } else { + for (const held of ids) { + if (this.unsettledLeases.has(held)) this.unsettledLeases.set(held, now.getTime() + this.opts.leaseMs); + } } }) .catch((err) => { this.logger?.warn?.('DbQueueAdapter: lease renewal failed', err as any); }) @@ -825,7 +984,15 @@ export class DbQueueAdapter implements IQueueService { return () => clearInterval(timer); } - private async claimBatch(queue: string, max: number): Promise { + /** + * 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. + */ + private async claimBatch(queue: string, max: number, inFlight?: Set): Promise { const now = this.now(); const candidates = await this.engine.find(QUEUE_TABLE, { where: { @@ -885,6 +1052,7 @@ 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); @@ -925,12 +1093,21 @@ export class DbQueueAdapter implements IQueueService { stopRenewing(); } + await this.settleRow(row, msg.attempts, success, lastError); + } + + /** + * Settle one dispatched row by its handler's verdict: `completed`, or — + * failed — `dlq` once `attempts` reached its `max_attempts`, else `pending` + * again on its backoff. Shared by {@link dispatch} and {@link dispatchBatch}. + */ + private async settleRow(row: any, attempts: number, success: boolean, lastError: string | undefined): Promise { const now = this.now(); if (success) { await this.engine.update(QUEUE_TABLE, { id: row.id, status: 'completed', - attempts: msg.attempts, + attempts, completed_at: now.toISOString(), locked_by: null, locked_until: null, @@ -940,7 +1117,6 @@ export class DbQueueAdapter implements IQueueService { return; } - const attempts = msg.attempts; const max = row.max_attempts ?? this.opts.defaultMaxAttempts; if (attempts >= max) { await this.engine.update(QUEUE_TABLE, { @@ -971,6 +1147,59 @@ export class DbQueueAdapter implements IQueueService { this.settled(row.id); } + /** + * [#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 + * 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. + */ + private async dispatchBatch(batch: RegisteredBatchHandler, rows: any[]): Promise { + const messages: QueueMessage[] = rows.map((row) => ({ + id: String(row.id), + data: parseJson(row.payload_json), + attempts: (row.attempts ?? 0) + 1, + timestamp: row.created_at ? new Date(row.created_at).getTime() : Date.now(), + })); + const ids = messages.map((m) => m.id); + for (const id of ids) this.batchInFlight.add(id); + let outcomes: QueueBatchOutcome[]; + const stopRenewing = this.renewLease(ids); + try { + const answered = await batch.fn(messages); + outcomes = Array.isArray(answered) && answered.length === messages.length + ? answered + : messages.map(() => ({ + ok: false as const, + error: `batch handler answered ${Array.isArray(answered) ? answered.length : 'no list of'} outcome(s) for ${messages.length} message(s)`, + })); + } catch (err) { + this.logger?.warn?.(`DbQueueAdapter: batch handler failed on ${batch.queue}`, err as any); + outcomes = messages.map(() => ({ ok: false as const, error: err })); + } finally { + stopRenewing(); + } + try { + 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); + } + } + } finally { + for (const id of ids) this.batchInFlight.delete(id); + } + } + private computeBackoff(row: any, attempt: number): number { const base = row.backoff_delay_ms ?? 1000; const cap = row.backoff_max_delay_ms ?? undefined; diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 3de9c282c8d..f012c7992d5 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -322,6 +322,9 @@ "PublishOptions (interface)", "QueryEvaluationGate (interface)", "QueueBackoffPolicy (interface)", + "QueueBatchHandler (type)", + "QueueBatchOutcome (type)", + "QueueBatchSubscribeOptions (interface)", "QueueExpansionPurpose (type)", "QueueHandler (type)", "QueueMemberSpec (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index d34858249d8..4d03a5d5c49 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -322,6 +322,9 @@ "PublishOptions": "src/contracts/cluster-service.ts#PublishOptions (interface)", "QueryEvaluationGate": "src/contracts/objectql-engine.ts#QueryEvaluationGate (interface)", "QueueBackoffPolicy": "src/contracts/queue-service.ts#QueueBackoffPolicy (interface)", + "QueueBatchHandler": "src/contracts/queue-service.ts#QueueBatchHandler (type)", + "QueueBatchOutcome": "src/contracts/queue-service.ts#QueueBatchOutcome (type)", + "QueueBatchSubscribeOptions": "src/contracts/queue-service.ts#QueueBatchSubscribeOptions (interface)", "QueueExpansionPurpose": "src/contracts/ownership-queue-service.ts#QueueExpansionPurpose (type)", "QueueHandler": "src/contracts/queue-service.ts#QueueHandler (type)", "QueueMemberSpec": "src/contracts/ownership-queue-service.ts#QueueMemberSpec (interface)", diff --git a/packages/spec/src/contracts/queue-service.ts b/packages/spec/src/contracts/queue-service.ts index 079486b8be0..e2e172ee6be 100644 --- a/packages/spec/src/contracts/queue-service.ts +++ b/packages/spec/src/contracts/queue-service.ts @@ -92,6 +92,33 @@ export interface QueueMessage { */ export type QueueHandler = (message: QueueMessage) => Promise; +/** + * What a batch handler answers for ONE message of its batch: `ok: true` + * settles it as delivered; `ok: false` takes it down the path a throwing + * {@link QueueHandler} takes — another attempt on its backoff, or the + * dead-letter state once its attempts are spent — with `error` as its + * recorded failure. Each message is settled by its own outcome, so one that + * fails never fails its neighbours. + */ +export type QueueBatchOutcome = { ok: true } | { ok: false; error: unknown }; + +/** + * Handler function for a batch of messages from one queue + * ({@link IQueueService.subscribeBatch}). It answers exactly one outcome per + * message, in the order the messages were handed. A handler that throws, or + * answers a different number of outcomes, fails every message of the batch. + */ +export type QueueBatchHandler = (messages: QueueMessage[]) => Promise; + +/** Options for {@link IQueueService.subscribeBatch}. */ +export interface QueueBatchSubscribeOptions { + /** + * The most messages one handler call receives (a positive integer). Size + * it so a full batch settles well inside the adapter's message lease. + */ + maxBatch: number; +} + export interface IQueueService { /** * Publish a message to a named queue @@ -109,6 +136,25 @@ export interface IQueueService { */ subscribe(queue: string, handler: QueueHandler): Promise; + /** + * Subscribe ONE batch handler to a named queue: each call hands it up to + * `options.maxBatch` messages of that queue, and each message is settled + * by its own {@link QueueBatchOutcome}. An adapter implementing it may + * deliver a backlog faster than per-message delivery; a queue consumed + * this way does not change how any other queue is delivered. + * + * Optional. A consumer that finds it absent subscribes per message with + * {@link subscribe}, which stays correct, only slower. A queue has either + * per-message handlers or one batch handler: an adapter refuses a + * subscription of the other kind on a queue that already has one. + * {@link unsubscribe} removes a batch handler too. + */ + subscribeBatch?( + queue: string, + handler: QueueBatchHandler, + options: QueueBatchSubscribeOptions, + ): Promise; + /** * Unsubscribe from a named queue * @param queue - Queue name