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
10 changes: 10 additions & 0 deletions .changeset/38591-reconcile-skips-pending-sync.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;

/** Rows of one object; `find` applies scalar equality, `$and`, `id: { $gt }` and `id: { $in }`, ordered by id. */
function makeEngine() {
const rows = new Map<string, Row>();
const matches = (row: Row, where: Record<string, unknown> | undefined): boolean => {
if (!where) return true;
for (const [key, value] of Object.entries(where)) {
if (key === '$and') {
if (!(value as Array<Record<string, unknown>>).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<string, unknown>) =>
[...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<string, unknown>; 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<string, unknown> }) => 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<string, KnowledgeDocument>();
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<void> => {
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<string, number>();
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');
});
});
Loading
Loading