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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/38413-knowledge-batch-sync.md
Original file line number Diff line number Diff line change
@@ -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`).
15 changes: 15 additions & 0 deletions .changeset/38413-queue-batch-consume.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions content/docs/kernel/runtime-services/queue-service.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ description: Publish and subscribe to async job queues with services.queue — q
```ts
services.queue.publish<T = unknown>(queue: string, data: T, options?: QueuePublishOptions): Promise<string>
services.queue.subscribe<T = unknown>(queue: string, handler: QueueHandler<T>): Promise<void>
services.queue.subscribeBatch?<T = unknown>(queue: string, handler: QueueBatchHandler<T>, options: QueueBatchSubscribeOptions): Promise<void>
services.queue.unsubscribe(queue: string): Promise<void>
services.queue.getQueueSize?(queue: string): Promise<number>
services.queue.purge?(queue: string): Promise<void>
Expand All @@ -21,6 +22,8 @@ services.queue.replay?(messageId: string): Promise<void>
services.queue.purgeFailed?(messageId: string): Promise<void>
```

`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.)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ type Row = Record<string, unknown>;

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<string, Row>(initial.map((r) => [String(r.id), { ...r }]));
const matches = (row: Row, where: Record<string, unknown> | undefined): boolean => {
Expand All @@ -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;
Expand Down Expand Up @@ -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<typeof makeEngine>['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<typeof makeLogger>) =>
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<void>((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);
});
}
});
Loading
Loading