From 1dff66d3f270563d9eea3974563b5c7237b5043b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:35:58 +0000 Subject: [PATCH 01/13] wip(service-knowledge): listDocuments, docHash, reindex skip and purge, adapter contract suite Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .../src/__tests__/contract.test.ts | 14 + .../plugins/knowledge-memory/src/index.ts | 33 ++ .../plugins/knowledge-memory/vitest.config.ts | 9 +- .../services/service-knowledge/package.json | 8 +- .../src/knowledge-service-plugin.ts | 14 +- .../src/knowledge-service.ts | 305 +++++++++++++++-- .../services/service-knowledge/src/testing.ts | 323 ++++++++++++++++++ .../services/service-knowledge/tsup.config.ts | 35 ++ .../spec/src/ai/knowledge-document.zod.ts | 10 + .../spec/src/contracts/knowledge-adapter.ts | 53 +++ 10 files changed, 774 insertions(+), 30 deletions(-) create mode 100644 packages/plugins/knowledge-memory/src/__tests__/contract.test.ts create mode 100644 packages/services/service-knowledge/src/testing.ts create mode 100644 packages/services/service-knowledge/tsup.config.ts diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts new file mode 100644 index 00000000000..5a01432e5d9 --- /dev/null +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -0,0 +1,14 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1), run against the +// reference adapter. Every adapter package runs the same suite with its own +// factory; a fresh adapter per case keeps the cases independent. + +import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; +import { KnowledgeMemoryAdapter } from '../index'; + +runKnowledgeAdapterContract({ + name: 'knowledge-memory', + makeAdapter: () => new KnowledgeMemoryAdapter('under_test'), + implements: { listDocuments: true }, +}); diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 4f56deaa4a4..2e8e3b69a0d 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -4,6 +4,8 @@ import type { IKnowledgeAdapter, IKnowledgeService, AdapterContext, + AdapterListDocumentsOptions, + AdapterListDocumentsPage, AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { @@ -20,6 +22,11 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; * * Deterministic — same input always produces the same hits — so it's * great for tests and reference implementations. **Don't use in prod.** + * + * The reference implementation of `listDocuments` (ADR-0161 K8, item 1): it + * stores each document's `docHash` as given and lists it back as stored, in + * document-id order, the cursor being the last id of the page before. It runs + * the contract suite of `@objectstack/service-knowledge/testing`. */ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { readonly id: string; @@ -55,6 +62,29 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { ); } + async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise { + if (!Number.isInteger(opts.limit) || opts.limit < 1) { + throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`); + } + // One entry per document, from its first chunk (every chunk carries the + // document's hash), in id order so a cursor stays valid across writes. + const byDoc = new Map(); + for (const c of this.store.get(ctx.source.id) ?? []) { + if (!byDoc.has(c.documentId)) byDoc.set(c.documentId, c.docHash); + } + const ids = [...byDoc.keys()] + .filter((id) => opts.cursor === undefined || id > opts.cursor) + .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + const page = ids.slice(0, opts.limit); + return { + documents: page.map((documentId) => { + const docHash = byDoc.get(documentId); + return docHash === undefined ? { documentId } : { documentId, docHash }; + }), + ...(ids.length > page.length ? { nextCursor: page[page.length - 1] } : {}), + }; + } + async search(query: string, opts: AdapterSearchOptions): Promise { const chunks = this.store.get(opts.source.id) ?? []; if (chunks.length === 0) return []; @@ -94,6 +124,8 @@ interface ChunkRecord { chunkId: string; documentId: string; sourceRecordId?: string; + /** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */ + docHash?: string; content: string; title?: string; metadata: Record; @@ -134,6 +166,7 @@ function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] { chunkId: `${doc.id}#${idx}`, documentId: doc.id, sourceRecordId: doc.sourceRecordId, + docHash: doc.docHash, content, title: doc.title, metadata: doc.metadata ?? {}, diff --git a/packages/plugins/knowledge-memory/vitest.config.ts b/packages/plugins/knowledge-memory/vitest.config.ts index e9052fa159f..4bf9c2f3d65 100644 --- a/packages/plugins/knowledge-memory/vitest.config.ts +++ b/packages/plugins/knowledge-memory/vitest.config.ts @@ -25,8 +25,15 @@ export default defineConfig({ { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + // `./testing` (the adapter contract suite) BEFORE the bare package, and both + // anchored: a string `find` matches by PREFIX, so the bare entry would + // resolve the subpath to `…/src/index.ts/testing` — ENOTDIR at run time. { - find: '@objectstack/service-knowledge', + find: /^@objectstack\/service-knowledge\/testing$/, + replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'), + }, + { + find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'), }, // #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place diff --git a/packages/services/service-knowledge/package.json b/packages/services/service-knowledge/package.json index 135ce83fc86..7f6c79c1ea6 100644 --- a/packages/services/service-knowledge/package.json +++ b/packages/services/service-knowledge/package.json @@ -17,10 +17,16 @@ "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } + }, + "./testing": { + "import": { + "types": "./dist/testing.d.ts", + "default": "./dist/testing.js" + } } }, "scripts": { - "build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs", + "build": "rm -rf dist && tsup && node ../../../scripts/check-dts-emitted.mjs", "test": "vitest run", "typecheck": "tsc --noEmit && pnpm check:test-typecheck", "check:test-typecheck": "tsx ../../../scripts/check-test-typecheck.mts --self-test && tsx ../../../scripts/check-test-typecheck.mts --package packages/services/service-knowledge --project tsconfig.test.json" diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 707a10b6458..86662c72f49 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -270,9 +270,10 @@ export class KnowledgeServicePlugin implements Plugin { // half-claimed, and stays so until a real object source justifies the // adapter-enumeration surface it would need (#4606's enforced-first // rule). Reporting it accurately is the whole job of this branch. - // An explicit reindexSource refreshes the rows that still exist and - // match; it removes no documents, so a predicate DELETE stays stale - // until the index purge (#37096) — the warning says so. + // A complete reindexSource refreshes the rows that still exist and + // match and, over an adapter that lists its documents, purges the + // documents of rows that are gone or no longer match — the warning + // says so, and names the adapter case it cannot repair. if (type === 'data.records.updated' || type === 'data.records.deleted') { const matched = payload.matched; ctx.logger.warn?.( @@ -282,9 +283,10 @@ export class KnowledgeServicePlugin implements Plugin { 'may now be stale and cannot be repaired from the event stream. ' + 'Retention-sweep deletes are covered separately: the lifecycle reap guard de-indexes those rows ' + 'before they are deleted; ' + - 'application-level predicate writes are not. An explicit reindexSource refreshes the documents of rows ' + - 'that still exist and match; it removes none, so the documents of deleted rows stay in the index ' + - 'until an index purge removes them.', + 'application-level predicate writes are not. A complete reindexSource (no limit, no dryRun) refreshes ' + + 'the documents of rows that still exist and match, and purges the documents of rows that are gone or ' + + 'no longer match when the source\'s adapter lists its documents; over an adapter that does not, they ' + + 'stay in the index.', { object, type, matched }, ); return; diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 90a2f6653f6..1fc0e0cc939 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -1,5 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +import { createHash } from 'node:crypto'; import type { IDataEngine, IKnowledgeAdapter, @@ -160,7 +161,9 @@ export class KnowledgeService implements IKnowledgeService { async indexDocument(sourceId: string, doc: KnowledgeDocument): Promise { const source = this.requireSource(sourceId); const adapter = this.getAdapter(source.adapter); - await adapter.upsert([doc], { source, reason: 'manual' }); + // `docHash` is the service's to compute (ADR-0161 K8, item 2): a caller's + // own value is replaced, never passed through. + await adapter.upsert([{ ...doc, docHash: computeDocHash(doc) }], { source, reason: 'manual' }); } async deleteDocument(sourceId: string, documentId: string): Promise { @@ -211,9 +214,29 @@ export class KnowledgeService implements IKnowledgeService { * Record events do NOT wait for a walk: the record sync has its own * per-document chain. A row updated or deleted between a page's read and * that page's upsert is written back from the older read — a deleted row's - * document then stays in the index as a ghost, because a reindex removes no - * documents (documents of rows that no longer exist or no longer match wait - * for the index purge, #37096). + * document then stays in the index as a ghost until the next complete walk + * purges it (below), or the row's next event repairs it. + * + * ## Skip and purge (ADR-0161 K8, items 1–2) + * + * When the adapter implements `listDocuments`, the walk first lists what the + * adapter holds for the source (document id → stored `docHash`). A row whose + * document's computed `docHash` equals the listed one is not upserted again + * (`skipped`); every other document is (`indexed`). + * + * After a COMPLETE walk — no `limit`, no `dryRun`, every page done — the + * documents listed before the walk that the walk did not see are purge + * candidates, handed to {@link purgeDocuments}: each is confirmed by the + * same re-read the event sync makes (`where` AND id) and deleted only when + * that re-read finds no row, so a row created or restored meanwhile keeps its + * document. A document written during the walk was not listed, and so is + * never a candidate. `purged` counts the deletions. + * + * `purged` is `null` when no purge ran: a walk with a `limit` or a `dryRun`, + * a failed walk, a source with `refresh.onRecordChange: false` (an external + * indexer owns its index), or an adapter without `listDocuments` — which + * also skips nothing, the walk otherwise as before. A listing that fails + * skips and purges nothing either; the result's `message` says so. */ async reindexSource( sourceId: string, @@ -228,6 +251,8 @@ export class KnowledgeService implements IKnowledgeService { ok: false, discovered: 0, indexed: 0, + skipped: 0, + purged: null, message: `Reindex for kind=${source.source.kind} is not handled by KnowledgeService. ` + `Trigger ingestion through the adapter (${source.adapter}) directly.`, @@ -240,6 +265,8 @@ export class KnowledgeService implements IKnowledgeService { ok: false, discovered: 0, indexed: 0, + skipped: 0, + purged: null, message: 'KnowledgeService has no IDataEngine bound; cannot walk object source.', }; } @@ -267,6 +294,8 @@ export class KnowledgeService implements IKnowledgeService { object, discovered: 0, indexed: 0, + skipped: 0, + purged: null, message: `reindex of source '${source.id}' refused: limit must be a non-negative finite number, got ${String(opts.limit)}.`, }; } @@ -281,13 +310,26 @@ export class KnowledgeService implements IKnowledgeService { object, discovered: cap === undefined ? total : Math.min(total, cap), indexed: 0, + skipped: 0, + purged: null, message: 'dryRun=true; no documents pushed.', }; } + // What the adapter holds before the walk: the skip's hashes, and the + // purge's candidates once the walk is complete. + const listing = await listAdapterDocuments(source, adapter); + const listed = listing.ok ? listing.documents : undefined; + const listingNote = listing.ok || listing.reason === undefined + ? undefined + : `the adapter's document listing failed (${listing.reason}), so no document was skipped and none was purged.`; + if (listingNote) this.options.logger?.warn?.(`[knowledge] reindex of source '${source.id}': ${listingNote}`); + const schema = this.schemaFor(object); + const seen = new Set(); let discovered = 0; let indexed = 0; + let skipped = 0; let cursor: string | number | undefined; for (let page = 1; ; page++) { const want = cap === undefined ? REINDEX_PAGE_SIZE : Math.min(REINDEX_PAGE_SIZE, cap - discovered); @@ -298,6 +340,8 @@ export class KnowledgeService implements IKnowledgeService { object, discovered, indexed, + skipped, + purged: null, message: `reindex of source '${source.id}' stopped at page ${page}${after}: ${what}`, }); @@ -330,13 +374,25 @@ export class KnowledgeService implements IKnowledgeService { } catch (err) { return stopped(`building the page's documents failed: ${errorText(err)}`); } - try { - await adapter.upsert(docs, { source, reason: 'reindex' }); - } catch (err) { - return stopped(`the adapter upsert failed: ${errorText(err)}`); + // A document whose computed hash equals the one the adapter listed for it + // is unchanged: it is not written again. + const changed = listed === undefined + ? docs + : docs.filter((doc) => { + const stored = listed.get(doc.id); + return stored === undefined || stored !== doc.docHash; + }); + if (changed.length > 0) { + try { + await adapter.upsert(changed, { source, reason: 'reindex' }); + } catch (err) { + return stopped(`the adapter upsert failed: ${errorText(err)}`); + } } + for (const doc of docs) seen.add(doc.id); discovered += rows.length; - indexed += docs.length; + indexed += changed.length; + skipped += docs.length - changed.length; // The next page continues after this page's last id. A last row with no // id, or one that did not move past the cursor (an engine that ignored @@ -350,7 +406,43 @@ export class KnowledgeService implements IKnowledgeService { } cursor = lastId; } - return { ok: true, object, discovered, indexed }; + + // The purge runs only after a COMPLETE walk: a `limit` walk saw part of + // the source, so "not seen" there means nothing (a failed page returned + // above; `dryRun` returned before the walk). + const done: KnowledgeReindexResult = { ok: true, object, discovered, indexed, skipped, purged: null }; + if (listingNote) return { ...done, message: listingNote }; + if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) return done; + + const candidates = [...listed.keys()].filter((id) => !seen.has(id)); + const purge = await purgeDocuments({ + source, + objSource, + adapter, + engine, + candidates, + serialize: (documentId, task) => chainAfter(this.recordSyncTails, documentId, task), + }); + if (purge.failure !== undefined) { + return { + ...done, + ok: false, + purged: purge.purged, + message: + `reindex of source '${source.id}' walked every page, but its purge stopped after ${purge.purged} ` + + `deletion(s): ${purge.failure}`, + }; + } + if (purge.foreign > 0) { + return { + ...done, + purged: purge.purged, + message: + `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + + `('${source.id}:' and the record id); they were kept, because no row can confirm them.`, + }; + } + return { ...done, purged: purge.purged }; } // ── The `search_knowledge` AI tool (ADR-0149 D2) ────────────────── @@ -459,8 +551,7 @@ export class KnowledgeService implements IKnowledgeService { * the committed row — which may still match — is missing from the index. * The row's next event or a `reindexSource` repairs a row that still exists; * a document built from an INSERT that rolled back has no row left to - * repair it from, and a reindex removes no documents — it stays until the - * index purge (#37096). + * repair it from — it stays until a complete `reindexSource` purges it. * `data.record.restored` is published after the restore's own unit has * committed. Bulk events (`data.records.*`) carry a count, not records, and * are not synced here — see the plugin's event bridge. @@ -512,13 +603,7 @@ export class KnowledgeService implements IKnowledgeService { ); return; } - const byId = { id: recordId }; - const rows = await engine.find( - object, - { where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, limit: 1 }, - { context: systemContext() }, - ); - const row = Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; + const row = await rereadRow(engine, objSource, recordId); if (row) { const doc = recordToDocument(source, objSource, row, this.schemaFor(object)); await adapter.upsert([doc], { source, reason: 'event-sync' }); @@ -844,13 +929,187 @@ export function objectSourcesFor(sources: KnowledgeSource[], object: string): Kn /** * The RLS-bypassing system context of the service's own reads: the reindex - * walk, and the event sync's re-read, which decide index MEMBERSHIP (`where`), - * never what a caller may read — search re-checks every hit as the caller. + * walk, the event sync's re-read and the purge's, which decide index + * MEMBERSHIP (`where`), never what a caller may read — search re-checks every + * hit as the caller. */ function systemContext(): ExecutionContext { return { positions: [], permissions: [], systemPermissions: [], isSystem: true }; } +/** + * THE membership re-read: the row `recordId` names, read under the system + * context and the source's `where` — `find(object, { where: where AND id, + * limit: 1 })` — so the database answers whether the row belongs in the + * index, never an event payload or an earlier read. `undefined` when no row + * matches (none exists, or it does not match `where`). Throws what `find` + * throws. + * + * One definition for both of its readers, the event sync + * ({@link KnowledgeService.handleRecordUpsert}) and the purge + * ({@link purgeDocuments}): they decide the same question, and a second copy + * is how they would drift into answering it differently. + */ +async function rereadRow( + engine: IDataEngine, + objSource: ObjectKnowledgeSource, + recordId: string | number, +): Promise | undefined> { + const byId = { id: recordId }; + const rows = await engine.find( + objSource.object, + { where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, limit: 1 }, + { context: systemContext() }, + ); + return Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; +} + +/** + * Entries one `listDocuments` call asks for. A memory bound per call, not a + * contract limit: the adapter may answer fewer. + */ +export const LIST_DOCUMENTS_PAGE_SIZE = 500; + +/** What {@link listAdapterDocuments} learned: every listed id → its stored hash, or why there is no listing. */ +type AdapterListing = + | { ok: true; documents: Map } + /** `reason` is absent when the adapter has no `listDocuments`; present when the listing failed. */ + | { ok: false; reason?: string }; + +/** + * Read every page of the adapter's `listDocuments` for `source`. Never throws: + * an adapter without the method answers `{ ok: false }` with no reason, and a + * listing that throws or answers a malformed page or a cursor it already gave + * (a listing that would never end) answers `{ ok: false, reason }`. + */ +async function listAdapterDocuments(source: KnowledgeSource, adapter: IKnowledgeAdapter): Promise { + if (typeof adapter.listDocuments !== 'function') return { ok: false }; + const documents = new Map(); + const cursors = new Set(); + let cursor: string | undefined; + try { + for (;;) { + const page = await adapter.listDocuments( + { source, reason: 'reindex' }, + cursor === undefined ? { limit: LIST_DOCUMENTS_PAGE_SIZE } : { cursor, limit: LIST_DOCUMENTS_PAGE_SIZE }, + ); + if (!page || !Array.isArray(page.documents)) return { ok: false, reason: 'a page carried no documents list' }; + for (const entry of page.documents) { + if (typeof entry?.documentId !== 'string') return { ok: false, reason: 'an entry carried no documentId' }; + documents.set(entry.documentId, typeof entry.docHash === 'string' ? entry.docHash : undefined); + } + if (page.nextCursor === undefined) return { ok: true, documents }; + if (cursors.has(page.nextCursor)) { + return { ok: false, reason: `the cursor '${page.nextCursor}' came back twice, so the listing would never end` }; + } + cursors.add(page.nextCursor); + cursor = page.nextCursor; + } + } catch (err) { + return { ok: false, reason: errorText(err) }; + } +} + +/** Input of {@link purgeDocuments}. */ +export interface PurgeDocumentsInput { + source: KnowledgeSource; + objSource: ObjectKnowledgeSource; + adapter: IKnowledgeAdapter; + engine: IDataEngine; + /** Document ids believed stale: listed by the adapter, not produced from a current row. */ + candidates: Iterable; + /** + * Runs one candidate's confirm-and-delete after every earlier sync of that + * document has finished, answering the task's own outcome — the service + * passes its per-document record-sync chain, so an event sync of the same + * row can never land between the purge's re-read and its delete. + */ + serialize: (documentId: string, task: () => Promise) => Promise; + /** Diagnostics tag on the adapter's `delete`. @default 'reindex' */ + reason?: string; +} + +/** Outcome of {@link purgeDocuments}. */ +export interface PurgeDocumentsOutcome { + /** Candidates deleted. */ + purged: number; + /** Candidates whose row the re-read found: kept. */ + kept: number; + /** Candidates whose id this source does not derive from a record id: kept, nothing can confirm them. */ + foreign: number; + /** Why the purge stopped early (a re-read or a delete that threw); absent when it went through every candidate. */ + failure?: string; +} + +/** + * The index purge (ADR-0161 K8, item 1): delete the candidates whose row is + * gone. Each candidate is confirmed by {@link rereadRow} — the event sync's + * own re-read, `where` AND id under the system context — and deleted only + * when that finds no row, so a document whose row was created, restored or + * came back into `where` since the candidates were computed is kept. Stops at + * the first re-read or delete that throws, counting what it did before. + * + * The caller decides when a purge may run at all (a complete reindex walk; + * the scheduled reconcile reuses this function) and computes the candidates. + */ +export async function purgeDocuments(input: PurgeDocumentsInput): Promise { + const { source, objSource, adapter, engine } = input; + const prefix = `${source.id}:`; + const outcome: PurgeDocumentsOutcome = { purged: 0, kept: 0, foreign: 0 }; + for (const documentId of input.candidates) { + const recordId = documentId.startsWith(prefix) ? documentId.slice(prefix.length) : ''; + if (recordId === '') { + outcome.foreign++; + continue; + } + try { + const deleted = await input.serialize(documentId, async () => { + if (await rereadRow(engine, objSource, recordId)) return false; + await adapter.delete([documentId], { source, reason: input.reason ?? 'reindex' }); + return true; + }); + if (deleted) outcome.purged++; + else outcome.kept++; + } catch (err) { + outcome.failure = `document '${documentId}': ${errorText(err)}`; + return outcome; + } + } + return outcome; +} + +/** + * The version of the {@link computeDocHash} recipe, the hash's prefix. Bump it + * when what the hash covers or how it serializes changes: every stored hash + * then reads as changed, and the next complete reindex writes every document + * once. + */ +export const DOC_HASH_VERSION = 'v1'; + +/** + * A document's `docHash` (ADR-0161 K8, item 2): SHA-256 over its content, + * title and metadata, serialized with object keys in a stable order, behind + * the {@link DOC_HASH_VERSION} prefix. The same assembled document gives the + * same hash on every machine, whatever order its metadata keys were built in. + */ +export function computeDocHash(doc: Pick): string { + const body = stableJson({ content: doc.content, title: doc.title ?? null, metadata: doc.metadata ?? {} }); + return `${DOC_HASH_VERSION}:${createHash('sha256').update(body).digest('hex')}`; +} + +/** `JSON.stringify` with every plain object's keys sorted, and a bigint as its decimal text. */ +function stableJson(value: unknown): string { + return JSON.stringify(value, (_key, v: unknown) => { + if (typeof v === 'bigint') return v.toString(); + if (v !== null && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype) { + const sorted: Record = {}; + for (const k of Object.keys(v as Record).sort()) sorted[k] = (v as Record)[k]; + return sorted; + } + return v; + }); +} + /** A thrown value's text: an `Error`'s message, anything else as a string. */ function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); @@ -909,7 +1168,7 @@ export function recordToDocument( if (withheld.has(field)) continue; if (record[field] !== undefined) metadata[field] = record[field]; } - return { + const doc: KnowledgeDocument = { id: documentIdFor(source.id, recordId || `unknown-${Date.now()}`), sourceId: source.id, sourceRecordId: recordId || undefined, @@ -917,4 +1176,6 @@ export function recordToDocument( title: typeof record.title === 'string' && !withheld.has('title') ? record.title : undefined, metadata, }; + doc.docHash = computeDocHash(doc); + return doc; } diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts new file mode 100644 index 00000000000..14c34286815 --- /dev/null +++ b/packages/services/service-knowledge/src/testing.ts @@ -0,0 +1,323 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `IKnowledgeAdapter` contract test suite (ADR-0161 K8, rule 1) — written + * once, run by every adapter package against its own factory: + * + * ```ts + * import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; + * + * runKnowledgeAdapterContract({ + * name: 'knowledge-memory', + * makeAdapter: () => new KnowledgeMemoryAdapter(), + * implements: { listDocuments: true }, + * }); + * ``` + * + * TEST-ONLY. This module imports `vitest`, and the package publishes it as its + * own `./testing` subpath, ESM only, never through the runtime entry (`.`). + * + * What it covers: `upsert` / `search` / `delete` on the adapter alone; the + * optional `listDocuments` (page boundaries at 0, one page and one page + 1; + * `docHash` returned as stored); and, through a real `KnowledgeService` over a + * small data-engine double, the skip of unchanged documents and the purge of + * documents the source no longer has. + * + * Every optional member is DECLARED by the caller in `implements`, and the + * suite asserts the declaration against the adapter: a member an adapter lacks + * runs the case that pins the service's behaviour without it, never nothing. + */ + +import { describe, expect, it } from 'vitest'; +import type { IDataEngine, IKnowledgeAdapter, AdapterContext } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from './knowledge-service.js'; + +/** Input of {@link runKnowledgeAdapterContract}. */ +export interface KnowledgeAdapterContractOptions { + /** Names the suite in the test report. */ + name: string; + /** + * A FRESH, empty adapter per call: every case makes its own, so no case + * reads what another wrote. A store-backed adapter gives each call its own + * store (or its own namespace in one). + */ + makeAdapter: () => IKnowledgeAdapter | Promise; + /** The optional members this adapter implements; checked against the adapter. */ + implements: { + listDocuments: boolean; + }; +} + +/** Every case's source id starts with this, so a shared store can be told apart. */ +const SOURCE_PREFIX = 'contract_'; + +function objectSource(id: string, extra: Partial = {}): KnowledgeSource { + return { + id: `${SOURCE_PREFIX}${id}`, + label: id, + adapter: 'under_test', + source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'], ...extra }, + } as KnowledgeSource; +} + +function ctxOf(source: KnowledgeSource): AdapterContext { + return { source, reason: 'manual' }; +} + +function doc(source: KnowledgeSource, n: string, content: string, docHash?: string): KnowledgeDocument { + return { + id: `${source.id}:${n}`, + sourceId: source.id, + sourceRecordId: n, + content, + title: `Title ${n}`, + metadata: { status: 'published' }, + ...(docHash === undefined ? {} : { docHash }), + }; +} + +/** Every page of `listDocuments`, asserting each page's bound; refuses a listing that does not end. */ +async function listAll( + adapter: IKnowledgeAdapter, + source: KnowledgeSource, + limit: number, +): Promise<{ pages: number; entries: Array<{ documentId: string; docHash?: string }> }> { + const entries: Array<{ documentId: string; docHash?: string }> = []; + let cursor: string | undefined; + for (let pages = 1; pages <= 1000; pages++) { + const page = await adapter.listDocuments!(ctxOf(source), cursor === undefined ? { limit } : { cursor, limit }); + expect(Array.isArray(page.documents)).toBe(true); + expect(page.documents.length).toBeLessThanOrEqual(limit); + entries.push(...page.documents); + if (page.nextCursor === undefined) return { pages, entries }; + expect(page.nextCursor).not.toBe(cursor); + cursor = page.nextCursor; + } + throw new Error('listDocuments never answered a page without nextCursor (1000 pages)'); +} + +type Row = Record; + +/** + * A data-engine double serving `find` / `count` the way the knowledge service + * calls them (the paged walk and the membership re-read), over rows the case + * mutates directly. It refuses — by a throw — any `where` shape it does not + * implement, so a service change it cannot answer turns the suite red rather + * than being answered wrongly. + */ +function rowsEngine(rows: Row[]): IDataEngine { + const matches = (row: Row, where: Record | undefined): boolean => { + if (!where) return true; + for (const [key, value] of Object.entries(where)) { + if (key === '$and') { + if (!Array.isArray(value)) throw new Error('engine double: $and takes an array'); + if (!value.every((c) => matches(row, c as Record))) return false; + continue; + } + if (key.startsWith('$')) throw new Error(`engine double: operator ${key} is not implemented`); + if (value !== null && typeof value === 'object') { + const ops = Object.keys(value); + if (key !== 'id' || ops.length !== 1 || ops[0] !== '$gt') { + throw new Error(`engine double: condition ${JSON.stringify(value)} on '${key}' is not implemented`); + } + if (!(String(row.id) > String((value as { $gt: unknown }).$gt))) return false; + continue; + } + if (row[key] !== value) return false; + } + return true; + }; + return { + find: async (_object: string, query: { where?: Record; limit?: number }) => { + if (typeof query?.limit !== 'number' || !(query.limit > 0)) throw new Error('engine double: an unbounded find'); + return rows + .filter((r) => matches(r, query.where)) + .sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)) + .slice(0, query.limit) + .map((r) => ({ ...r })); + }, + count: async (_object: string, query: { where?: Record }) => + rows.filter((r) => matches(r, query?.where)).length, + } as unknown as IDataEngine; +} + +/** A `KnowledgeService` over `adapter` and `rows`, with the adapter's `upsert` counted. */ +async function serviceOver(make: () => IKnowledgeAdapter | Promise, rows: Row[], source: KnowledgeSource) { + const adapter = await make(); + const upserted: string[][] = []; + // Delegation, not a prototype proxy: an adapter with `#private` fields only + // answers when its methods are called on the adapter itself. + const counting: IKnowledgeAdapter = { + id: adapter.id, + upsert: async (docs, ctx) => { + upserted.push(docs.map((d) => d.id)); + return adapter.upsert(docs, ctx); + }, + search: (query, searchOpts) => adapter.search(query, searchOpts), + delete: (ids, ctx) => adapter.delete(ids, ctx), + ...(typeof adapter.listDocuments === 'function' + ? { listDocuments: (ctx: AdapterContext, listOpts: { cursor?: string; limit: number }) => adapter.listDocuments!(ctx, listOpts) } + : {}), + }; + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + svc.registerAdapter('under_test', counting); + svc.registerSource(source); + return { adapter, svc, upserted }; +} + +const rowsOf = (n: number): Row[] => + Array.from({ length: n }, (_, i) => ({ id: `r${i}`, body: `body number ${i} zebra${i}`, status: 'published' })); + +/** + * Register the contract suite for one adapter. Call it at the top level of a + * test file. + */ +export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOptions): void { + const make = opts.makeAdapter; + + describe(`IKnowledgeAdapter contract — ${opts.name}`, () => { + it('declares exactly the optional members it implements', async () => { + const adapter = await make(); + expect(typeof adapter.id).toBe('string'); + expect(typeof adapter.listDocuments === 'function').toBe(opts.implements.listDocuments); + }); + + describe('upsert / search / delete', () => { + it('a search finds an upserted document, scoped to the searched source, best first', async () => { + const adapter = await make(); + const a = objectSource('a'); + const b = objectSource('b'); + await adapter.upsert([doc(a, '1', 'alpine meadow flowers'), doc(a, '2', 'harbour cranes at night')], ctxOf(a)); + await adapter.upsert([doc(b, '1', 'alpine meadow flowers')], ctxOf(b)); + const hits = await adapter.search('alpine meadow', { source: a, topK: 5 }); + expect(hits.length).toBeGreaterThan(0); + expect(hits[0].documentId).toBe(`${a.id}:1`); + for (const hit of hits) expect(hit.sourceId).toBe(a.id); + for (let i = 1; i < hits.length; i++) expect(hits[i - 1].score).toBeGreaterThanOrEqual(hits[i].score); + expect((await adapter.search('alpine meadow', { source: a, topK: 1 })).length).toBeLessThanOrEqual(1); + }); + + it('an upsert of an existing id replaces the document', async () => { + const adapter = await make(); + const a = objectSource('a'); + await adapter.upsert([doc(a, '1', 'volcanic basalt columns')], ctxOf(a)); + await adapter.upsert([doc(a, '1', 'glacier ice caves')], ctxOf(a)); + const stale = await adapter.search('volcanic basalt', { source: a, topK: 5 }); + expect(stale.filter((h) => h.documentId === `${a.id}:1`)).toEqual([]); + const fresh = await adapter.search('glacier ice', { source: a, topK: 5 }); + expect(fresh.map((h) => h.documentId)).toContain(`${a.id}:1`); + }); + + it('a deleted document is not found; deleting an absent id is a no-op', async () => { + const adapter = await make(); + const a = objectSource('a'); + await adapter.upsert([doc(a, '1', 'copper kettle'), doc(a, '2', 'copper wire')], ctxOf(a)); + await adapter.delete([`${a.id}:1`, `${a.id}:absent`], ctxOf(a)); + const hits = await adapter.search('copper', { source: a, topK: 5 }); + expect(hits.map((h) => h.documentId)).toEqual([`${a.id}:2`]); + }); + }); + + if (opts.implements.listDocuments) { + describe('listDocuments', () => { + it.each([ + ['0 documents', 0], + ['exactly one page', 3], + ['one page + 1', 4], + ])('%s: every document once, no page over its limit', async (_label, n) => { + const adapter = await make(); + const a = objectSource('a'); + if (n > 0) { + await adapter.upsert( + Array.from({ length: n }, (_, i) => doc(a, `d${i}`, `listed document ${i}`, `hash-${i}`)), + ctxOf(a), + ); + } + const { pages, entries } = await listAll(adapter, a, 3); + const ids = entries.map((e) => e.documentId); + expect(new Set(ids).size).toBe(ids.length); + expect([...ids].sort()).toEqual(Array.from({ length: n }, (_, i) => `${a.id}:d${i}`).sort()); + // 0 and 3 documents fit one page (plus, at most, an empty one after it); 4 need two. + expect(pages).toBeLessThanOrEqual(n === 4 ? 3 : 2); + if (n === 4) expect(pages).toBeGreaterThanOrEqual(2); + }); + + it('returns each docHash as stored, and none for a document stored without one', async () => { + const adapter = await make(); + const a = objectSource('a'); + await adapter.upsert([doc(a, '1', 'granite quarry', 'v1:opaque-as-given'), doc(a, '2', 'marble quarry')], ctxOf(a)); + await adapter.upsert([doc(a, '1', 'granite quarry, revised', 'v1:replaced')], ctxOf(a)); + const { entries } = await listAll(adapter, a, 10); + const byId = new Map(entries.map((e) => [e.documentId, e.docHash])); + expect(byId.get(`${a.id}:1`)).toBe('v1:replaced'); + expect(byId.has(`${a.id}:2`)).toBe(true); + expect(byId.get(`${a.id}:2`)).toBeUndefined(); + }); + + it("lists only the source's own documents, and none that were deleted", async () => { + const adapter = await make(); + const a = objectSource('a'); + const b = objectSource('b'); + await adapter.upsert([doc(a, '1', 'tidal pool'), doc(a, '2', 'tidal flat')], ctxOf(a)); + await adapter.upsert([doc(b, '1', 'tidal pool')], ctxOf(b)); + await adapter.delete([`${a.id}:2`], ctxOf(a)); + const { entries } = await listAll(adapter, a, 10); + expect(entries.map((e) => e.documentId)).toEqual([`${a.id}:1`]); + }); + }); + + describe('through KnowledgeService.reindexSource', () => { + it('a second complete reindex skips every unchanged document and rewrites a changed one', async () => { + const rows = rowsOf(3); + const source = objectSource('skip'); + const h = await serviceOver(make, rows, source); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 3, skipped: 0, purged: 0 }); + h.upserted.length = 0; + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, discovered: 3, indexed: 0, skipped: 3, purged: 0 }); + expect(h.upserted).toEqual([]); + rows[1].body = 'body number 1 rewritten'; + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 1, skipped: 2, purged: 0 }); + expect(h.upserted).toEqual([[`${source.id}:r1`]]); + }); + + it('a complete reindex purges the documents of a deleted row and of a row that left where', async () => { + const rows = rowsOf(3); + const source = objectSource('purge', { where: { status: 'published' } }); + const h = await serviceOver(make, rows, source); + await h.svc.reindexSource(source.id); + rows.splice(0, 1); // r0 deleted + rows[1].status = 'draft'; // r2 stopped matching + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, discovered: 1, purged: 2 }); + const { entries } = await listAll(h.adapter, source, 10); + expect(entries.map((e) => e.documentId)).toEqual([`${source.id}:r1`]); + expect((await h.adapter.search('zebra0 zebra2', { source, topK: 5 })).map((x) => x.documentId)).toEqual([]); + }); + + it('a reindex with a limit or a dryRun purges nothing', async () => { + const rows = rowsOf(3); + const source = objectSource('partial'); + const h = await serviceOver(make, rows, source); + await h.svc.reindexSource(source.id); + rows.splice(0, 1); + expect(await h.svc.reindexSource(source.id, { limit: 10 })).toMatchObject({ ok: true, purged: null }); + expect(await h.svc.reindexSource(source.id, { dryRun: true })).toMatchObject({ ok: true, purged: null }); + expect((await listAll(h.adapter, source, 10)).entries).toHaveLength(3); + }); + }); + } else { + describe('without listDocuments', () => { + it('a complete reindex rewrites every document and reports purged: null', async () => { + const rows = rowsOf(3); + const source = objectSource('nolist'); + const h = await serviceOver(make, rows, source); + await h.svc.reindexSource(source.id); + rows.splice(0, 1); + h.upserted.length = 0; + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0, purged: null }); + expect(h.upserted.flat()).toEqual([`${source.id}:r1`, `${source.id}:r2`]); + }); + }); + } + }); +} diff --git a/packages/services/service-knowledge/tsup.config.ts b/packages/services/service-knowledge/tsup.config.ts new file mode 100644 index 00000000000..5120f2ea79e --- /dev/null +++ b/packages/services/service-knowledge/tsup.config.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineConfig, type Options } from 'tsup'; + +import { dropSourcesContent } from '../../../scripts/tsup-drop-sources-content.mjs'; + +// The root config builds `src/index.ts` alone; this package also publishes the +// adapter contract test suite as `./testing` (ADR-0161 K8, rule 1). Same shape, +// and the same reasons, as `packages/services/service-cluster/tsup.config.ts`, +// whose comments carry the measured history: +// +// - `clean` is `false` in both halves: tsup builds an array config +// concurrently, so a `clean` in one half races the other's writes. The +// `build` script empties `dist/` once, before tsup starts. +// - The split is by FORMAT, never by ENTRY. `./testing` is ESM only (it imports +// `vitest`, which is ESM only, and its export map has no `require` +// condition), so only the CJS half drops it. Both entries stay together in +// the ESM half because `src/testing.ts` imports `KnowledgeService` from the +// runtime modules: one config, one shared chunk, one class identity for a +// service reached through either entry. +// - `vitest` is external: the suite runs inside the consumer's own vitest. +const shared: Options = { + splitting: true, + sourcemap: true, + clean: false, + dts: !process.env.OS_SKIP_DTS, + target: 'es2020', + external: ['vitest'], + esbuildOptions: dropSourcesContent, +}; + +export default defineConfig([ + { ...shared, entry: ['src/index.ts', 'src/testing.ts'], format: ['esm'] }, + { ...shared, entry: ['src/index.ts'], format: ['cjs'] }, +]); diff --git a/packages/spec/src/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index 26d6818a267..93647fd7cf2 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -48,6 +48,16 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ * `object` sources is handled by re-querying via the data engine. */ permissions: z.array(z.string()).optional(), + /** + * A hash of the assembled document — its content, title and metadata, in a + * stable key order, behind a version prefix (ADR-0161 K8, item 2). Computed + * by the knowledge service on every document it hands an adapter, stored by + * the adapter, and returned as stored by `listDocuments`; an unchanged hash + * lets a complete reindex skip writing the document again. Adapters never + * compute or alter it. + */ + docHash: z.string().optional() + .describe('Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter'), })); /** diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 46ce1fcb6b1..6c415fc0093 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -49,9 +49,48 @@ export interface AdapterSearchOptions { traceId?: string; } +/** Options accepted by `IKnowledgeAdapter.listDocuments`. */ +export interface AdapterListDocumentsOptions { + /** + * Where to continue: the `nextCursor` of the page before. Omitted for the + * first page. Opaque to the service — the adapter alone gives it meaning. + */ + cursor?: string; + /** Most entries this page may hold. A positive integer. */ + limit: number; +} + +/** One entry of a `listDocuments` page. */ +export interface AdapterListedDocument { + /** The stored document's id (`KnowledgeDocument.id`). */ + documentId: string; + /** + * The `docHash` the document was stored with, returned as stored. An entry + * without one reads as changed: the next complete reindex writes it again. + */ + docHash?: string; +} + +/** One page of `IKnowledgeAdapter.listDocuments`. */ +export interface AdapterListDocumentsPage { + /** This page's entries; empty when the source holds nothing past `cursor`. */ + documents: AdapterListedDocument[]; + /** + * Pass back as `cursor` for the next page. Absent when the listing is + * complete. A page may be followed by an empty one. + */ + nextCursor?: string; +} + /** * Plugin-implemented adapter. **One per backend**. Stateless across * source ids — the source is supplied per-call. + * + * Every member past `upsert` / `search` / `delete` is optional (ADR-0161 K8, + * rule 2): an adapter that lacks one keeps working, and the service does what + * it did before that member existed and says so where its result can carry it. + * The contract test suite every adapter can run is exported by + * `@objectstack/service-knowledge/testing`. */ export interface IKnowledgeAdapter { /** Stable adapter id used in `KnowledgeSource.adapter`. */ @@ -66,6 +105,20 @@ export interface IKnowledgeAdapter { /** Remove documents by id. */ delete(documentIds: string[], ctx: AdapterContext): Promise; + /** + * List the documents the adapter holds for `ctx.source`, one page at a + * time (ADR-0161 K8, item 1): each entry is a document id and the + * `docHash` it was stored with. It lists the generation that writes go to. + * A document written while a listing runs may be missing from it — the + * safe direction, because a missing entry is never a purge candidate. + * + * The service reads it before a complete reindex: an unchanged document + * (same `docHash`) is not written again, and a listed document the walk did + * not see is a purge candidate. An adapter without it gets no skip and no + * purge, and the reindex result says `purged: null`. + */ + listDocuments?(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise; + /** * Optional liveness probe. When implemented, used by the service's * health endpoint and Studio "test connection" actions. From b93cf08dd36ab89cf60dbb1515235febaff572ad Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:41:38 +0000 Subject: [PATCH 02/13] wip(service-knowledge): skip/purge tests; protocol doc Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 91 ++++- .../src/__tests__/knowledge-service.test.ts | 310 ++++++++++++++++-- 2 files changed, 370 insertions(+), 31 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 273ed653100..edd453588db 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -158,7 +158,11 @@ registers itself with that name. Adapter config (endpoint, dataset id, Canonical shapes shared by every adapter: - `KnowledgeDocument` — one logical document (`id`, `sourceId`, - `sourceRecordId?`, `content`, `metadata`, `permissions?`). + `sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`). + `docHash` is a hash of the assembled document — content, title and + metadata, in a stable key order, behind a version prefix (`v1:`). The + service computes it on every document it hands an adapter; the adapter + stores it and returns it as stored, and never computes or alters it. - `KnowledgeChunk` — adapter-produced chunk of a document. The framework does **not** chunk; adapters do. - `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`, @@ -200,7 +204,8 @@ interface IKnowledgeService { the all-important `executionContext` (from the permission-aware tool execution work — see `actions-as-tools.mdx`). `KnowledgeReindexOptions` accepts `dryRun` and `limit`; `reindexSource` returns a -`KnowledgeReindexResult` (`indexed`, `discovered`, `ok`, …). +`KnowledgeReindexResult` (`indexed`, `discovered`, `skipped`, `purged`, +`ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge). ### 3.4 `IKnowledgeAdapter` (implemented by plugins) @@ -210,6 +215,10 @@ interface IKnowledgeAdapter { upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; search(query: string, opts: AdapterSearchOptions): Promise; delete(documentIds: string[], ctx: AdapterContext): Promise; + listDocuments?( + ctx: AdapterContext, + opts: { cursor?: string; limit: number }, + ): Promise<{ documents: { documentId: string; docHash?: string }[]; nextCursor?: string }>; healthCheck?(): Promise<{ ok: boolean; message?: string }>; } ``` @@ -219,6 +228,34 @@ management, no chunk strategy, no rerank toggles. Those are the adapter's private concerns. Adapters that need extra knobs expose them in their plugin options. +Every member past `upsert` / `search` / `delete` is optional (ADR-0161 +K8): an adapter that lacks one keeps working, and the service does what it +did before that member existed. `listDocuments` lists the documents the +adapter holds for a source, a page of at most `limit` entries at a time, each +with the `docHash` it was stored with; `nextCursor` is absent once the +listing is complete. A document written while a listing runs may be missing +from it — the safe direction, since a missing entry is never purged. + +**The contract test suite.** Every adapter package runs the same suite +against its own factory: + +```ts +import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; + +runKnowledgeAdapterContract({ + name: 'my-adapter', + makeAdapter: () => new MyAdapter(/* a fresh, empty store */), + implements: { listDocuments: true }, +}); +``` + +It covers upsert / search / delete, `listDocuments` page boundaries and +`docHash` round-trips, and — through a real `KnowledgeService` — the skip and +the purge below. `implements` declares the optional members, and the suite +checks the declaration against the adapter. `./testing` is a test-only, +ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. +`knowledge-memory` runs it as the reference implementation. + --- ## 4. Plugin model @@ -392,8 +429,7 @@ then rolls back, the index is wrong in one of two ways: The row's next event or a `reindexSource` repairs a row that still exists. A document built from an **insert** that rolled back has no row left to repair it -from, and a reindex removes no documents, so it stays until the index purge -([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands. +from; it stays until a complete reindex purges it (below). `data.record.restored` is published after the restore's own unit has committed. @@ -412,12 +448,42 @@ published after the restore's own unit has committed. than per-record events. A knowledge index is a per-record projection and `matched: 40` names no record, so there is no upsert or delete to derive — the service logs a warning naming the object and count instead of failing - silently. An explicit `reindexSource` refreshes the documents of rows that - still exist and match; it removes no documents, so those of deleted rows (or - of rows that stopped matching) stay until the index purge - ([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands. + silently. A complete `reindexSource` refreshes the documents of rows that + still exist and match, and — over an adapter that implements + `listDocuments` — purges those of deleted rows and of rows that stopped + matching. Over an adapter that does not, they stay in the index. +### Reindex: skip and purge + +A `reindexSource` of an `object` source over an adapter that implements +`listDocuments` first lists what the adapter holds for the source (document +id → stored `docHash`), then walks the object's rows page by page: + +- **Skip.** A row whose document's computed `docHash` equals the listed one is + not written again; the result counts it in `skipped`. Every other document + is written (`indexed`). A listed entry without a `docHash` reads as changed. +- **Purge.** After a **complete** walk — no `limit`, no `dryRun`, no failed + page — every document listed before the walk that the walk did not see is a + candidate. Each candidate is confirmed by the same re-read the event sync + makes (the source's `where` AND the record id, under the system context) and + deleted only when that finds no row. A row created or restored during the + walk keeps its document: if it was listed, the re-read finds it; if it was + not, it was never a candidate. The purge of a document waits for any + in-flight event sync of the same document. `purged` counts the deletions. +- **`purged: null`** means no purge ran: a walk with a `limit` or a `dryRun`, + a failed walk, a source with `refresh.onRecordChange: false` (an external + indexer owns its index), or an adapter without `listDocuments` — which also + skips nothing, the walk otherwise unchanged. A listing that fails skips and + purges nothing either, and the result's `message` says why. +- A listed document whose id is not one the source derives from a record + (`:`) is never purged, since no row can confirm it; the + result's `message` counts such documents. + +A re-read or delete that fails stops the purge: the result is `ok: false`, +`purged` counts the deletions made before it, and the `message` names the +document. + ### Retention deletes are covered by a reap guard The platform's own predicate delete — `LifecycleService` reaping rows past @@ -445,9 +511,10 @@ returns the ids it confirms. Rows it does not confirm stay put. external indexer owns is never a reason to hold up another package's retention. -Application-level predicate writes remain uncovered: de-indexing them needs an -adapter-side enumeration capability that no adapter declares today, and that -surface stays unbuilt until a real `object` source calls for it. +Application-level predicate writes are not de-indexed as they happen. Their +stale documents are removed by the next complete `reindexSource`, over an +adapter that implements `listDocuments` ([Reindex: skip and +purge](#reindex-skip-and-purge)); nothing runs that reindex on a schedule yet. `file` / `http` sources rely on explicit `reindexSource` calls (typically triggered by a cron job, a Console button, or a webhook). @@ -467,7 +534,7 @@ up. | `KnowledgeSourceSchema` | ✅ | object / file / http kinds | | `KnowledgeDocument` / `Chunk` / `Hit` | ✅ | Canonical shapes | | `IKnowledgeService` contract | ✅ | search / index / delete / reindex | -| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck | +| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments` with a contract test suite (`@objectstack/service-knowledge/testing`) | | `service-knowledge` orchestrator | ✅ | Adapter routing, RLS wrapper, sync | | `knowledge-memory` | ✅ | In-process; deterministic fake embedder | | `knowledge-ragflow` | ✅ | Minimal REST adapter (datasets + chunks + retrieval) | diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 565ac386fa4..60f261c53d4 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1,9 +1,18 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi } from 'vitest'; -import { KnowledgeService, REINDEX_PAGE_SIZE, documentIdFor, recordToDocument } from '../knowledge-service.js'; +import { + DOC_HASH_VERSION, + KnowledgeService, + LIST_DOCUMENTS_PAGE_SIZE, + REINDEX_PAGE_SIZE, + computeDocHash, + documentIdFor, + recordToDocument, +} from '../knowledge-service.js'; import type { IDataEngine, + AdapterContext, IKnowledgeAdapter, } from '@objectstack/spec/contracts'; import type { @@ -71,9 +80,13 @@ describe('KnowledgeService — adapter & source registry', () => { const a = makeAdapter('memory'); svc.registerAdapter('memory', a); svc.registerSource(objectSource('s1', 'task')); - const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello' }; + const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello', docHash: 'caller-supplied' }; await svc.indexDocument('s1', doc); - expect(a.upsertSpy).toHaveBeenCalledWith([doc], expect.objectContaining({ reason: 'manual' })); + // The service computes `docHash`; a caller's own value never reaches the adapter. + expect(a.upsertSpy).toHaveBeenCalledWith( + [{ ...doc, docHash: computeDocHash(doc) }], + expect.objectContaining({ reason: 'manual' }), + ); await svc.deleteDocument('s1', 'd1'); expect(a.deleteSpy).toHaveBeenCalledWith(['d1'], expect.objectContaining({ reason: 'manual' })); }); @@ -485,6 +498,10 @@ function pagedEngine(rowsIn: PagedRow[]) { } return true; }; + const pinsId = (where: Record | undefined): boolean => + where !== undefined && + (typeof where.id === 'string' || typeof where.id === 'number' || + (Array.isArray(where.$and) && where.$and.some((c) => pinsId(c as Record)))); const find = vi.fn(async ( _object: string, query: { where?: Record; orderBy?: unknown; limit?: number }, @@ -493,7 +510,10 @@ function pagedEngine(rowsIn: PagedRow[]) { if (typeof query?.limit !== 'number' || !(query.limit > 0)) { throw new Error('engine double: an unbounded find (no positive limit)'); } - if (JSON.stringify(query.orderBy) !== JSON.stringify([{ field: 'id', order: 'asc' }])) { + // The membership re-read (event sync, purge) pins one id and needs no order; + // every other read is a walk page and must be ordered by id. + const pinsOneId = query.limit === 1 && pinsId(query.where); + if (!pinsOneId && JSON.stringify(query.orderBy) !== JSON.stringify([{ field: 'id', order: 'asc' }])) { throw new Error(`engine double: expected orderBy id asc, got ${JSON.stringify(query.orderBy)}`); } if (options?.context?.isSystem !== true) throw new Error('engine double: expected the system context'); @@ -513,6 +533,8 @@ function pagedEngine(rowsIn: PagedRow[]) { engine: { find, count } as unknown as IDataEngine, find, count, + /** The double's live rows: a case mutates them to change the database under the service. */ + rows, /** The next `find` reads at call time but resolves only once the returned function is called. */ holdNextFind(): () => void { let release!: () => void; @@ -535,9 +557,12 @@ function upsertedIds(adapter: ReturnType): string[][] { return (adapter.upsertSpy.mock.calls as unknown as Array<[KnowledgeDocument[]]>).map(([docs]) => docs.map((d) => d.id)); } -function reindexHarness(rows: PagedRow[], src: KnowledgeSource = objectSource('s1', 'task')) { +function reindexHarness>( + rows: PagedRow[], + src: KnowledgeSource = objectSource('s1', 'task'), + adapter: A = makeAdapter('memory') as unknown as A, +) { const db = pagedEngine(rows); - const adapter = makeAdapter('memory'); const svc = new KnowledgeService({ dataEngine: db.engine }); svc.registerAdapter('memory', adapter); svc.registerSource(src); @@ -555,7 +580,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('0 rows: one bounded read, no upsert', async () => { const h = reindexHarness([]); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 0, indexed: 0 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 0, indexed: 0, skipped: 0, purged: null }); expect(h.find).toHaveBeenCalledTimes(1); expect(h.adapter.upsertSpy).not.toHaveBeenCalled(); }); @@ -563,7 +588,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('exactly one page: one upsert of the page, then a read that comes back empty', async () => { const h = reindexHarness(taskRows(100)); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 100, indexed: 100 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 100, indexed: 100, skipped: 0, purged: null }); expect(upsertedIds(h.adapter)).toEqual([ids(0, 100)]); expect(h.find).toHaveBeenCalledTimes(2); expect(h.find.mock.calls[1][1].where).toEqual({ id: { $gt: 'r099' } }); @@ -572,7 +597,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('one page + 1: two upserts (100, then 1), each row once, in id order', async () => { const h = reindexHarness(taskRows(101)); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 101, indexed: 101 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 101, indexed: 101, skipped: 0, purged: null }); expect(upsertedIds(h.adapter)).toEqual([ids(0, 100), ids(100, 101)]); // A short page is not the end — only the empty third read is. expect(h.find).toHaveBeenCalledTimes(3); @@ -589,7 +614,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { (src.source as ObjectKnowledgeSource).where = { status: 'open' }; const h = reindexHarness(taskRows(250, (i) => ({ status: i % 5 === 0 ? 'done' : 'open' })), src); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 200, indexed: 200 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 200, indexed: 200, skipped: 0, purged: null }); const all = upsertedIds(h.adapter).flat(); expect(all).toHaveLength(200); expect(new Set(all).size).toBe(200); @@ -606,7 +631,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { ])('limit %i caps the total: reads %j', async (limit, reads, total) => { const h = reindexHarness(taskRows(250)); const res = await h.svc.reindexSource('s1', { limit }); - expect(res).toEqual({ ok: true, object: 'task', discovered: total, indexed: total }); + expect(res).toEqual({ ok: true, object: 'task', discovered: total, indexed: total, skipped: 0, purged: null }); expect(h.find.mock.calls.map((c) => c[1].limit)).toEqual(reads); expect(upsertedIds(h.adapter).flat()).toEqual(ids(0, total)); }); @@ -614,7 +639,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('a limit above the row count reads to the end', async () => { const h = reindexHarness(taskRows(120)); const res = await h.svc.reindexSource('s1', { limit: 500 }); - expect(res).toEqual({ ok: true, object: 'task', discovered: 120, indexed: 120 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 120, indexed: 120, skipped: 0, purged: null }); }); it('a short page is not the end: a page that lost a row to a hook does not stop the walk', async () => { @@ -626,7 +651,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { return h.find.mock.calls.length === 1 ? page.filter((r) => r.id !== 'r049') : page; }); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 249, indexed: 249 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 249, indexed: 249, skipped: 0, purged: null }); expect(upsertedIds(h.adapter).map((p) => p.length)).toEqual([99, 100, 50]); expect(upsertedIds(h.adapter).flat()).toEqual(ids(0, 250).filter((id) => id !== 's1:r049')); expect(h.find).toHaveBeenCalledTimes(4); @@ -636,7 +661,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { const rows = taskRows(150).map((r) => ({ ...r, id: Number(String(r.id).slice(1)) + 1 })); const h = reindexHarness(rows); const res = await h.svc.reindexSource('s1'); - expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); const want = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, k) => `s1:${from + k}`); expect(upsertedIds(h.adapter)).toEqual([want(1, 100), want(101, 150)]); expect(h.find.mock.calls.map((c) => c[1].where)).toEqual([undefined, { id: { $gt: 100 } }, { id: { $gt: 150 } }]); @@ -645,7 +670,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { it('a fractional limit is floored', async () => { const h = reindexHarness(taskRows(250)); const res = await h.svc.reindexSource('s1', { limit: 150.7 }); - expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150 }); + expect(res).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); expect(h.find.mock.calls.map((c) => c[1].limit)).toEqual([100, 50]); }); @@ -726,7 +751,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { expect(h.find).toHaveBeenCalledTimes(2); // The failed walk released the source's lock. const again = await h.svc.reindexSource('s1'); - expect(again).toEqual({ ok: true, object: 'task', discovered: 250, indexed: 250 }); + expect(again).toEqual({ ok: true, object: 'task', discovered: 250, indexed: 250, skipped: 0, purged: null }); }); it('an engine that ignores the cursor ends the walk instead of looping', async () => { @@ -771,7 +796,7 @@ describe('KnowledgeService — the reindex walk pages by id', () => { expect(h.find).toHaveBeenCalledTimes(1); release(); const [a, b] = await Promise.all([first, second]); - expect(a).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150 }); + expect(a).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: null }); expect(b).toEqual(a); expect(order).toEqual(['s1:r000+100', 's1:r100+50', 's1:r000+100', 's1:r100+50']); }); @@ -782,8 +807,255 @@ describe('KnowledgeService — the reindex walk pages by id', () => { const release = h.holdNextFind(); const first = h.svc.reindexSource('s1'); const other = await h.svc.reindexSource('s2'); - expect(other).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10 }); + expect(other).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null }); release(); - expect(await first).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10 }); + expect(await first).toEqual({ ok: true, object: 'task', discovered: 10, indexed: 10, skipped: 0, purged: null }); + }); +}); + +// ── docHash, skip and purge (ADR-0161 K8, items 1–2) ───────────────── +// +// The adapter below stores each document's `docHash` and lists it back, one +// page of `opts.limit` at a time, in id order: the smallest adapter that +// implements `listDocuments`. Its calls are counted, so "not upserted" is read +// from the adapter, never inferred from the result. + +function listingAdapter(id = 'memory') { + const stored = new Map(); + const upsertSpy = vi.fn(async (docs: KnowledgeDocument[], _ctx: AdapterContext) => { + for (const d of docs) stored.set(d.id, d.docHash); + }); + const deleteSpy = vi.fn(async (documentIds: string[], _ctx: AdapterContext) => { + for (const d of documentIds) stored.delete(d); + }); + const listSpy = vi.fn(async (_ctx: AdapterContext, opts: { cursor?: string; limit: number }) => { + const all = [...stored.keys()].sort().filter((d) => opts.cursor === undefined || d > opts.cursor); + const page = all.slice(0, opts.limit); + return { + documents: page.map((documentId) => ({ documentId, docHash: stored.get(documentId) })), + ...(all.length > page.length ? { nextCursor: page[page.length - 1] } : {}), + }; + }); + const adapter = { + id, + upsert: upsertSpy, + delete: deleteSpy, + search: vi.fn(async () => [] as KnowledgeHit[]), + listDocuments: listSpy, + }; + return { adapter, stored, upsertSpy, deleteSpy, listSpy }; +} + +const upsertedOf = (spy: { mock: { calls: unknown[][] } }): string[] => + (spy.mock.calls as Array<[KnowledgeDocument[]]>).flatMap(([docs]) => docs.map((d) => d.id)); +const deletedOf = (spy: { mock: { calls: unknown[][] } }): string[] => + (spy.mock.calls as Array<[string[]]>).flatMap(([docIds]) => docIds); + +describe('computeDocHash', () => { + const base = { content: 'Body', title: 'T', metadata: { status: 'open', tags: ['a', 'b'], nested: { y: 1, x: 2 } } }; + + it('carries the version prefix and is stable under metadata key order, at every depth', () => { + const h = computeDocHash(base); + expect(h).toMatch(new RegExp(`^${DOC_HASH_VERSION}:[0-9a-f]{64}$`)); + expect(computeDocHash({ ...base, metadata: { nested: { x: 2, y: 1 }, tags: ['a', 'b'], status: 'open' } })).toBe(h); + }); + + it.each([ + ['content', { ...base, content: 'Body!' }], + ['title', { ...base, title: 'T2' }], + ['an absent title', { ...base, title: undefined }], + ['a metadata value', { ...base, metadata: { ...base.metadata, status: 'done' } }], + ['array order', { ...base, metadata: { ...base.metadata, tags: ['b', 'a'] } }], + ])('changes with %s', (_what, changed) => { + expect(computeDocHash(changed)).not.toBe(computeDocHash(base)); + }); + + it('recordToDocument stamps it on every document it builds', () => { + const src = objectSource('s1', 'task'); + const doc = recordToDocument(src, src.source as ObjectKnowledgeSource, { id: 'r1', title: 'A', notes: 'B', status: 'open' }); + expect(doc.docHash).toBe(computeDocHash(doc)); + }); +}); + +describe('KnowledgeService — a complete reindex skips unchanged documents and purges stale ones', () => { + it('first reindex over an empty listing writes everything; the next writes nothing unchanged', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(150), objectSource('s1', 'task'), la.adapter); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 150, skipped: 0, purged: 0 }); + la.upsertSpy.mockClear(); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 150, indexed: 0, skipped: 150, purged: 0 }); + expect(la.upsertSpy).not.toHaveBeenCalled(); + expect(la.deleteSpy).not.toHaveBeenCalled(); + }); + + it('a changed row is written again; only it', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(10), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + la.upsertSpy.mockClear(); + h.rows.find((r) => r.id === 'r003')!.notes = 'changed'; + h.rows.find((r) => r.id === 'r007')!.status = 'done'; // a metadata field + expect(await h.svc.reindexSource('s1')).toMatchObject({ ok: true, indexed: 2, skipped: 8, purged: 0 }); + expect(upsertedOf(la.upsertSpy)).toEqual(['s1:r003', 's1:r007']); + }); + + it('a listed entry with no docHash reads as changed', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + la.stored.set('s1:r001', undefined); + la.upsertSpy.mockClear(); + expect(await h.svc.reindexSource('s1')).toMatchObject({ indexed: 1, skipped: 2 }); + expect(upsertedOf(la.upsertSpy)).toEqual(['s1:r001']); + }); + + it('the listing is read page by page to its end before the walk', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + for (let i = 0; i < LIST_DOCUMENTS_PAGE_SIZE + 1; i++) la.stored.set(`s1:zz${String(i).padStart(4, '0')}`, 'x'); + const res = await h.svc.reindexSource('s1'); + expect(la.listSpy.mock.calls.map((c) => c[1])).toEqual([ + { limit: LIST_DOCUMENTS_PAGE_SIZE }, + { cursor: `s1:zz${String(LIST_DOCUMENTS_PAGE_SIZE - 1).padStart(4, '0')}`, limit: LIST_DOCUMENTS_PAGE_SIZE }, + ]); + // Every listed `zz` document has no row: all purged. + expect(res).toMatchObject({ ok: true, indexed: 3, purged: LIST_DOCUMENTS_PAGE_SIZE + 1 }); + }); + + it('purges the document of a deleted row and of a row that stopped matching where, each confirmed by a re-read', async () => { + const src = objectSource('s1', 'task'); + (src.source as ObjectKnowledgeSource).where = { status: 'open' }; + const la = listingAdapter(); + const h = reindexHarness(taskRows(5), src, la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(h.rows.findIndex((r) => r.id === 'r001'), 1); + h.rows.find((r) => r.id === 'r003')!.status = 'done'; + h.find.mockClear(); + const res = await h.svc.reindexSource('s1'); + expect(res).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: 2 }); + expect(deletedOf(la.deleteSpy).sort()).toEqual(['s1:r001', 's1:r003']); + for (const call of la.deleteSpy.mock.calls) expect(call[1]).toMatchObject({ reason: 'reindex' }); + // The confirming re-reads are the event sync's: `where` AND id, one row, system context. + const rereads = h.find.mock.calls.filter((c) => c[1].limit === 1).map((c) => c[1].where); + expect(rereads).toEqual([ + { $and: [{ status: 'open' }, { id: 'r001' }] }, + { $and: [{ status: 'open' }, { id: 'r003' }] }, + ]); + expect([...la.stored.keys()].sort()).toEqual(['s1:r000', 's1:r002', 's1:r004']); + }); + + it.each([ + ['a limit', { limit: 100 }], + ['a limit of 0', { limit: 0 }], + ['a dryRun', { dryRun: true }], + ])('a reindex with %s purges nothing and says purged: null', async (_what, opts) => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(5), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(0, 2); + const res = await h.svc.reindexSource('s1', opts); + expect(res).toMatchObject({ ok: true, purged: null }); + expect(la.deleteSpy).not.toHaveBeenCalled(); + expect(la.stored.size).toBe(5); + }); + + it('a walk with a failed page purges nothing', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(150), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(0, 1); + const real = h.find.getMockImplementation()!; + h.find.mockClear(); + h.find.mockImplementation(async (o, q, opt) => { + if (h.find.mock.calls.length === 2) throw new Error('connection reset'); + return real(o, q, opt); + }); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, purged: null }); + expect(res.message).toContain('page 2'); + expect(la.deleteSpy).not.toHaveBeenCalled(); + }); + + it('a document written by the event sync during the walk survives the purge', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + // r001's row is gone when the walk reads, so its listed document is a + // candidate — but the row is restored, and synced, before the purge runs. + const r001 = h.rows.splice(h.rows.findIndex((r) => r.id === 'r001'), 1)[0]; + const release = h.holdNextFind(); + const walk = h.svc.reindexSource('s1'); + await new Promise((r) => setTimeout(r, 5)); + h.rows.push(r001); + await h.svc.handleRecordUpsert('task', { id: 'r001' }); + // A row created during the walk: its document was never listed. + h.rows.push({ id: 'r900', title: 'New', notes: 'N', status: 'open' }); + await h.svc.handleRecordUpsert('task', { id: 'r900' }); + release(); + const res = await walk; + expect(res).toMatchObject({ ok: true, purged: 0 }); + expect(la.deleteSpy).not.toHaveBeenCalled(); + expect(la.stored.has('s1:r001')).toBe(true); + expect(la.stored.has('s1:r900')).toBe(true); + }); + + it('a source with refresh.onRecordChange: false still skips, and is never purged', async () => { + const src = { ...objectSource('s1', 'task'), refresh: { onRecordChange: false } } as KnowledgeSource; + const la = listingAdapter(); + const h = reindexHarness(taskRows(4), src, la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(0, 1); + expect(await h.svc.reindexSource('s1')).toEqual({ ok: true, object: 'task', discovered: 3, indexed: 0, skipped: 3, purged: null }); + expect(la.deleteSpy).not.toHaveBeenCalled(); + }); + + it('a listing that fails skips and purges nothing, writes every document, and says why', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(4), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(0, 1); + la.listSpy.mockImplementationOnce(async () => { throw new Error('vector store timeout'); }); + la.upsertSpy.mockClear(); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: true, discovered: 3, indexed: 3, skipped: 0, purged: null }); + expect(res.message).toContain('vector store timeout'); + expect(upsertedOf(la.upsertSpy)).toHaveLength(3); + expect(la.deleteSpy).not.toHaveBeenCalled(); + }); + + it('a listing whose cursor comes back twice is refused rather than looped on', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(2), objectSource('s1', 'task'), la.adapter); + la.listSpy.mockImplementation(async () => ({ documents: [], nextCursor: 'same' })); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: true, indexed: 2, purged: null }); + expect(res.message).toMatch(/came back twice/); + expect(la.listSpy).toHaveBeenCalledTimes(2); + }); + + it('a purge whose re-read fails stops, keeps the document and reports ok:false', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(0, 1); + const real = h.find.getMockImplementation()!; + h.find.mockImplementation(async (o, q, opt) => { + if (q.limit === 1) throw new Error('replica lag'); + return real(o, q, opt); + }); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, discovered: 2, purged: 0 }); + expect(res.message).toMatch(/purge stopped after 0 deletion\(s\): document 's1:r000': replica lag/); + expect(la.stored.has('s1:r000')).toBe(true); + }); + + it('a listed document whose id this source does not derive is kept, and the result says so', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(2), objectSource('s1', 'task'), la.adapter); + la.stored.set('pushed-faq-1', 'x'); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: true, purged: 0 }); + expect(res.message).toMatch(/1 listed document\(s\) carry an id/); + expect(la.stored.has('pushed-faq-1')).toBe(true); }); }); From 49e730c1a89851dc6fd363c310dffc57561cb076 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:45:07 +0000 Subject: [PATCH 03/13] wip: changeset Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .changeset/37096-knowledge-list-skip-purge.md diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md new file mode 100644 index 00000000000..7bbffbb6370 --- /dev/null +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-memory': patch +--- + +feat(service-knowledge): adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one adapter contract test suite + +Clause-②: yes +Metadata-protocol: none + +Two optional knowledge-adapter contract members land with their reader (ADR-0161 K8, items 1 and 2): + +- `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` answers `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }` — the documents the adapter holds for the source, a page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`. +- `KnowledgeDocument.docHash?` — a hash of the assembled document (content, title and metadata, in a stable key order, behind the `v1:` prefix). The knowledge service computes it on every document it hands an adapter, `indexDocument` included (a caller's own value is replaced); the adapter stores it and returns it as stored. + +`KnowledgeService.reindexSource` of an `object` source, over an adapter that implements `listDocuments`, lists the adapter's documents first and does not write a document again when its computed `docHash` equals the listed one. After a complete walk — no `limit`, no `dryRun`, no failed page — it purges each listed document the walk did not see, once the event sync's own re-read (the source's `where` AND the record id) confirms no row backs it; a row created or restored during the walk keeps its document. `KnowledgeReindexResult` gains `skipped` and `purged`; `purged` is `null` when no purge ran (a `limit` or `dryRun` walk, a failed walk, a source with `refresh.onRecordChange: false`, or an adapter without `listDocuments`, which also skips nothing). A failed listing skips and purges nothing and the result's `message` says why; a failed purge step answers `ok: false`. The purge is the exported `purgeDocuments` function of the service module. + +`@objectstack/service-knowledge/testing` (new, test-only, ESM only — it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`: upsert / search / delete, `listDocuments` page boundaries and `docHash` round-trips, and the skip and purge through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite. + +What to do: nothing. An adapter without `listDocuments` keeps working; its reindex writes every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the purge, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. From ba749f2f2fcc3a4b0a5bddbd42250e123cd806cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:48:16 +0000 Subject: [PATCH 04/13] chore(spec): regenerate api-surface, export-origins, authorable-surface and reference docs for the knowledge members Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- content/docs/references/ai/knowledge-document.mdx | 1 + packages/spec/api-surface/contracts.json | 3 +++ packages/spec/authorable-surface/ai.json | 1 + packages/spec/export-origins/contracts.json | 3 +++ 4 files changed, 8 insertions(+) diff --git a/content/docs/references/ai/knowledge-document.mdx b/content/docs/references/ai/knowledge-document.mdx index 9492bc5ac9b..34ab2a70204 100644 --- a/content/docs/references/ai/knowledge-document.mdx +++ b/content/docs/references/ai/knowledge-document.mdx @@ -60,6 +60,7 @@ const result = KnowledgeChunkSchema.parse(data); | **title** | `string` | optional | | | **metadata** | `Record` | optional (default: `{}`) | | | **permissions** | `string[]` | optional | | +| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter | --- diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 663aa38ed20..ab81d11b5f4 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -35,6 +35,9 @@ "ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails (interface)", "AdapterContext (interface)", + "AdapterListDocumentsOptions (interface)", + "AdapterListDocumentsPage (interface)", + "AdapterListedDocument (interface)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", "AnalyticsQuery (type)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 6768d287b01..f653ed222d0 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -222,6 +222,7 @@ "ai/KnowledgeChunk:index", "ai/KnowledgeChunk:metadata", "ai/KnowledgeDocument:content", + "ai/KnowledgeDocument:docHash", "ai/KnowledgeDocument:id", "ai/KnowledgeDocument:metadata", "ai/KnowledgeDocument:permissions", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 8362571c196..8e01e4ac6bb 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -35,6 +35,9 @@ "ActionConfirmationRefusalReason": "src/contracts/ai-service.ts#ActionConfirmationRefusalReason (type)", "ActionConfirmationRequiredDetails": "src/contracts/ai-service.ts#ActionConfirmationRequiredDetails (interface)", "AdapterContext": "src/contracts/knowledge-adapter.ts#AdapterContext (interface)", + "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", + "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", + "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", "AnalyticsQuery": "src/data/analytics.zod.ts#AnalyticsQuery (type)", From c6e78ea50a99d4ffa0236a304426c7e8a9266bd9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:58:37 +0000 Subject: [PATCH 05/13] fix(service-knowledge): type the contract suite's adapter receivers so the tenant-audit census can place them Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .../services/service-knowledge/src/testing.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 14c34286815..b5b03dba734 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -144,7 +144,7 @@ function rowsEngine(rows: Row[]): IDataEngine { /** A `KnowledgeService` over `adapter` and `rows`, with the adapter's `upsert` counted. */ async function serviceOver(make: () => IKnowledgeAdapter | Promise, rows: Row[], source: KnowledgeSource) { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const upserted: string[][] = []; // Delegation, not a prototype proxy: an adapter with `#private` fields only // answers when its methods are called on the adapter itself. @@ -178,14 +178,14 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption describe(`IKnowledgeAdapter contract — ${opts.name}`, () => { it('declares exactly the optional members it implements', async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); expect(typeof adapter.id).toBe('string'); expect(typeof adapter.listDocuments === 'function').toBe(opts.implements.listDocuments); }); describe('upsert / search / delete', () => { it('a search finds an upserted document, scoped to the searched source, best first', async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); const b = objectSource('b'); await adapter.upsert([doc(a, '1', 'alpine meadow flowers'), doc(a, '2', 'harbour cranes at night')], ctxOf(a)); @@ -199,7 +199,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); it('an upsert of an existing id replaces the document', async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); await adapter.upsert([doc(a, '1', 'volcanic basalt columns')], ctxOf(a)); await adapter.upsert([doc(a, '1', 'glacier ice caves')], ctxOf(a)); @@ -210,7 +210,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); it('a deleted document is not found; deleting an absent id is a no-op', async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); await adapter.upsert([doc(a, '1', 'copper kettle'), doc(a, '2', 'copper wire')], ctxOf(a)); await adapter.delete([`${a.id}:1`, `${a.id}:absent`], ctxOf(a)); @@ -226,7 +226,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption ['exactly one page', 3], ['one page + 1', 4], ])('%s: every document once, no page over its limit', async (_label, n) => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); if (n > 0) { await adapter.upsert( @@ -244,7 +244,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); it('returns each docHash as stored, and none for a document stored without one', async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); await adapter.upsert([doc(a, '1', 'granite quarry', 'v1:opaque-as-given'), doc(a, '2', 'marble quarry')], ctxOf(a)); await adapter.upsert([doc(a, '1', 'granite quarry, revised', 'v1:replaced')], ctxOf(a)); @@ -256,7 +256,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); it("lists only the source's own documents, and none that were deleted", async () => { - const adapter = await make(); + const adapter: IKnowledgeAdapter = await make(); const a = objectSource('a'); const b = objectSource('b'); await adapter.upsert([doc(a, '1', 'tidal pool'), doc(a, '2', 'tidal flat')], ctxOf(a)); From cf8b70ae216330df78d1c9c56774ecc58c560106 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 00:28:44 +0000 Subject: [PATCH 06/13] feat(spec): KnowledgeReindexResult gains skipped and purged; knowledge-ragflow aliases the ./testing subpath File surface extended by the dispatching zone (card What 4; check:test-source-alias). Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .../plugins/knowledge-ragflow/vitest.config.ts | 6 ++++++ packages/spec/src/contracts/knowledge-service.ts | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/plugins/knowledge-ragflow/vitest.config.ts b/packages/plugins/knowledge-ragflow/vitest.config.ts index e9052fa159f..075f8e3b3e8 100644 --- a/packages/plugins/knowledge-ragflow/vitest.config.ts +++ b/packages/plugins/knowledge-ragflow/vitest.config.ts @@ -25,6 +25,12 @@ export default defineConfig({ { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, + // The published `./testing` subpath BEFORE the bare package, which is a + // PREFIX match with a FILE replacement (ENOTDIR otherwise). + { + find: /^@objectstack\/service-knowledge\/testing$/, + replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'), + }, { find: '@objectstack/service-knowledge', replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'), diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index ed0b9d0826c..1ba96fa5d0f 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -63,6 +63,20 @@ export interface KnowledgeReindexResult { ok: boolean; /** Free-form diagnostics. */ message?: string; + /** + * Documents the walk did not push because the adapter already holds them + * with the same `docHash` (ADR-0161 K8, item 2). `0` when the adapter has + * no `listDocuments`, whose walk pushes every document. + */ + skipped?: number; + /** + * Documents deleted by the purge that follows a complete walk: listed by + * the adapter before the walk, not seen in it, and confirmed gone by a + * re-read of their row (ADR-0161 K8, item 1). `null` when no purge ran — a + * walk with `limit` or `dryRun`, a failed walk, a source with + * `refresh.onRecordChange: false`, or an adapter without `listDocuments`. + */ + purged?: number | null; } /** From 84aa5e904c1ab3c25ab14ad58f8b650b1c55685c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:46:49 +0000 Subject: [PATCH 07/13] chore(changeset): the docHash key is a metadata-protocol addition; spec takes minor Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md index 7bbffbb6370..86971a4faa6 100644 --- a/.changeset/37096-knowledge-list-skip-purge.md +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/service-knowledge': patch '@objectstack/knowledge-memory': patch --- @@ -7,7 +7,7 @@ feat(service-knowledge): adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one adapter contract test suite Clause-②: yes -Metadata-protocol: none +Metadata-protocol: added Two optional knowledge-adapter contract members land with their reader (ADR-0161 K8, items 1 and 2): From eddd9a64b0f86f5604a3bc7dda84a409fca49450 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:47:27 +0000 Subject: [PATCH 08/13] chore(changeset): Skills-docs line for the metadata-protocol addition Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md index 86971a4faa6..8d33c8168e7 100644 --- a/.changeset/37096-knowledge-list-skip-purge.md +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -8,6 +8,7 @@ feat(service-knowledge): adapters list their documents; a complete reindex skips Clause-②: yes Metadata-protocol: added +Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, the adapter contract or reindex; `skills/objectstack-ai/SKILL.md` teaches `KnowledgeSource` authoring only, which this change does not touch. `content/docs/protocol/knowledge.mdx` gains the members, the skip and the purge in this change. Two optional knowledge-adapter contract members land with their reader (ADR-0161 K8, items 1 and 2): From 58478cafac5ea4348b684bb80ee2a60a9efae38c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 01:54:36 +0000 Subject: [PATCH 09/13] fix(service-knowledge): indexDocument refuses a caller-supplied docHash instead of replacing it Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 2 +- .../src/__tests__/knowledge-service.test.ts | 16 ++++++++++++++-- .../service-knowledge/src/knowledge-service.ts | 11 +++++++++-- packages/spec/src/ai/knowledge-document.zod.ts | 11 ++++++----- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md index 8d33c8168e7..5b8856163ec 100644 --- a/.changeset/37096-knowledge-list-skip-purge.md +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -13,7 +13,7 @@ Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, th Two optional knowledge-adapter contract members land with their reader (ADR-0161 K8, items 1 and 2): - `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` answers `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }` — the documents the adapter holds for the source, a page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`. -- `KnowledgeDocument.docHash?` — a hash of the assembled document (content, title and metadata, in a stable key order, behind the `v1:` prefix). The knowledge service computes it on every document it hands an adapter, `indexDocument` included (a caller's own value is replaced); the adapter stores it and returns it as stored. +- `KnowledgeDocument.docHash?` — a hash of the assembled document (content, title and metadata, in a stable key order, behind the `v1:` prefix). The knowledge service computes it on every document it hands an adapter, `indexDocument` included (a caller-supplied `docHash` is refused there: `indexDocument` throws, naming `docHash` and that the service computes it); the adapter stores it and returns it as stored. `KnowledgeService.reindexSource` of an `object` source, over an adapter that implements `listDocuments`, lists the adapter's documents first and does not write a document again when its computed `docHash` equals the listed one. After a complete walk — no `limit`, no `dryRun`, no failed page — it purges each listed document the walk did not see, once the event sync's own re-read (the source's `where` AND the record id) confirms no row backs it; a row created or restored during the walk keeps its document. `KnowledgeReindexResult` gains `skipped` and `purged`; `purged` is `null` when no purge ran (a `limit` or `dryRun` walk, a failed walk, a source with `refresh.onRecordChange: false`, or an adapter without `listDocuments`, which also skips nothing). A failed listing skips and purges nothing and the result's `message` says why; a failed purge step answers `ok: false`. The purge is the exported `purgeDocuments` function of the service module. diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 60f261c53d4..087e9741d44 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -80,9 +80,9 @@ describe('KnowledgeService — adapter & source registry', () => { const a = makeAdapter('memory'); svc.registerAdapter('memory', a); svc.registerSource(objectSource('s1', 'task')); - const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello', docHash: 'caller-supplied' }; + const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello' }; await svc.indexDocument('s1', doc); - // The service computes `docHash`; a caller's own value never reaches the adapter. + // The service computes `docHash` and stamps it on the document it hands the adapter. expect(a.upsertSpy).toHaveBeenCalledWith( [{ ...doc, docHash: computeDocHash(doc) }], expect.objectContaining({ reason: 'manual' }), @@ -91,6 +91,18 @@ describe('KnowledgeService — adapter & source registry', () => { expect(a.deleteSpy).toHaveBeenCalledWith(['d1'], expect.objectContaining({ reason: 'manual' })); }); + it('indexDocument refuses a caller-supplied docHash, naming it, and writes nothing', async () => { + const svc = new KnowledgeService(); + const a = makeAdapter('memory'); + svc.registerAdapter('memory', a); + svc.registerSource(objectSource('s1', 'task')); + const doc: KnowledgeDocument = { id: 'd1', sourceId: 's1', content: 'hello', docHash: 'v1:caller-supplied' }; + await expect(svc.indexDocument('s1', doc)).rejects.toThrow( + /indexDocument refused document 'd1': docHash is computed by the knowledge service/, + ); + expect(a.upsertSpy).not.toHaveBeenCalled(); + }); + it('indexDocument throws on unknown source', async () => { const svc = new KnowledgeService(); await expect(svc.indexDocument('nope', { id: 'd', sourceId: 'nope', content: '' })).rejects.toThrow(/unknown source/); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 1fc0e0cc939..6e926bc4d0c 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -161,8 +161,15 @@ export class KnowledgeService implements IKnowledgeService { async indexDocument(sourceId: string, doc: KnowledgeDocument): Promise { const source = this.requireSource(sourceId); const adapter = this.getAdapter(source.adapter); - // `docHash` is the service's to compute (ADR-0161 K8, item 2): a caller's - // own value is replaced, never passed through. + // `docHash` is the service's to compute (ADR-0161 K8, item 2). A caller's + // own value is refused, never replaced in silence: a door that accepted it + // and stored something else would answer as if it had been honoured. + if (doc.docHash !== undefined) { + throw new Error( + `[knowledge] indexDocument refused document '${doc.id}': docHash is computed by the knowledge service ` + + 'from the content, title and metadata; omit it.', + ); + } await adapter.upsert([{ ...doc, docHash: computeDocHash(doc) }], { source, reason: 'manual' }); } diff --git a/packages/spec/src/ai/knowledge-document.zod.ts b/packages/spec/src/ai/knowledge-document.zod.ts index 93647fd7cf2..7ef0f986574 100644 --- a/packages/spec/src/ai/knowledge-document.zod.ts +++ b/packages/spec/src/ai/knowledge-document.zod.ts @@ -50,11 +50,12 @@ export const KnowledgeDocumentSchema = lazySchema(() => z.object({ permissions: z.array(z.string()).optional(), /** * A hash of the assembled document — its content, title and metadata, in a - * stable key order, behind a version prefix (ADR-0161 K8, item 2). Computed - * by the knowledge service on every document it hands an adapter, stored by - * the adapter, and returned as stored by `listDocuments`; an unchanged hash - * lets a complete reindex skip writing the document again. Adapters never - * compute or alter it. + * stable key order, behind a version prefix (ADR-0161 K8, item 2). Set by + * the knowledge service on every document it hands an adapter; a + * caller-supplied value is refused by `indexDocument`. Stored by the adapter + * and returned as stored by `listDocuments`; an unchanged hash lets a + * complete reindex skip writing the document again. Adapters never compute + * or alter it. */ docHash: z.string().optional() .describe('Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter'), From 85a3f8c9e5672dc77bf34bd3cda02669200da950 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:53:34 +0000 Subject: [PATCH 10/13] fix(service-knowledge): the purge never deletes on an unreadable answer, finds numeric ids by number; pin its sync chain Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 20 +++-- .../src/__tests__/knowledge-service.test.ts | 86 +++++++++++++++++++ .../src/knowledge-service.ts | 43 ++++++++-- .../spec/src/contracts/knowledge-service.ts | 13 ++- 4 files changed, 147 insertions(+), 15 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index edd453588db..036d3813fe1 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -161,7 +161,8 @@ Canonical shapes shared by every adapter: `sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`). `docHash` is a hash of the assembled document — content, title and metadata, in a stable key order, behind a version prefix (`v1:`). The - service computes it on every document it hands an adapter; the adapter + service computes it on every document it hands an adapter, and + `indexDocument` refuses a document that already carries one; the adapter stores it and returns it as stored, and never computes or alters it. - `KnowledgeChunk` — adapter-produced chunk of a document. The framework does **not** chunk; adapters do. @@ -469,8 +470,12 @@ id → stored `docHash`), then walks the object's rows page by page: makes (the source's `where` AND the record id, under the system context) and deleted only when that finds no row. A row created or restored during the walk keeps its document: if it was listed, the re-read finds it; if it was - not, it was never a candidate. The purge of a document waits for any - in-flight event sync of the same document. `purged` counts the deletions. + not, it was never a candidate. The record id is read back from the document + id as text; when that text is a whole number and the first re-read finds no + row, the row is asked for again by the number, so a caller-supplied numeric + id is found on a driver that does not equate `'5'` with `5`. The purge of a + document waits for any in-flight event sync of the same document. `purged` + counts the deletions. - **`purged: null`** means no purge ran: a walk with a `limit` or a `dryRun`, a failed walk, a source with `refresh.onRecordChange: false` (an external indexer owns its index), or an adapter without `listDocuments` — which also @@ -480,9 +485,12 @@ id → stored `docHash`), then walks the object's rows page by page: (`:`) is never purged, since no row can confirm it; the result's `message` counts such documents. -A re-read or delete that fails stops the purge: the result is `ok: false`, -`purged` counts the deletions made before it, and the `message` names the -document. +A re-read or delete that fails stops the purge — a re-read that answers no +list of rows counts as failed, never as "no row" — and the result is +`ok: false`, `purged` counts the deletions made before it, and the `message` +names the document. A walk page that answers no list of rows stops the walk +the same way, with `purged: null`, rather than ending it as if the source were +empty. ### Retention deletes are covered by a reap guard diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 087e9741d44..092b89662d2 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1071,3 +1071,89 @@ describe('KnowledgeService — a complete reindex skips unchanged documents and expect(la.stored.has('pushed-faq-1')).toBe(true); }); }); + +describe('KnowledgeService — the purge never deletes on an answer it cannot read, and waits for the event sync', () => { + it('a walk page that answers no list stops the walk: ok:false, purged: null, nothing deleted', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + const real = h.find.getMockImplementation()!; + h.find.mockImplementation(async (o, q, opt) => (q.limit === REINDEX_PAGE_SIZE ? (null as never) : real(o, q, opt))); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, discovered: 0, purged: null }); + expect(res.message).toContain('page 1: the read answered null instead of a list of rows.'); + expect(la.deleteSpy).not.toHaveBeenCalled(); + expect(la.stored.size).toBe(3); + }); + + it('a purge re-read that answers no list stops the purge: ok:false, the document kept', async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + h.rows.splice(h.rows.findIndex((r) => r.id === 'r000'), 1); + const real = h.find.getMockImplementation()!; + h.find.mockImplementation(async (o, q, opt) => (q.limit === 1 ? (undefined as never) : real(o, q, opt))); + const res = await h.svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, discovered: 2, purged: 0 }); + expect(res.message).toMatch(/document 's1:r000': the re-read of record 'r000' answered undefined instead of a list of rows/); + expect(la.deleteSpy).not.toHaveBeenCalled(); + expect(la.stored.has('s1:r000')).toBe(true); + }); + + it("the purge's re-read and delete run on the document's sync chain: an event sync arriving meanwhile lands after them", async () => { + const la = listingAdapter(); + const h = reindexHarness(taskRows(3), objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + const r001 = h.rows.splice(h.rows.findIndex((r) => r.id === 'r001'), 1)[0]; + // Hold the purge's re-read of r001 AFTER it has read (no row): the purge is + // now between its re-read and its delete. + const real = h.find.getMockImplementation()!; + let reached!: () => void; + const atReread = new Promise((resolve) => { reached = resolve; }); + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + let held = false; + h.find.mockImplementation(async (o, q, opt) => { + const answer = await real(o, q, opt); + if (q.limit === 1 && !held) { + held = true; + reached(); + await gate; + } + return answer; + }); + const walk = h.svc.reindexSource('s1'); + await atReread; + // The row is restored and its event sync fires while the purge is held. + h.rows.push(r001); + const sync = h.svc.handleRecordUpsert('task', { id: 'r001' }); + await new Promise((r) => setTimeout(r, 5)); + release(); + await Promise.all([walk, sync]); + // On the chain, the sync re-reads after the purge's delete and writes the + // document back; off it, the sync would write first and the purge delete it. + expect(la.stored.has('s1:r001')).toBe(true); + }); + + it('a numeric record id restored during the walk is found by its number and kept; a gone one is purged', async () => { + const la = listingAdapter(); + const rows = taskRows(5).map((r) => ({ ...r, id: Number(String(r.id).slice(1)) + 1 })); + const h = reindexHarness(rows, objectSource('s1', 'task'), la.adapter); + await h.svc.reindexSource('s1'); + // Row 2 is gone when the walk reads and back before the purge; row 4 is gone for good. + const row2 = h.rows.splice(h.rows.findIndex((r) => r.id === 2), 1)[0]; + h.rows.splice(h.rows.findIndex((r) => r.id === 4), 1); + const release = h.holdNextFind(); + const walk = h.svc.reindexSource('s1'); + await new Promise((r) => setTimeout(r, 5)); + h.rows.push(row2); + release(); + const res = await walk; + expect(res).toMatchObject({ ok: true, purged: 1 }); + expect(deletedOf(la.deleteSpy)).toEqual(['s1:4']); + expect(la.stored.has('s1:2')).toBe(true); + // The text form is asked first, then the number the text spells. + const rereads = h.find.mock.calls.filter((c) => c[1].limit === 1).map((c) => c[1].where); + expect(rereads).toEqual(expect.arrayContaining([{ id: '2' }, { id: 2 }, { id: '4' }, { id: 4 }])); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 6e926bc4d0c..40ce168b4df 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -373,7 +373,13 @@ export class KnowledgeService implements IKnowledgeService { // Only an EMPTY page ends the walk. A short page does not: `find` does // not promise `min(limit, remaining)` rows — an `afterFind` hook may drop // rows from a page — so rows after a short page can still exist. - if (!Array.isArray(rows) || rows.length === 0) break; + // A read that answers no list is a failed read, never the end of the + // source: read as an empty page it would make a complete walk of nothing + // and hand every listed document to the purge. + if (!Array.isArray(rows)) { + return stopped(`the read answered ${describeValue(rows)} instead of a list of rows.`); + } + if (rows.length === 0) break; let docs: KnowledgeDocument[]; try { @@ -950,7 +956,8 @@ function systemContext(): ExecutionContext { * limit: 1 })` — so the database answers whether the row belongs in the * index, never an event payload or an earlier read. `undefined` when no row * matches (none exists, or it does not match `where`). Throws what `find` - * throws. + * throws, and throws when `find` answers no list: "no row" is a verdict the + * purge deletes on, so a malformed answer is never read as one. * * One definition for both of its readers, the event sync * ({@link KnowledgeService.handleRecordUpsert}) and the purge @@ -968,7 +975,10 @@ async function rereadRow( { where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, limit: 1 }, { context: systemContext() }, ); - return Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; + if (!Array.isArray(rows)) { + throw new Error(`the re-read of record '${String(recordId)}' answered ${describeValue(rows)} instead of a list of rows`); + } + return rows[0] as Record | undefined; } /** @@ -1053,8 +1063,13 @@ export interface PurgeDocumentsOutcome { * gone. Each candidate is confirmed by {@link rereadRow} — the event sync's * own re-read, `where` AND id under the system context — and deleted only * when that finds no row, so a document whose row was created, restored or - * came back into `where` since the candidates were computed is kept. Stops at - * the first re-read or delete that throws, counting what it did before. + * came back into `where` since the candidates were computed is kept. The + * record id is recovered from the document id as text; when that text is a + * canonical safe integer and the first re-read finds nothing, the row is asked + * for again by the number, so a caller-supplied numeric id on a driver that + * does not equate `'5'` with `5` is still found. Stops at the first re-read or + * delete that throws (a re-read that answers no list included), counting what + * it did before. * * The caller decides when a purge may run at all (a complete reindex walk; * the scheduled reconcile reuses this function) and computes the candidates. @@ -1072,6 +1087,12 @@ export async function purgeDocuments(input: PurgeDocumentsInput): Promise { if (await rereadRow(engine, objSource, recordId)) return false; + // The document id carries the record id as text. A row whose id is the + // number that text spells (a caller-supplied numeric id, on a driver + // that does not equate '5' with 5) is asked for again by the number, + // so the purge and the event sync give one answer for one row. + const asNumber = canonicalSafeInteger(recordId); + if (asNumber !== undefined && (await rereadRow(engine, objSource, asNumber))) return false; await adapter.delete([documentId], { source, reason: input.reason ?? 'reindex' }); return true; }); @@ -1117,6 +1138,18 @@ function stableJson(value: unknown): string { }); } +/** How a non-list answer is named in a refusal: `null`, `undefined`, or its `typeof`. */ +function describeValue(value: unknown): string { + return value === null ? 'null' : value === undefined ? 'undefined' : `a value of type ${typeof value}`; +} + +/** The number a record id's text spells, when it is a canonical safe integer (`'5'`, `'-12'`; never `'05'` or `'-0'`). */ +function canonicalSafeInteger(text: string): number | undefined { + if (!/^(0|-?[1-9][0-9]*)$/.test(text)) return undefined; + const n = Number(text); + return Number.isSafeInteger(n) ? n : undefined; +} + /** A thrown value's text: an `Error`'s message, anything else as a string. */ function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); diff --git a/packages/spec/src/contracts/knowledge-service.ts b/packages/spec/src/contracts/knowledge-service.ts index 1ba96fa5d0f..8cf3a874c72 100644 --- a/packages/spec/src/contracts/knowledge-service.ts +++ b/packages/spec/src/contracts/knowledge-service.ts @@ -66,15 +66,20 @@ export interface KnowledgeReindexResult { /** * Documents the walk did not push because the adapter already holds them * with the same `docHash` (ADR-0161 K8, item 2). `0` when the adapter has - * no `listDocuments`, whose walk pushes every document. + * no `listDocuments`, whose walk pushes every document. Absent from a result + * of an implementation that predates the field. */ skipped?: number; /** * Documents deleted by the purge that follows a complete walk: listed by * the adapter before the walk, not seen in it, and confirmed gone by a - * re-read of their row (ADR-0161 K8, item 1). `null` when no purge ran — a - * walk with `limit` or `dryRun`, a failed walk, a source with - * `refresh.onRecordChange: false`, or an adapter without `listDocuments`. + * re-read of their row (ADR-0161 K8, item 1). `null` when no purge ran: + * a source that is not an `object` source, no data engine bound, a refused + * `limit`, a walk with `limit` or `dryRun`, a failed walk, a source with + * `refresh.onRecordChange: false`, an adapter without `listDocuments`, or a + * listing that failed. A number, with `ok: false`, when the purge stopped + * part-way: the deletions made before it stopped. Absent from a result of an + * implementation that predates the field. */ purged?: number | null; } From ffc6bff41d23f5d9418a5029ed4a392eb0a072d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 02:57:37 +0000 Subject: [PATCH 11/13] chore(changeset): plain wording; list when purged is null Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md index 5b8856163ec..29b55c8491e 100644 --- a/.changeset/37096-knowledge-list-skip-purge.md +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -10,13 +10,21 @@ Clause-②: yes Metadata-protocol: added Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, the adapter contract or reindex; `skills/objectstack-ai/SKILL.md` teaches `KnowledgeSource` authoring only, which this change does not touch. `content/docs/protocol/knowledge.mdx` gains the members, the skip and the purge in this change. -Two optional knowledge-adapter contract members land with their reader (ADR-0161 K8, items 1 and 2): +Knowledge adapters can now list the documents they hold, and a full reindex uses that list to skip unchanged documents and to remove documents whose record is gone. -- `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` answers `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }` — the documents the adapter holds for the source, a page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`. -- `KnowledgeDocument.docHash?` — a hash of the assembled document (content, title and metadata, in a stable key order, behind the `v1:` prefix). The knowledge service computes it on every document it hands an adapter, `indexDocument` included (a caller-supplied `docHash` is refused there: `indexDocument` throws, naming `docHash` and that the service computes it); the adapter stores it and returns it as stored. +New, all optional, in `@objectstack/spec`: -`KnowledgeService.reindexSource` of an `object` source, over an adapter that implements `listDocuments`, lists the adapter's documents first and does not write a document again when its computed `docHash` equals the listed one. After a complete walk — no `limit`, no `dryRun`, no failed page — it purges each listed document the walk did not see, once the event sync's own re-read (the source's `where` AND the record id) confirms no row backs it; a row created or restored during the walk keeps its document. `KnowledgeReindexResult` gains `skipped` and `purged`; `purged` is `null` when no purge ran (a `limit` or `dryRun` walk, a failed walk, a source with `refresh.onRecordChange: false`, or an adapter without `listDocuments`, which also skips nothing). A failed listing skips and purges nothing and the result's `message` says why; a failed purge step answers `ok: false`. The purge is the exported `purgeDocuments` function of the service module. +- `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` returns `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }`: the documents the adapter holds for a source, one page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`. +- `KnowledgeDocument.docHash?`: a hash of the document's content, title and metadata, prefixed `v1:`. The knowledge service sets it on every document it hands an adapter; the adapter stores it and returns it unchanged. `indexDocument` refuses a document that already carries a `docHash` (it throws, naming the field). +- `KnowledgeReindexResult.skipped?` and `purged?`. -`@objectstack/service-knowledge/testing` (new, test-only, ESM only — it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`: upsert / search / delete, `listDocuments` page boundaries and `docHash` round-trips, and the skip and purge through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite. +`KnowledgeService.reindexSource` for an `object` source, when the source's adapter implements `listDocuments`: -What to do: nothing. An adapter without `listDocuments` keeps working; its reindex writes every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the purge, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. +- does not send a document to the adapter again when its hash is unchanged, and counts it in `skipped`; +- after a full run (no `limit`, no `dryRun`, every page read), deletes each listed document whose record no longer exists or no longer matches the source's `where`. Before each deletion it reads the record again; a record that exists at that moment keeps its document, a numeric record id included. A deletion never overlaps a sync of the same record. `purged` counts the deletions. + +`purged` is `null` when nothing was deleted because no removal ran: the adapter has no `listDocuments`, the run had a `limit` or `dryRun`, a page failed or answered no list of rows, the source sets `refresh.onRecordChange: false`, or the adapter's listing failed (the `message` says why). If a re-read or a deletion fails, the result is `ok: false` and `purged` counts the deletions made before it. + +`@objectstack/service-knowledge/testing` (new, test-only, ESM only; it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`, a test suite any adapter package runs with its own factory: upsert, search and delete; `listDocuments` paging and `docHash` round-trips; and the skip and the removal through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite. + +What to do: nothing. An adapter without `listDocuments` keeps working; its reindex sends every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the removal, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. A caller of `indexDocument` stops setting `docHash`. From 48ed4f12aefa95cb1def5a3ff57a13c5d52e2ad6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 04:03:44 +0000 Subject: [PATCH 12/13] fix(service-knowledge): drop the purge's numeric re-ask and state the limit; pin the event sync's keep; no clock in the purge tests Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- .changeset/37096-knowledge-list-skip-purge.md | 4 +- content/docs/protocol/knowledge.mdx | 19 ++++--- .../src/__tests__/knowledge-service.test.ts | 57 ++++++++++++++----- .../src/knowledge-service.ts | 36 ++++++------ 4 files changed, 75 insertions(+), 41 deletions(-) diff --git a/.changeset/37096-knowledge-list-skip-purge.md b/.changeset/37096-knowledge-list-skip-purge.md index 29b55c8491e..3931e78a3f5 100644 --- a/.changeset/37096-knowledge-list-skip-purge.md +++ b/.changeset/37096-knowledge-list-skip-purge.md @@ -21,10 +21,12 @@ New, all optional, in `@objectstack/spec`: `KnowledgeService.reindexSource` for an `object` source, when the source's adapter implements `listDocuments`: - does not send a document to the adapter again when its hash is unchanged, and counts it in `skipped`; -- after a full run (no `limit`, no `dryRun`, every page read), deletes each listed document whose record no longer exists or no longer matches the source's `where`. Before each deletion it reads the record again; a record that exists at that moment keeps its document, a numeric record id included. A deletion never overlaps a sync of the same record. `purged` counts the deletions. +- after a full run (no `limit`, no `dryRun`, every page read), deletes each listed document whose record no longer exists or no longer matches the source's `where`. Before each deletion it reads the record again; a record that exists at that moment keeps its document. A deletion never overlaps a sync of the same record. `purged` counts the deletions. Known limit: on driver-mongodb and driver-memory, a record stored under a caller-supplied numeric id is not found by that re-read, so if it was restored during the run its document is deleted until the record's next change or the next full reindex. `purged` is `null` when nothing was deleted because no removal ran: the adapter has no `listDocuments`, the run had a `limit` or `dryRun`, a page failed or answered no list of rows, the source sets `refresh.onRecordChange: false`, or the adapter's listing failed (the `message` says why). If a re-read or a deletion fails, the result is `ok: false` and `purged` counts the deletions made before it. +The record sync (on record create, update and restore) now leaves a document in place and logs a warning when the data engine answers its re-read with something other than a list of rows; it used to delete the document. + `@objectstack/service-knowledge/testing` (new, test-only, ESM only; it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`, a test suite any adapter package runs with its own factory: upsert, search and delete; `listDocuments` paging and `docHash` round-trips; and the skip and the removal through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite. What to do: nothing. An adapter without `listDocuments` keeps working; its reindex sends every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the removal, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. A caller of `indexDocument` stops setting `docHash`. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 036d3813fe1..40f1dffc4ea 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -470,12 +470,16 @@ id → stored `docHash`), then walks the object's rows page by page: makes (the source's `where` AND the record id, under the system context) and deleted only when that finds no row. A row created or restored during the walk keeps its document: if it was listed, the re-read finds it; if it was - not, it was never a candidate. The record id is read back from the document - id as text; when that text is a whole number and the first re-read finds no - row, the row is asked for again by the number, so a caller-supplied numeric - id is found on a driver that does not equate `'5'` with `5`. The purge of a - document waits for any in-flight event sync of the same document. `purged` - counts the deletions. + not, it was never a candidate. The purge of a document waits for any + in-flight event sync of the same document. `purged` counts the deletions. +- **Known limit: numeric record ids.** The purge reads the record id back from + the document id as text and re-reads by that text. On driver-mongodb and + driver-memory, which do not equate `'5'` with `5`, a row stored under a + caller-supplied numeric id is not found by that re-read; if such a row was + restored (or came back into `where`) after the walk read past it, its + document is deleted. The row itself is untouched, and its document returns at + the row's next event or the next complete reindex. Platform-minted ids are + text on every driver, so this needs a caller-supplied numeric id. - **`purged: null`** means no purge ran: a walk with a `limit` or a `dryRun`, a failed walk, a source with `refresh.onRecordChange: false` (an external indexer owns its index), or an adapter without `listDocuments` — which also @@ -490,7 +494,8 @@ list of rows counts as failed, never as "no row" — and the result is `ok: false`, `purged` counts the deletions made before it, and the `message` names the document. A walk page that answers no list of rows stops the walk the same way, with `purged: null`, rather than ending it as if the source were -empty. +empty. The event sync shares that re-read: when it answers no list of rows, the +sync leaves the document in place and logs a warning, rather than deleting it. ### Retention deletes are covered by a reap guard diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 092b89662d2..a9adc919921 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -489,6 +489,7 @@ function compareIds(a: unknown, b: unknown): number { function pagedEngine(rowsIn: PagedRow[]) { const rows = [...rowsIn]; let hold: Promise | undefined; + let heldReached: (() => void) | undefined; const matches = (row: PagedRow, where: Record | undefined): boolean => { if (!where) return true; for (const [key, value] of Object.entries(where)) { @@ -536,7 +537,10 @@ function pagedEngine(rowsIn: PagedRow[]) { .map((r) => ({ ...r })); const gate = hold; hold = undefined; - if (gate) await gate; + if (gate) { + heldReached?.(); + await gate; + } return page; }); const count = vi.fn(async (_object: string, query: { where?: Record }) => @@ -548,10 +552,16 @@ function pagedEngine(rowsIn: PagedRow[]) { /** The double's live rows: a case mutates them to change the database under the service. */ rows, /** The next `find` reads at call time but resolves only once the returned function is called. */ - holdNextFind(): () => void { + /** + * The next `find` reads at call time but resolves only once the returned + * function is called; its `reached` resolves when that `find` has been + * entered, so a case waits on the walk itself, never on a clock. + */ + holdNextFind(): (() => void) & { reached: Promise } { let release!: () => void; hold = new Promise((resolve) => { release = resolve; }); - return release; + const reached = new Promise((resolve) => { heldReached = resolve; }); + return Object.assign(release, { reached }); }, }; } @@ -997,7 +1007,7 @@ describe('KnowledgeService — a complete reindex skips unchanged documents and const r001 = h.rows.splice(h.rows.findIndex((r) => r.id === 'r001'), 1)[0]; const release = h.holdNextFind(); const walk = h.svc.reindexSource('s1'); - await new Promise((r) => setTimeout(r, 5)); + await release.reached; h.rows.push(r001); await h.svc.handleRecordUpsert('task', { id: 'r001' }); // A row created during the walk: its document was never listed. @@ -1127,7 +1137,10 @@ describe('KnowledgeService — the purge never deletes on an answer it cannot re // The row is restored and its event sync fires while the purge is held. h.rows.push(r001); const sync = h.svc.handleRecordUpsert('task', { id: 'r001' }); - await new Promise((r) => setTimeout(r, 5)); + // Let every promise that can run, run (one macrotask turn — no clock: the + // paths under test await only promises). Off the chain the sync finishes + // here, before the purge's delete; on it, the sync is still queued. + await new Promise((resolve) => setImmediate(resolve)); release(); await Promise.all([walk, sync]); // On the chain, the sync re-reads after the purge's delete and writes the @@ -1135,25 +1148,43 @@ describe('KnowledgeService — the purge never deletes on an answer it cannot re expect(la.stored.has('s1:r001')).toBe(true); }); - it('a numeric record id restored during the walk is found by its number and kept; a gone one is purged', async () => { + it('the purge re-reads by the id text only: a numeric id restored mid-walk is not found (the stated limit)', async () => { + // The engine double compares with `!==`, as driver-mongodb and driver-memory + // do: a row stored under the number 2 is not found by `{ id: '2' }`. The + // purge does not ask again by the number (on driver-sql that number is + // bound against a text column), so this pins the limit the docs state. const la = listingAdapter(); const rows = taskRows(5).map((r) => ({ ...r, id: Number(String(r.id).slice(1)) + 1 })); const h = reindexHarness(rows, objectSource('s1', 'task'), la.adapter); await h.svc.reindexSource('s1'); - // Row 2 is gone when the walk reads and back before the purge; row 4 is gone for good. const row2 = h.rows.splice(h.rows.findIndex((r) => r.id === 2), 1)[0]; h.rows.splice(h.rows.findIndex((r) => r.id === 4), 1); const release = h.holdNextFind(); const walk = h.svc.reindexSource('s1'); - await new Promise((r) => setTimeout(r, 5)); + await release.reached; h.rows.push(row2); release(); const res = await walk; - expect(res).toMatchObject({ ok: true, purged: 1 }); - expect(deletedOf(la.deleteSpy)).toEqual(['s1:4']); - expect(la.stored.has('s1:2')).toBe(true); - // The text form is asked first, then the number the text spells. + expect(res).toMatchObject({ ok: true, purged: 2 }); + expect(deletedOf(la.deleteSpy).sort()).toEqual(['s1:2', 's1:4']); const rereads = h.find.mock.calls.filter((c) => c[1].limit === 1).map((c) => c[1].where); - expect(rereads).toEqual(expect.arrayContaining([{ id: '2' }, { id: 2 }, { id: '4' }, { id: 4 }])); + expect(rereads).toEqual([{ id: '2' }, { id: '4' }]); + }); +}); + +describe('KnowledgeService — the event sync on an unreadable re-read', () => { + it('a re-read that answers no list leaves the document and warns once; it does not delete', async () => { + const warn = vi.fn(); + const adapter = makeAdapter('memory'); + const find = vi.fn(async () => undefined as never); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine, logger: { warn } }); + svc.registerAdapter('memory', adapter); + svc.registerSource(objectSource('s1', 'task')); + await expect(svc.handleRecordUpsert('task', { id: 'r1', title: 'T', notes: 'N' })).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledTimes(1); + expect(adapter.deleteSpy).not.toHaveBeenCalled(); + expect(adapter.upsertSpy).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toMatch(/event-sync failed for source 's1': the re-read of record 'r1' answered undefined instead of a list of rows/); }); }); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 40ce168b4df..bd3540564c7 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -1063,13 +1063,22 @@ export interface PurgeDocumentsOutcome { * gone. Each candidate is confirmed by {@link rereadRow} — the event sync's * own re-read, `where` AND id under the system context — and deleted only * when that finds no row, so a document whose row was created, restored or - * came back into `where` since the candidates were computed is kept. The - * record id is recovered from the document id as text; when that text is a - * canonical safe integer and the first re-read finds nothing, the row is asked - * for again by the number, so a caller-supplied numeric id on a driver that - * does not equate `'5'` with `5` is still found. Stops at the first re-read or - * delete that throws (a re-read that answers no list included), counting what - * it did before. + * came back into `where` since the candidates were computed is kept. Stops at + * the first re-read or delete that throws (a re-read that answers no list + * included), counting what it did before. + * + * KNOWN LIMIT — numeric record ids. The record id is recovered from the + * document id as text, and the re-read asks for that text. A driver that does + * not equate `'5'` with `5` (driver-mongodb, driver-memory) does not find a + * row stored under a caller-supplied NUMERIC id, so if such a row's document + * is a candidate while the row exists (it was restored, or came back into + * `where`, after the walk read past it), the document is deleted. The row is + * untouched; its document returns at the row's next event or the next complete + * reindex. Asking again by the number is not done: on driver-sql the number + * is bound against the text `id` column, which MySQL compares numerically + * (`'05'` matches `5`) and SQL Server and Oracle reject outright, and the + * object schema does not say which ids are numeric. Platform-minted ids are + * text on every driver, so the limit needs a caller-supplied numeric id. * * The caller decides when a purge may run at all (a complete reindex walk; * the scheduled reconcile reuses this function) and computes the candidates. @@ -1087,12 +1096,6 @@ export async function purgeDocuments(input: PurgeDocumentsInput): Promise { if (await rereadRow(engine, objSource, recordId)) return false; - // The document id carries the record id as text. A row whose id is the - // number that text spells (a caller-supplied numeric id, on a driver - // that does not equate '5' with 5) is asked for again by the number, - // so the purge and the event sync give one answer for one row. - const asNumber = canonicalSafeInteger(recordId); - if (asNumber !== undefined && (await rereadRow(engine, objSource, asNumber))) return false; await adapter.delete([documentId], { source, reason: input.reason ?? 'reindex' }); return true; }); @@ -1143,13 +1146,6 @@ function describeValue(value: unknown): string { return value === null ? 'null' : value === undefined ? 'undefined' : `a value of type ${typeof value}`; } -/** The number a record id's text spells, when it is a canonical safe integer (`'5'`, `'-12'`; never `'05'` or `'-0'`). */ -function canonicalSafeInteger(text: string): number | undefined { - if (!/^(0|-?[1-9][0-9]*)$/.test(text)) return undefined; - const n = Number(text); - return Number.isSafeInteger(n) ? n : undefined; -} - /** A thrown value's text: an `Error`'s message, anything else as a string. */ function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); From 8ba26077dea4ad94150c04d21ccf32190ee001dc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 05:31:16 +0000 Subject: [PATCH 13/13] chore(spec): regenerate authorable-surface/ai.json on the merged tree The os-regen driver kept the branch's side of the shard in the merge commit and step 2 took main's; gen:schema on the merged HEAD yields both: main's 56 entries (#37173) and this branch's ai/KnowledgeDocument:docHash. Claude-Session: https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E Co-authored-by: Claude --- packages/spec/authorable-surface/ai.json | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index f653ed222d0..29dda225bd9 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -36,6 +36,23 @@ "ai/Agent:skills", "ai/Agent:structuredOutput", "ai/Agent:surface", + "ai/AiContext:_lock", + "ai/AiContext:_lockDocsUrl", + "ai/AiContext:_lockReason", + "ai/AiContext:_lockSource", + "ai/AiContext:_packageId", + "ai/AiContext:_packageVersion", + "ai/AiContext:_provenance", + "ai/AiContext:body", + "ai/AiContext:fields", + "ai/AiContext:label", + "ai/AiContext:name", + "ai/AiContext:object", + "ai/AiContext:related", + "ai/AiContextBody:field", + "ai/AiContextRelated:field", + "ai/AiContextRelated:fields", + "ai/AiContextRelated:object", "ai/BlueprintApp:icon", "ai/BlueprintApp:label", "ai/BlueprintApp:name", @@ -209,6 +226,13 @@ "ai/FunctionCall:arguments", "ai/FunctionCall:name", "ai/FunctionCall:result", + "ai/GetRecordContextInput:anchor", + "ai/GetRecordContextInput:context", + "ai/GetRecordContextInput:objectName", + "ai/GetRecordContextInput:recordId", + "ai/GetRecordContextOutput:data", + "ai/GetRecordContextOutput:framing", + "ai/GetRecordContextOutput:notes", "ai/HttpKnowledgeSource:kind", "ai/HttpKnowledgeSource:urls", "ai/HttpKnowledgeSource:userAgent", @@ -380,6 +404,38 @@ "ai/QueryDatasetOutput:totals", "ai/QueryDatasetOutput:truncated", "ai/QueryDatasetOutput:warning", + "ai/RecordContextBody:anchor", + "ai/RecordContextBody:field", + "ai/RecordContextBody:label", + "ai/RecordContextBody:outline", + "ai/RecordContextBody:text", + "ai/RecordContextBody:truncated", + "ai/RecordContextData:body", + "ai/RecordContextData:fields", + "ai/RecordContextData:pack", + "ai/RecordContextData:record", + "ai/RecordContextData:related", + "ai/RecordContextFieldEntry:display", + "ai/RecordContextFieldEntry:label", + "ai/RecordContextFieldEntry:name", + "ai/RecordContextFieldEntry:notVisible", + "ai/RecordContextFieldEntry:value", + "ai/RecordContextFieldEntry:withheld", + "ai/RecordContextNote:fields", + "ai/RecordContextNote:kind", + "ai/RecordContextNote:object", + "ai/RecordContextNote:text", + "ai/RecordContextOutlineEntry:anchor", + "ai/RecordContextOutlineEntry:heading", + "ai/RecordContextOutlineEntry:level", + "ai/RecordContextRelatedList:field", + "ai/RecordContextRelatedList:label", + "ai/RecordContextRelatedList:object", + "ai/RecordContextRelatedList:rows", + "ai/RecordContextRelatedList:truncated", + "ai/RecordContextRelatedRow:displayName", + "ai/RecordContextRelatedRow:fields", + "ai/RecordContextRelatedRow:id", "ai/Skill:_lock", "ai/Skill:_lockDocsUrl", "ai/Skill:_lockReason",