diff --git a/.changeset/38591-reconcile-skips-pending-sync.md b/.changeset/38591-reconcile-skips-pending-sync.md new file mode 100644 index 00000000000..d3c6cdd97a3 --- /dev/null +++ b/.changeset/38591-reconcile-skips-pending-sync.md @@ -0,0 +1,10 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a backlog reconcile asked for during a bulk import waits until the import's record syncs have drained + +Clause-②: no +Metadata-protocol: none + +When the record-sync backlog of a source is no larger than the source's rows (a bulk import or bulk update: about one message per record), the reconcile the batch worker schedules for it now starts only once that backlog has drained, and then writes only the rows no record sync reached. Before, it walked beside the drain, and since a message is covered only when it was published 30 s before the walk began, every imported record was embedded and written twice: about twice the embedding requests and twice the vector writes of a rebuild. A backlog that outnumbers the source's rows (repeated saves, rows deleted or moved out of `where`) is still walked beside the drain, as before. A queue that does not drain within an hour starts the walk anyway. No option, setting or error code changes. diff --git a/packages/services/service-knowledge/src/__tests__/reconcile-during-import-38591.test.ts b/packages/services/service-knowledge/src/__tests__/reconcile-during-import-38591.test.ts new file mode 100644 index 00000000000..5e5293965e4 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/reconcile-during-import-38591.test.ts @@ -0,0 +1,252 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38591] A backlog reconcile that starts during a bulk import is deferred + * until the import's record syncs have drained. + * + * A message is covered by a build only when it was published + * `RECORD_SYNC_COVER_MARGIN_MS` before the build began, and the drain syncs + * every message it takes while a walk runs. So a walk beside an import + * (about one message per record) embedded and wrote each record a second + * time. A backlog no larger than the source's rows now waits for the drain, + * and the walk then writes only the rows no message reached. + * + * What is pinned: + * + * - a reconcile asked for during a pending import embeds no record that has + * a pending message, and each imported record is written once, by its sync; + * - a record with no sync message at all is still reconciled, once the + * import has drained; + * - a queue that never drains does not hold the walk off for good; + * - builds stopped while the walk waits: nothing is walked. + * + * A backlog that outnumbers the rows is still walked beside the drain: that + * is pinned by the #38413 suite in `knowledge-build.test.ts`, unchanged. + */ + +import { afterEach, describe, it, expect, vi } from 'vitest'; +import type { AdapterContext, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { + RECORD_SYNC_BACKLOG_READ_INTERVAL_MS, + RECORD_SYNC_BACKLOG_RETRY_MAX_MS, + RECORD_SYNC_BATCH_SIZE, +} from '../knowledge-record-sync-queue.js'; + +type Row = Record; + +/** Rows of one object; `find` applies scalar equality, `$and`, `id: { $gt }` and `id: { $in }`, ordered by id. */ +function makeEngine() { + const rows = new Map(); + const matches = (row: Row, where: Record | undefined): boolean => { + if (!where) return true; + for (const [key, value] of Object.entries(where)) { + if (key === '$and') { + if (!(value as Array>).every((c) => matches(row, c))) return false; + 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; + continue; + } + if (row[key] !== value) return false; + } + return true; + }; + const select = (where?: Record) => + [...rows.values()].filter((r) => matches(r, where)).sort((a, b) => String(a.id).localeCompare(String(b.id))); + const engine = { + find: async (_object: string, query?: { where?: Record; limit?: number }) => { + const all = select(query?.where); + return (typeof query?.limit === 'number' ? all.slice(0, query.limit) : all).map((r) => ({ ...r })); + }, + count: async (_object: string, query?: { where?: Record }) => select(query?.where).length, + } as unknown as IDataEngine; + return { rows, engine }; +} + +/** + * A store that lists its documents (so a reconcile skips an unchanged one and + * purges), and records every document it is asked to write with the reason + * of the call: `reindex` for a walk, `event-sync` for a record sync. + */ +function makeAdapter() { + const docs = new Map(); + const held: { fingerprint?: string; recipeHash?: string } = {}; + const writes: Array<{ reason: string; id: string }> = []; + const adapter: IKnowledgeAdapter = { + id: 'memory', + embedding: { model: 'model-a', dimensions: 3 }, + async upsert(batch: KnowledgeDocument[], ctx?: AdapterContext) { + for (const doc of batch) { + writes.push({ reason: String(ctx?.reason), id: doc.id }); + docs.set(doc.id, doc); + } + }, + async delete(ids: string[]) { + for (const id of ids) docs.delete(id); + }, + async search() { + return []; + }, + async listDocuments(_ctx: AdapterContext, page: { cursor?: string; limit: number }) { + const all = [...docs.values()].map((d) => ({ documentId: d.id, ...(d.docHash ? { docHash: d.docHash } : {}) })); + const start = page.cursor === undefined ? 0 : Number(page.cursor); + const slice = all.slice(start, start + page.limit); + return { documents: slice, ...(start + page.limit < all.length ? { nextCursor: String(start + page.limit) } : {}) }; + }, + async indexStatus() { + return { ...held }; + }, + async beginBuild(ctx: AdapterContext) { + if (held.fingerprint !== ctx.index!.fingerprint) { + docs.clear(); + held.fingerprint = ctx.index!.fingerprint; + delete held.recipeHash; + } + }, + async completeBuild(ctx: AdapterContext) { + held.fingerprint = ctx.index!.fingerprint; + held.recipeHash = ctx.index!.recipeHash; + }, + }; + return { adapter, docs, writes }; +} + +const SOURCE: KnowledgeSource = { + name: 'kb', + label: 'Knowledge base', + adapter: 'memory', + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'] }, +}; + +/** Over the threshold (5,000) and no larger than the source's rows: an import's backlog. */ +const IMPORTED = 6_000; + +const message = (recordId: string) => ({ source: 'kb', object: 'kb_article', recordId, reason: 'event' }); + +/** + * An index made current over an empty table, then an import of + * {@link IMPORTED} rows, each with one message waiting on the queue, plus + * the `orphans`: rows written with no message (a publish that failed). + */ +async function importPending(orphans: string[] = []) { + const db = makeEngine(); + const store = makeAdapter(); + const service = new KnowledgeService({ + dataEngine: db.engine, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + service.registerAdapter('memory', store.adapter); + service.registerSource(SOURCE); + expect(await service.rebuildSource('kb', { trigger: 'operator' })).toMatchObject({ status: 'done' }); + + const imported = Array.from({ length: IMPORTED }, (_, i) => `imp${String(i).padStart(5, '0')}`); + for (const id of [...imported, ...orphans]) db.rows.set(id, { id, title: `Clause ${id}`, body: `Body of ${id}` }); + const queue = { pending: imported.length }; + service.useRecordSyncQueue({ + getQueueSize: async () => queue.pending, + listFailed: async () => [], + purgeFailed: async () => undefined, + }); + /** Ids whose message has not been taken yet. */ + const waiting = new Set(imported); + + /** The worker takes the next batch (it leaves the waiting count) and answers it; a second passes. */ + const drainOne = async (): Promise => { + const batch = [...waiting].slice(0, RECORD_SYNC_BATCH_SIZE); + for (const id of batch) waiting.delete(id); + queue.pending = waiting.size; + const results = await service.processRecordSyncBatch( + batch.map((id) => ({ data: message(id), publishedAt: Date.now() })), + ); + expect(results.every((r) => r.ok && r.outcome === 'synced')).toBe(true); + await vi.advanceTimersByTimeAsync(1_000); + }; + const walked = () => store.writes.filter((w) => w.reason === 'reindex').map((w) => w.id); + const reconciled = async () => { + await vi.waitFor(() => { + const record = service.buildRecord('kb'); + if (record?.trigger !== 'reconcile' || record.status === 'running') throw new Error('the reconcile has not ended'); + }, { timeout: 5_000, interval: 5 }); + expect(service.buildRecord('kb')).toMatchObject({ trigger: 'reconcile', status: 'done' }); + }; + return { service, store, queue, imported, waiting, drainOne, walked, reconciled }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('backlog reconcile during a bulk import (#38591)', () => { + it('a reconcile started during a pending import embeds no record that has a pending message', async () => { + vi.useFakeTimers(); + const t = await importPending(); + + while (t.waiting.size > 0) { + await t.drainOne(); + // No walk has written a record whose message is still waiting. + expect(t.walked().filter((id) => t.waiting.has(id.slice('kb:'.length)))).toEqual([]); + } + + // Drained: the reconcile asked for during the import walks now. + await vi.advanceTimersByTimeAsync(RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + await t.reconciled(); + // Every imported record was embedded and written once, by its own sync. + expect(t.walked()).toEqual([]); + const perDocument = new Map(); + for (const w of t.store.writes) perDocument.set(w.id, (perDocument.get(w.id) ?? 0) + 1); + expect(perDocument.size).toBe(IMPORTED); + expect([...perDocument.values()].every((n) => n === 1)).toBe(true); + }); + + it('a record with no sync message is still reconciled, once the import has drained', async () => { + vi.useFakeTimers(); + const t = await importPending(['orphan']); + + while (t.waiting.size > 0) { + // Not walked while the import's messages wait. + expect(t.store.docs.has('kb:orphan')).toBe(false); + await t.drainOne(); + } + + await vi.advanceTimersByTimeAsync(RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + await t.reconciled(); + expect(t.walked()).toEqual(['kb:orphan']); + expect(t.store.docs.size).toBe(IMPORTED + 1); + }); + + it('a queue that does not drain holds the walk off for a bounded time, not for good', async () => { + vi.useFakeTimers(); + const t = await importPending(['orphan']); + await t.drainOne(); + // Other syncs keep the queue busy: the waiting count never falls. + t.queue.pending = 50_000; + + await vi.advanceTimersByTimeAsync(RECORD_SYNC_BACKLOG_RETRY_MAX_MS - 2 * RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + expect(t.walked()).toEqual([]); + await vi.advanceTimersByTimeAsync(2 * RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + await t.reconciled(); + expect(t.walked()).toContain('kb:orphan'); + }); + + it('builds stopped while the walk waits for the drain: nothing is walked', async () => { + vi.useFakeTimers(); + const t = await importPending(['orphan']); + await t.drainOne(); + t.service.stopBuilds(); + while (t.waiting.size > 0) await t.drainOne(); + + await vi.advanceTimersByTimeAsync(2 * RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + expect(t.walked()).toEqual([]); + expect(t.service.buildRecord('kb')?.trigger).toBe('operator'); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts index e0648a07dd4..8cdba5dc3e6 100644 --- a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts +++ b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts @@ -641,12 +641,19 @@ export async function sourceRowCount( * ({@link coveredByBuild}) complete without a read once it ends. A source * the reconcile does not walk ({@link reconcileExclusion}) is never * scheduled. Never rejects. + * + * [#38591] Where the estimate is no larger than the source's rows (a bulk + * import or update: about one message per record), the walk is deferred + * until the backlog has drained ({@link backlogDrained}): the drain embeds + * and writes each of those records once, and the walk then writes only the + * rows no message reached. Only a backlog that outnumbers the source's rows + * is walked beside the drain. */ export async function considerBacklogReconcile( this: Pick< KnowledgeRecordSyncHost, 'backlogReconciles' | 'builds' | 'buildsStopped' | 'enqueueReconcile' | 'held' | 'options' | - 'reconcileExclusion' | 'recordSyncWaiting' | 'registry' | 'sourceRowCount' + 'pendingRecordSyncs' | 'reconcileExclusion' | 'recordSyncWaiting' | 'registry' | 'sourceRowCount' >, group: RecordSyncGroup, batchLength: number, @@ -667,33 +674,117 @@ export async function considerBacklogReconcile( const next = { running: true, notBefore: Number.POSITIVE_INFINITY, failures: state?.failures ?? 0 }; this.backlogReconciles.set(key, next); + // [#38591] A backlog no larger than the source's rows (a bulk import, a bulk + // update) is about one message per record, so the drain already embeds each + // of them once, and a walk beside it would embed the same records again: it + // could cover only the messages published RECORD_SYNC_COVER_MARGIN_MS before + // it began, and the drain syncs every message it takes while the walk runs. + // So the walk waits until the backlog has drained, and then writes only the + // rows no message reached (the walk skips a document the drain already wrote + // unchanged). A backlog that outnumbers the rows (repeated saves, rows that + // left `where` or were deleted) is walked beside the drain, as before: one + // walk is cheaper than its messages, and it covers them. + const deferred = estimate <= rows; 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.', + deferred + ? `[knowledge] source '${entry.face}': about ${estimate} record syncs are waiting for its ${rows} row(s), so one ` + + 'reconcile of the source is scheduled for when they have drained: they sync those records meanwhile, and the ' + + 'reconcile then writes only the rows no record sync reached.' + : `[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.', ); - void this.enqueueReconcile(() => { - const current = this.registry.byIndexKey(key); - return current === undefined ? [] : [current]; - }) - .then(() => undefined, () => undefined) - .then(() => { + const share = group.items.length / batchLength; + const ready = deferred ? backlogDrained.call(this, key, share) : Promise.resolve(true); + void ready.then(async (walk) => { + if (!walk) { + // Stopped, held, or the source is gone or no longer walked: nothing + // ran, so a later backlog may ask again at once. 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.notBefore = Date.now(); + return; + } + await this.enqueueReconcile(() => { + const current = this.registry.byIndexKey(key); + return current === undefined ? [] : [current]; + }).then(() => undefined, () => undefined); + 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.`, + ); + }); +} + +/** + * [#38591] When the deferred reconcile of {@link considerBacklogReconcile} + * may walk the source under `key`: `true` once its record-sync backlog has + * drained, that is once the queue's waiting count (read afresh every + * {@link RECORD_SYNC_BACKLOG_READ_INTERVAL_MS}), times `share`, the source's + * share of the batch that scheduled the reconcile, is under one message. A + * count that fails is read as not drained. A queue that does not drain within + * {@link RECORD_SYNC_BACKLOG_RETRY_MAX_MS} (other sources' syncs keep it + * busy) cannot hold the walk off for good: it answers `true` then. `false`, + * and nothing is walked, once builds are stopped, the service is held, or + * the source is gone or no longer walked. Never rejects. + */ +export function backlogDrained( + this: Pick< + KnowledgeRecordSyncHost, + 'buildsStopped' | 'held' | 'options' | 'pendingRecordSyncs' | 'reconcileExclusion' | 'registry' + >, + key: string, + share: number, +): Promise { + const until = Date.now() + RECORD_SYNC_BACKLOG_RETRY_MAX_MS; + return new Promise((resolve) => { + const wait = (): void => { + const timer = setTimeout(() => { void check(); }, RECORD_SYNC_BACKLOG_READ_INTERVAL_MS); + (timer as { unref?: () => void }).unref?.(); + }; + const check = async (): Promise => { + try { + const entry = this.registry.byIndexKey(key); + if (!entry || this.buildsStopped || this.held || this.reconcileExclusion(entry) !== undefined) { + resolve(false); + return; + } + let waiting: number | undefined; + try { + waiting = await this.pendingRecordSyncs(); + } catch { + waiting = undefined; + } + if (waiting !== undefined && waiting * share < 1) { + resolve(true); + return; + } + if (Date.now() >= until) { + this.options.logger?.info?.( + `[knowledge] source '${entry.face}': the record-sync queue has not drained in ` + + `${Math.round(RECORD_SYNC_BACKLOG_RETRY_MAX_MS / 60_000)} min, so the reconcile scheduled for its backlog ` + + 'starts now, beside the record syncs still waiting.', + ); + resolve(true); + return; + } + wait(); + } catch { + resolve(false); } - 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.`, - ); - }); + }; + wait(); + }); } /**