diff --git a/.changeset/38556-sync-cover-margin.md b/.changeset/38556-sync-cover-margin.md new file mode 100644 index 00000000000..f8b5d7e7bea --- /dev/null +++ b/.changeset/38556-sync-cover-margin.md @@ -0,0 +1,8 @@ +--- +'@objectstack/service-knowledge': patch +--- + +Clause-②: no +Metadata-protocol: none + +A record-sync message now completes as `covered` only when the complete build that covers it began at least 30 s (the queue adapter's default message lease) after the message was published, up from 5 s. The margin guards a sync still in flight as well as clock skew: a sync that re-read a record before a later write, and whose store write landed after the build's walk, could leave the older document in the index while the later write's message was answered `covered`. A message inside the margin is synced as usual, which is the only cost. A sync in flight for longer than the margin stays uncovered until the next build that purges. diff --git a/packages/services/service-knowledge/src/knowledge-record-sync-cover-margin.test.ts b/packages/services/service-knowledge/src/knowledge-record-sync-cover-margin.test.ts new file mode 100644 index 00000000000..7b01ee168a9 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-record-sync-cover-margin.test.ts @@ -0,0 +1,156 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `covered` margin ({@link RECORD_SYNC_COVER_MARGIN_MS}) guards a sync + * still in flight as well as clock skew: a message published inside the + * margin of a complete build's start is synced, so a document an in-flight + * sync wrote late over the walk's is repaired by the later write's message. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { AdapterContext, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { DbQueueAdapter, type JobEngine } from '@objectstack/service-queue'; +import { KnowledgeService } from './knowledge-service.js'; +import { RECORD_SYNC_COVER_MARGIN_MS } 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(initial: Row[]) { + const rows = new Map(initial.map((r) => [String(r.id), { ...r }])); + 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 find = vi.fn(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 })); + }); + const count = vi.fn(async (_object: string, query?: { where?: Record }) => select(query?.where).length); + return { rows, find, engine: { find, count } as unknown as IDataEngine }; +} + +/** An adapter that lists its documents, so a complete build runs its purge. */ +function makeAdapter() { + const docs = new Map(); + const held: { fingerprint?: string; recipeHash?: string } = {}; + const adapter: IKnowledgeAdapter = { + id: 'memory', + embedding: { model: 'model-a', dimensions: 3 }, + async upsert(batch: KnowledgeDocument[]) { + for (const doc of batch) 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 }; +} + +const SOURCE: KnowledgeSource = { + name: 'kb', + label: 'Knowledge base', + adapter: 'memory', + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'] }, +}; + +const message = (recordId: string) => ({ source: 'kb', object: 'kb_article', recordId, reason: 'event' }); + +/** A complete build of `kb` that ended `done` with its purge run, and when it began (epoch ms). */ +async function afterPurgingBuild() { + const db = makeEngine([ + { id: 'a1', title: 'Leave policy', body: 'Twenty days of paid leave' }, + { id: 'a2', title: 'Travel policy', body: 'Economy class under six hours' }, + ]); + const { adapter, docs } = makeAdapter(); + const service = new KnowledgeService({ + dataEngine: db.engine, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + service.registerAdapter('memory', adapter); + service.registerSource(SOURCE); + const record = await service.rebuildSource('kb', { trigger: 'operator' }); + expect(record).toMatchObject({ status: 'done', result: { purged: 0 } }); + const startedAt = Date.parse(record.startedAt); + expect(Number.isFinite(startedAt)).toBe(true); + return { service, docs, db, startedAt }; +} + +describe('record sync — the covered margin guards a sync still in flight', () => { + it('is the queue adapter\'s default message lease', () => { + const queue = new DbQueueAdapter({ engine: {} as unknown as JobEngine, options: { autoStart: false } }); + const leaseMs = (queue as unknown as { opts: { leaseMs: number } }).opts.leaseMs; + expect(RECORD_SYNC_COVER_MARGIN_MS).toBe(leaseMs); + }); + + it('a message published inside the margin of the build\'s start is synced, and repairs a document an in-flight sync wrote late', async () => { + const { service, docs, db, startedAt } = await afterPurgingBuild(); + // The record was written 10 s before the build began; a sync that read it + // before that write landed its store write after the walk's. + db.rows.get('a1')!.title = 'Leave policy (revised)'; + const walked = docs.get('kb:a1')!; + docs.set('kb:a1', { ...walked, content: 'Leave policy\nTwenty days of paid leave' }); + const publishedAt = startedAt - 10_000; + + expect(await service.processRecordSync(message('a1'), publishedAt)).toBe('synced'); + expect(docs.get('kb:a1')!.content).toContain('Leave policy (revised)'); + + const batch = await service.processRecordSyncBatch([{ data: message('a2'), publishedAt }]); + expect(batch).toEqual([{ ok: true, outcome: 'synced' }]); + }); + + it('a message published more than the margin before the build\'s start is covered', async () => { + const { service, db, startedAt } = await afterPurgingBuild(); + const publishedAt = startedAt - RECORD_SYNC_COVER_MARGIN_MS - 1; + const reads = db.find.mock.calls.length; + + expect(await service.processRecordSync(message('a1'), publishedAt)).toBe('covered'); + const batch = await service.processRecordSyncBatch([{ data: message('a2'), publishedAt }]); + expect(batch).toEqual([{ ok: true, outcome: 'covered' }]); + expect(db.find.mock.calls.length).toBe(reads); + }); +}); 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 6ea891a66b8..5cd069403a5 100644 --- a/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts +++ b/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts @@ -209,12 +209,29 @@ 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. + * for that build to cover it (`covered`). A message inside the margin is + * synced as usual; that normal sync is the margin's only cost. It guards two + * things: + * + * - clock skew: the publish time is stamped by the publishing node's queue + * and the build's start by the building node's clock; + * - a sync still in flight: a sync that re-read the record before a later + * write, and whose store write lands after the build's walk wrote the + * record (or after its listing, for a record created and then deleted), + * leaves the older document in the index. The later write's message must + * then be synced, not covered, and it is whenever the build began within + * the margin of that write. + * + * The margin is the queue adapter's default message lease + * (`DbQueueAdapterOptions.leaseMs`, 30 s), which a batch is sized to settle + * well inside (`QueueBatchSubscribeOptions.maxBatch`). What stays uncovered: + * a sync in flight for longer than the margin (a live handler keeps renewing + * its lease, so the lease does not bound it; a slow embedding provider is the + * way there), plus skew beyond what the sync's own time leaves of the margin. + * Such a stale document stays until the next build that purges, which is + * where ADR-0161 K1 puts an index's correctness. */ -export const RECORD_SYNC_COVER_MARGIN_MS = 5_000; +export const RECORD_SYNC_COVER_MARGIN_MS = 30_000; /** One message handed to `KnowledgeService.processRecordSyncBatch`: its payload, and when the queue says it was published (epoch ms). */ export interface KnowledgeRecordSyncBatchItem {