From d687db52be048b348a1331314144d61270ac3b01 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 17:51:13 +0000 Subject: [PATCH 01/11] wip(knowledge): index fingerprint, build calls, coded search refusals --- .../services/service-knowledge/src/index.ts | 13 + .../src/knowledge-index-fingerprint.ts | 164 +++++++++ .../src/knowledge-service.ts | 335 +++++++++++++++--- .../service-knowledge/src/knowledge-tools.ts | 52 ++- .../service-knowledge/src/split/index.ts | 1 + .../service-knowledge/src/split/splitter.ts | 10 + packages/spec/src/contracts/embedder.ts | 10 + .../spec/src/contracts/knowledge-adapter.ts | 105 ++++++ 8 files changed, 641 insertions(+), 49 deletions(-) create mode 100644 packages/services/service-knowledge/src/knowledge-index-fingerprint.ts diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 50a34e75c75..ff73df5e23d 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -3,8 +3,20 @@ export { KnowledgeService, documentIdFor, recordToDocument } from './knowledge-service.js'; export type { KnowledgeLogger, + KnowledgeSearchRefusal, + KnowledgeSearchReport, KnowledgeServiceOptions, } from './knowledge-service.js'; +export { + ASSEMBLY_RULE_VERSION, + INDEX_FINGERPRINT_VERSION, + RECIPE_HASH_VERSION, + TITLE_RULE_VERSION, + computeIndexFingerprint, + computeRecipeHash, +} from './knowledge-index-fingerprint.js'; +export type { IndexFingerprintInput, RecipeHashInput } from './knowledge-index-fingerprint.js'; +export { SPLIT_ALGORITHM_VERSION } from './split/index.js'; export { SEARCH_KNOWLEDGE_DEFAULT_TOP_K, SEARCH_KNOWLEDGE_MAX_TOP_K, @@ -17,6 +29,7 @@ export type { SearchKnowledgeHit, SearchKnowledgeInput, SearchKnowledgeOutput, + SearchKnowledgeRefusedSource, SearchKnowledgeSourceSummary, } from './knowledge-tools.js'; export type { KnowledgeFieldSecurity } from './knowledge-source-admission.js'; diff --git a/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts b/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts new file mode 100644 index 00000000000..b4c9546cd25 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-index-fingerprint.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The index fingerprint and the recipe hash (ADR-0161 K7; K8, item 8): the + * two hashes the knowledge service computes, each in ONE function here, and + * hands to the adapter on every call (`AdapterContext.index`, + * `AdapterSearchOptions.index`). + * + * ## The fingerprint — may yesterday's vector be ranked against today's? + * + * Five components (K7): + * + * | Component | Read from | + * |:--|:--| + * | embedding model (with `variant`, an adapter option that changes stored vectors) | the adapter's `embedding` descriptor: what it reports for the embedder it calls | + * | dimensions | the same descriptor | + * | split configuration | the RESOLVED split (`strategy`, `maxChars`, `minChars`, the token budget) — the split that is applied, not the one that is written; absent for an adapter that does not take chunks, which splits for itself | + * | split algorithm version | {@link SPLIT_ALGORITHM_VERSION}, the splitter's constant | + * | content recipe | the source kind, the object, the ordered `content` list, and {@link ASSEMBLY_RULE_VERSION} | + * + * Model and dimensions are always what the adapter reports, never what the + * deployment's settings say around it (K7, "Whose embedder"). An adapter that + * reports no descriptor gives the fingerprint no model and no dimensions, so a + * change of either cannot be seen for it (K7, rule 8). + * + * ## The recipe hash — what assembly reads that the fingerprint leaves out + * + * The source's `where`, its `metadataFields`, the title rule (the field the + * title is read from, as it resolves now, and {@link TITLE_RULE_VERSION}), and + * the fields an index may not carry as they resolve now (credential-class and + * `internal`). None of them changes a vector, so a change is repaired by a + * complete rebuild inside the same generation, not by a new one (K7, point 2). + * + * ## Over values, in a fixed order, pinned by a test (K7, rules 6 and 7) + * + * Both hashes are SHA-256 over a JSON body whose object keys are sorted, so + * the same source and the same adapter give the same hash on every machine. + * They hash values, never key spellings: a key rename changes neither. Both + * are derived; no key on a source sets them. Pinned by + * `__tests__/index-fingerprint.test.ts`, which holds the hash of a fixed input. + */ + +import { createHash } from 'node:crypto'; +import type { AdapterIndexExpectation, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { collectCredentialWriteResponseFields, collectInternalWriteResponseFields } from '@objectstack/core'; +import { SPLIT_ALGORITHM_VERSION, type ResolvedSplit } from './split/index.js'; +import { documentTitleField } from './knowledge-source-admission.js'; + +/** The fingerprint's prefix; bump it when what the fingerprint covers or how it serializes changes. */ +export const INDEX_FINGERPRINT_VERSION = 'fp1'; + +/** The recipe hash's prefix; bump it when what the recipe hash covers or how it serializes changes. */ +export const RECIPE_HASH_VERSION = 'rh1'; + +/** + * The version of the assembly rule — how the listed content values become one + * text (`recordToDocument`: each listed field's value, `'*'` as every string + * field, joined by a blank line). Part of the content recipe. Bump it in the + * change that makes assembly give another text for the same record and source. + */ +export const ASSEMBLY_RULE_VERSION = 1; + +/** + * The version of the title rule — how a document's title is read from its + * record (`documentTitle`). Part of the recipe hash. Bump it in the change + * that makes the same record give another title. + */ +export const TITLE_RULE_VERSION = 1; + +/** What {@link computeIndexFingerprint} reads. */ +export interface IndexFingerprintInput { + source: KnowledgeSource; + /** The adapter's `embedding` descriptor, read now. */ + embedding: IKnowledgeAdapter['embedding']; + /** The split the service applies for this adapter; absent when the adapter does not take chunks. */ + split?: ResolvedSplit; +} + +/** What {@link computeRecipeHash} reads. */ +export interface RecipeHashInput { + source: KnowledgeSource; + /** The registered object definition of an object source, when the engine exposes one. */ + schema?: unknown; +} + +/** The index fingerprint of a source under an adapter (ADR-0161 K7). */ +export function computeIndexFingerprint(input: IndexFingerprintInput): string { + const embedding = input.embedding; + const split = input.split; + return hashed(INDEX_FINGERPRINT_VERSION, { + model: embedding?.model ?? null, + variant: embedding?.variant ?? null, + dimensions: embedding?.dimensions ?? null, + split: split === undefined + ? null + : { + strategy: split.strategy, + maxChars: split.maxChars, + minChars: split.minChars, + maxTokens: split.maxTokens ?? null, + }, + splitAlgorithm: split === undefined ? null : SPLIT_ALGORITHM_VERSION, + recipe: contentRecipe(input.source), + }); +} + +/** The recipe hash of a source (ADR-0161 K7, "The recipe hash"). */ +export function computeRecipeHash(input: RecipeHashInput): string { + const { source, schema } = input; + if (source.source.kind !== 'object') { + return hashed(RECIPE_HASH_VERSION, { kind: source.source.kind }); + } + const objSource = source.source as ObjectKnowledgeSource; + const withheld = [...new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ])].sort(); + return hashed(RECIPE_HASH_VERSION, { + where: objSource.where ?? null, + metadataFields: objSource.metadataFields ?? [], + title: { field: documentTitleField(schema) ?? null, rule: TITLE_RULE_VERSION }, + withheld, + }); +} + +/** Both hashes, as the adapter is handed them. */ +export function indexExpectation(fingerprint: IndexFingerprintInput, recipe: RecipeHashInput): AdapterIndexExpectation { + return { fingerprint: computeIndexFingerprint(fingerprint), recipeHash: computeRecipeHash(recipe) }; +} + +/** + * The content recipe (K7, point 2): what assembly reads to build the text. + * For an object source, the object and the ORDERED content list — the order is + * the order of the text. Another kind is not assembled by the service; its + * recipe is its kind. + */ +function contentRecipe(source: KnowledgeSource): Record { + if (source.source.kind !== 'object') return { kind: source.source.kind }; + const objSource = source.source as ObjectKnowledgeSource; + return { + kind: 'object', + object: objSource.object, + content: [...objSource.contentFields], + assembly: ASSEMBLY_RULE_VERSION, + }; +} + +function hashed(prefix: string, body: unknown): string { + return `${prefix}:${createHash('sha256').update(stableJson(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; + }); +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 5047b3dbf59..974b019f182 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -2,6 +2,8 @@ import { createHash } from 'node:crypto'; import type { + AdapterContext, + AdapterIndexExpectation, IDataEngine, IKnowledgeAdapter, IKnowledgeService, @@ -23,7 +25,8 @@ import { } from '@objectstack/core'; import type { TenancyPosture } from '@objectstack/spec/security'; import { createKnowledgeTools, type KnowledgeTools } from './knowledge-tools.js'; -import { resolveSplit, splitDocument } from './split/index.js'; +import { resolveSplit, splitDocument, type ResolvedSplit } from './split/index.js'; +import { indexExpectation } from './knowledge-index-fingerprint.js'; import { documentOrganizationId, searchOrganizationIds, @@ -224,15 +227,49 @@ export class KnowledgeService implements IKnowledgeService { "splitter from the content, by the source's split; omit them.", ); } - const prepared = await this.prepareDocuments(source, adapter, [{ ...doc, docHash: computeDocHash(doc) }]); + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('manual'); + const prepared = this.prepareDocuments(plan, [{ ...doc, docHash: computeDocHash(doc) }]); if (prepared.failed.length > 0) { const failure = prepared.failed[0]; - await adapter.delete([doc.id], { source, reason: 'manual' }); + await adapter.delete([doc.id], ctx); throw new Error( `[knowledge] indexDocument did not index document '${doc.id}' and removed it from the index: ${failure.reason}`, ); } - await adapter.upsert(prepared.ready, { source, reason: 'manual' }); + await adapter.upsert(prepared.ready, ctx); + } + + /** + * What every adapter call for `source` carries, read now (ADR-0161 K7; K8, + * item 8): the split the service applies for this adapter — resolved from + * the source's `split`, the settings page's `knowledge.chunk_target` and the + * adapter's reported `embedding.maxInputTokens`, absent for an adapter that + * does not take chunks — and the index fingerprint and recipe hash computed + * over that same split, the adapter's descriptor and the source. One read + * feeds both, so the fingerprint is always the fingerprint of the split the + * documents were cut by. Never cached: the settings, the descriptor and the + * object definition may each change between two calls. + */ + private async planIndex(source: KnowledgeSource, adapter: IKnowledgeAdapter): Promise { + const split = adapter.capabilities?.chunks === true + ? resolveSplit({ + split: source.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).split : undefined, + chunkTarget: await this.readChunkTarget(), + maxInputTokens: adapter.embedding?.maxInputTokens, + }) + : undefined; + const index = indexExpectation( + { source, embedding: adapter.embedding, ...(split === undefined ? {} : { split }) }, + { source, schema: source.source.kind === 'object' ? this.schemaFor((source.source as ObjectKnowledgeSource).object) : undefined }, + ); + return { + source, + adapter, + ...(split === undefined ? {} : { split }), + index, + context: (reason) => ({ source, reason, index }), + }; } /** @@ -240,27 +277,22 @@ export class KnowledgeService implements IKnowledgeService { * K1). An adapter that does not declare `capabilities.chunks` gets the * documents as they are, without `chunks` — it splits them itself, as * before. One that does gets each document with the passages of - * {@link splitDocument}, under the source's `split` (an object source's - * key; any other source splits `recursive`), the settings page's - * `knowledge.chunk_target`, and the adapter's reported - * `embedding.maxInputTokens` — both read now, for this batch, never cached. - * A document the split cannot index (a `whole` document over the budget) - * is answered in `failed`, never truncated; the caller removes it. + * {@link splitDocument}, under the split {@link planIndex} resolved for + * this call: the source's `split` (an object source's key; any other source + * splits `recursive`), the settings page's `knowledge.chunk_target`, and the + * adapter's reported `embedding.maxInputTokens` — read for this call, never + * cached. A document the split cannot index (a `whole` document over the + * budget) is answered in `failed`, never truncated; the caller removes it. */ - private async prepareDocuments( - source: KnowledgeSource, - adapter: IKnowledgeAdapter, + private prepareDocuments( + plan: IndexPlan, docs: KnowledgeDocument[], - ): Promise<{ + ): { ready: KnowledgeDocument[]; failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }>; - }> { - if (adapter.capabilities?.chunks !== true || docs.length === 0) return { ready: docs, failed: [] }; - const split = resolveSplit({ - split: source.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).split : undefined, - chunkTarget: await this.readChunkTarget(), - maxInputTokens: adapter.embedding?.maxInputTokens, - }); + } { + const split = plan.split; + if (split === undefined || docs.length === 0) return { ready: docs, failed: [] }; const ready: KnowledgeDocument[] = []; const failed: Array<{ documentId: string; reason: string; estimate: number; budget: number }> = []; for (const doc of docs) { @@ -289,7 +321,7 @@ export class KnowledgeService implements IKnowledgeService { async deleteDocument(sourceId: string, documentId: string): Promise { const source = this.requireSource(sourceId); const adapter = this.getAdapter(source.adapter); - await adapter.delete([documentId], { source, reason: 'manual' }); + await adapter.delete([documentId], (await this.planIndex(source, adapter)).context('manual')); } // ── Reindex ─────────────────────────────────────────────────────── @@ -357,6 +389,19 @@ export class KnowledgeService implements IKnowledgeService { * 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. + * + * ## The build (ADR-0161 K7, rule 3; K8, item 8) + * + * Every adapter call of the walk carries the index fingerprint and recipe + * hash ({@link planIndex}), computed once per walk. A COMPLETE walk is a + * build: before it the service calls the adapter's `beginBuild`, and after + * the walk and its purge it calls `completeBuild` once, so the adapter + * records what it now holds. A walk with a `limit` or a `dryRun` is not a + * build and makes neither call. `beginBuild` refusing stops the walk before + * any write (`ok: false`, its message carried). A walk that fails, a purge + * that stops, or a listing that failed (the purge could not run, so stale + * documents may remain) is not completed: the adapter keeps what it held, + * and the next complete walk builds again. */ async reindexSource( sourceId: string, @@ -463,9 +508,35 @@ export class KnowledgeService implements IKnowledgeService { }; } + // One plan for the whole walk: the split every page is cut by, and the + // fingerprint and recipe hash every adapter call carries. + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('reindex'); + + // A complete walk is a build (K7, rule 3): the adapter is told before the + // first write, and may open a generation for a new fingerprint — or refuse. + const build = cap === undefined; + if (build && typeof adapter.beginBuild === 'function') { + try { + await adapter.beginBuild(ctx); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${source.id}' refused: the adapter did not begin the build (${errorText(err)}); nothing was written.`, + }; + } + } + // 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 listing = await listAdapterDocuments(source, adapter, plan.index); const listed = listing.ok ? listing.documents : undefined; const listingNote = listing.ok || listing.reason === undefined ? undefined @@ -543,10 +614,10 @@ export class KnowledgeService implements IKnowledgeService { return stored === undefined || stored !== doc.docHash; }); // One split per changed document, for an adapter that takes chunks. - const prepared = await this.prepareDocuments(source, adapter, changed); + const prepared = this.prepareDocuments(plan, changed); if (prepared.ready.length > 0) { try { - await adapter.upsert(prepared.ready, { source, reason: 'reindex' }); + await adapter.upsert(prepared.ready, ctx); } catch (err) { return stopped(`the adapter upsert failed: ${errorText(err)}`); } @@ -556,7 +627,7 @@ export class KnowledgeService implements IKnowledgeService { // reported, never truncated. if (prepared.failed.length > 0) { try { - await adapter.delete(prepared.failed.map((f) => f.documentId), { source, reason: 'reindex' }); + await adapter.delete(prepared.failed.map((f) => f.documentId), ctx); } catch (err) { return stopped(`removing the page's documents that cannot be indexed failed: ${errorText(err)}`); } @@ -602,7 +673,9 @@ export class KnowledgeService implements IKnowledgeService { ...(failedNote === undefined ? {} : { message: failedNote }), }; if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; - if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) return done; + if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { + return build ? this.completeBuild(source, adapter, ctx, done) : done; + } const candidates = [...listed.keys()].filter((id) => !seen.has(id)); const purge = await purgeDocuments({ @@ -612,6 +685,7 @@ export class KnowledgeService implements IKnowledgeService { engine, candidates, serialize: (documentId, task) => chainAfter(this.recordSyncTails, documentId, task), + index: plan.index, }); if (purge.failure !== undefined) { return { @@ -624,16 +698,44 @@ export class KnowledgeService implements IKnowledgeService { }; } if (purge.foreign > 0) { - return { + return this.completeBuild(source, adapter, ctx, { ...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.` + (failedNote === undefined ? '' : ` ${failedNote}`), + }); + } + return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }); + } + + /** + * The end of a complete build (ADR-0161 K8, item 8 c): the adapter's + * `completeBuild`, once, with the fingerprint and recipe hash the walk + * carried. An adapter without it records nothing. One that throws turns the + * walk's result into `ok: false`: every page was written, but the adapter + * did not record what it holds, so the next complete walk builds again. + */ + private async completeBuild( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + ctx: AdapterContext, + done: KnowledgeReindexResult, + ): Promise { + if (typeof adapter.completeBuild !== 'function') return done; + try { + await adapter.completeBuild(ctx); + return done; + } catch (err) { + return { + ...done, + ok: false, + message: + `reindex of source '${source.id}' walked every page, but the adapter did not complete the build ` + + `(${errorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, }; } - return { ...done, purged: purge.purged }; } // ── The `search_knowledge` AI tool (ADR-0149 D2) ────────────────── @@ -681,17 +783,52 @@ export class KnowledgeService implements IKnowledgeService { * The answer is at most `topK` hits (`KnowledgeSearchOptions.topK`), chunk- * level as before. How many hits the re-check removed is logged at `debug`, * never returned: the count is an oracle on rows the caller may not read. + * + * ## A refused source is never an empty answer (ADR-0161 K7, rule 5) + * + * Each source is searched under the fingerprint the service expects of its + * index ({@link planIndex}). An adapter whose index holds another — the + * source needs a rebuild, or is being rebuilt — refuses with an ADR-0112 + * coded error, and so may any adapter for a reason it codes. A coded refusal + * is not logged and dropped like a failure: the sources that can be searched + * answer, and when NONE can, the call is refused whole — this method throws + * a coded error naming each refused source with its code. When some answer, + * the hits are theirs and the refused sources are logged at `warn`; the + * return type of `IKnowledgeService.search` has no place to name them, so a + * caller that must name them to its own caller (the `search_knowledge` tool) + * reads {@link searchWithRefusals}. */ async search(query: string, opts: KnowledgeSearchOptions = {}): Promise { + const report = await this.searchWithRefusals(query, opts); + if (report.refused.length > 0) { + this.options.logger?.warn?.( + `[knowledge] ${report.refused.length} source(s) refused this search and were not searched: ` + + report.refused.map((r) => `'${r.sourceId}' (${r.code}: ${r.message})`).join('; '), + ); + } + return report.hits; + } + + /** + * {@link search}, answering the refused sources beside the hits: each + * source whose adapter refused with an ADR-0112 coded error, with its code. + * Throws a coded error when no source could be searched and at least one + * refused (the call refused whole, ADR-0161 K7, rule 5); the thrown error's + * `refused` lists them all. + */ + async searchWithRefusals(query: string, opts: KnowledgeSearchOptions = {}): Promise { const topK = opts.topK ?? this.defaultTopK; const ctx = opts.executionContext; - const sources = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); - if (sources.length === 0) return []; + const admitted = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); + if (admitted.length === 0) return { hits: [], refused: [] }; + const sources = await this.planSearches(admitted); const filtered = ctx !== undefined && ctx.isSystem !== true && this.options.dataEngine !== undefined; const firstAsk = (source: KnowledgeSource): number => filtered && source.source.kind === 'object' ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; - const first = await this.searchRound(query, sources, firstAsk, opts.filter); + const refused: KnowledgeSearchRefusal[] = []; + const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); + if (first.size === 0 && refused.length > 0) throw wholeRefusal(refused); const raw = [...first.values()].flatMap((answer) => answer.hits); let kept = await this.applyPermissionFilter(raw, ctx); let removed = raw.length - kept.length; @@ -702,7 +839,7 @@ export class KnowledgeService implements IKnowledgeService { return source.source.kind === 'object' && answer !== undefined && answer.answered >= firstAsk(source); }); if (saturated.length > 0) { - const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter); + const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); // A refilled source's second answer is a superset of its first: its // first-round survivors are dropped and the whole answer re-checked. const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); @@ -721,7 +858,28 @@ export class KnowledgeService implements IKnowledgeService { ); } kept.sort((a, b) => b.score - a.score); - return kept.slice(0, topK); + return { hits: kept.slice(0, topK), refused }; + } + + /** + * Each admitted source paired with the fingerprint its search carries + * ({@link planIndex}); a source whose adapter is not registered carries none + * (the round skips it, as before). + */ + private async planSearches( + admitted: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, + ): Promise { + const out: SearchTarget[] = []; + for (const entry of admitted) { + const adapter = this.adapters.get(entry.source.adapter); + if (!adapter) { + out.push(entry); + continue; + } + const plan = await this.planIndex(entry.source, adapter); + out.push({ ...entry, fingerprint: plan.index.fingerprint }); + } + return out; } /** @@ -729,16 +887,19 @@ export class KnowledgeService implements IKnowledgeService { * hits. Answers, per source that answered, the hits it serves and how many * the adapter returned (`answered`, before a hit naming another source is * dropped — what decides whether the adapter may hold more). A source whose - * adapter is unknown or throws is absent from the answer, logged. + * adapter is unknown or throws is absent from the answer: a coded refusal + * (ADR-0112 `code` and `status`) is added to `refused`, anything else is + * logged. */ private async searchRound( query: string, - sources: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, + sources: SearchTarget[], ask: (source: KnowledgeSource) => number, filter: Record | undefined, + refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds } of sources) { + for (const { source, organizationIds, fingerprint } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { this.options.logger?.warn?.( @@ -752,6 +913,7 @@ export class KnowledgeService implements IKnowledgeService { topK: ask(source), filter, ...(organizationIds === undefined ? {} : { organizationIds }), + ...(fingerprint === undefined ? {} : { index: { fingerprint } }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store @@ -768,6 +930,11 @@ export class KnowledgeService implements IKnowledgeService { } out.set(source.id, { hits: served, answered: hits.length }); } catch (err) { + const coded = codedRefusalOf(err); + if (coded !== undefined) { + refused.push({ sourceId: source.id, ...coded }); + continue; + } this.options.logger?.error?.( `[knowledge] adapter '${source.adapter}' search failed for source '${source.id}': ${(err as Error).message}`, ); @@ -878,7 +1045,8 @@ export class KnowledgeService implements IKnowledgeService { const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); await this.writeSynced(source, adapter, doc, recordId); } else { - await adapter.delete([documentIdFor(source.id, String(recordId))], { source, reason: 'event-sync' }); + const plan = await this.planIndex(source, adapter); + await adapter.delete([documentIdFor(source.id, String(recordId))], plan.context('event-sync')); } } catch (err) { this.options.logger?.warn?.( @@ -901,10 +1069,12 @@ export class KnowledgeService implements IKnowledgeService { doc: KnowledgeDocument, recordId: unknown, ): Promise { - const prepared = await this.prepareDocuments(source, adapter, [doc]); - if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, { source, reason: 'event-sync' }); + const plan = await this.planIndex(source, adapter); + const ctx = plan.context('event-sync'); + const prepared = this.prepareDocuments(plan, [doc]); + if (prepared.ready.length > 0) await adapter.upsert(prepared.ready, ctx); for (const f of prepared.failed) { - await adapter.delete([f.documentId], { source, reason: 'event-sync' }); + await adapter.delete([f.documentId], ctx); const limit = adapter.embedding?.maxInputTokens; const message = `[knowledge] record '${String(recordId)}' of source '${source.id}' is no longer in the index and search ` + @@ -967,7 +1137,7 @@ export class KnowledgeService implements IKnowledgeService { await this.serializeRecordSync(docId, async () => { try { const adapter = this.getAdapter(source.adapter); - await adapter.delete([docId], { source, reason: 'event-sync' }); + await adapter.delete([docId], (await this.planIndex(source, adapter)).context('event-sync')); } catch (err) { this.options.logger?.warn?.( `[knowledge] event-sync delete failed for source '${source.id}': ${(err as Error).message}`, @@ -1228,6 +1398,71 @@ export class KnowledgeService implements IKnowledgeService { // ── Helpers ───────────────────────────────────────────────────────── +/** + * A source that refused a search (ADR-0161 K7, rule 5): its adapter answered + * an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds + * another fingerprint than the one the search carried. + */ +export interface KnowledgeSearchRefusal { + sourceId: string; + /** The adapter's error code. */ + code: string; + /** The adapter's HTTP-shaped status. */ + status: number; + /** The adapter's message, which says what to do. */ + message: string; +} + +/** What {@link KnowledgeService.searchWithRefusals} answers. */ +export interface KnowledgeSearchReport { + /** The hits of the sources that answered, as {@link KnowledgeService.search} returns them. */ + hits: KnowledgeHit[]; + /** The sources that refused, each with its code; empty when none did. */ + refused: KnowledgeSearchRefusal[]; +} + +/** One source a search round asks: its organizations scope and the fingerprint its search carries. */ +interface SearchTarget { + source: KnowledgeSource; + organizationIds?: string[]; + fingerprint?: string; +} + +/** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ +function codedRefusalOf(err: unknown): Omit | undefined { + if (err === null || typeof err !== 'object') return undefined; + const { code, status } = err as { code?: unknown; status?: unknown }; + if (typeof code !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(code)) return undefined; + if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599) return undefined; + return { code, status, message: errorText(err) }; +} + +/** + * The refusal of a search no source could answer (ADR-0161 K7, rule 5): the + * first refusal's code and status — the one every refusal shares, when they + * share one — and a message naming each refused source with its code. The + * thrown error carries `refused`. + */ +function wholeRefusal(refused: KnowledgeSearchRefusal[]): Error { + const [first] = refused; + const message = + `[knowledge] no source could be searched: ` + + refused.map((r) => `source '${r.sourceId}' refused (${r.code}): ${r.message}`).join('; '); + return Object.assign(new Error(message), { code: first.code, status: first.status, refused: [...refused] }); +} + +/** What {@link KnowledgeService.planIndex} resolves for one call against one source's adapter. */ +interface IndexPlan { + source: KnowledgeSource; + adapter: IKnowledgeAdapter; + /** The split applied for an adapter that takes chunks; absent for one that does not. */ + split?: ResolvedSplit; + /** The fingerprint and recipe hash every adapter call carries. */ + index: AdapterIndexExpectation; + /** The adapter context of a call made for `reason`, carrying `index`. */ + context(reason: NonNullable): AdapterContext; +} + /** * Rows one reindex page reads, and so the most documents one reindex `upsert` * carries. A memory and request-size bound for the walk, not an embedder @@ -1362,7 +1597,11 @@ type AdapterListing = * 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 { +async function listAdapterDocuments( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + index: AdapterIndexExpectation, +): Promise { if (typeof adapter.listDocuments !== 'function') return { ok: false }; const documents = new Map(); const cursors = new Set(); @@ -1370,7 +1609,7 @@ async function listAdapterDocuments(source: KnowledgeSource, adapter: IKnowledge try { for (;;) { const page = await adapter.listDocuments( - { source, reason: 'reindex' }, + { source, reason: 'reindex', index }, 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' }; @@ -1407,6 +1646,8 @@ export interface PurgeDocumentsInput { serialize: (documentId: string, task: () => Promise) => Promise; /** Diagnostics tag on the adapter's `delete`. @default 'reindex' */ reason?: string; + /** The fingerprint and recipe hash the adapter's `delete` carries (ADR-0161 K8, item 8 a). */ + index?: AdapterIndexExpectation; } /** Outcome of {@link purgeDocuments}. */ @@ -1459,7 +1700,11 @@ export async function purgeDocuments(input: PurgeDocumentsInput): Promise { if (await rereadRow(engine, objSource, recordId)) return false; - await adapter.delete([documentId], { source, reason: input.reason ?? 'reindex' }); + await adapter.delete([documentId], { + source, + reason: input.reason ?? 'reindex', + ...(input.index === undefined ? {} : { index: input.index }), + }); return true; }); if (deleted) outcome.purged++; diff --git a/packages/services/service-knowledge/src/knowledge-tools.ts b/packages/services/service-knowledge/src/knowledge-tools.ts index 3114dc6ab9a..cd3cc90a1c6 100644 --- a/packages/services/service-knowledge/src/knowledge-tools.ts +++ b/packages/services/service-knowledge/src/knowledge-tools.ts @@ -80,12 +80,32 @@ export interface SearchKnowledgeHit { record?: { object: string; id: string }; } +/** + * A source that could not be searched for this call (ADR-0161 K7, rule 5): + * its index needs a rebuild, or is being rebuilt, or its store refused for + * another coded reason. Its passages are missing from `hits` — not absent + * from the source. + */ +export interface SearchKnowledgeRefusedSource { + sourceId: string; + /** The refusal's ADR-0112 code, e.g. `KNOWLEDGE_REBUILD_REQUIRED`. */ + code: string; + /** What the store said. */ + message: string; +} + /** A `search_knowledge` answer. */ export interface SearchKnowledgeOutput { /** The passages, most relevant first, at most `topK`. */ hits: SearchKnowledgeHit[]; /** Every source this tool may search; `sourceIds` takes their `id`s. */ sources: SearchKnowledgeSourceSummary[]; + /** + * The searched sources that refused this call, each with its code; absent + * when none did. When every searched source refuses, the call itself is + * refused with the first refusal's code. + */ + refused?: SearchKnowledgeRefusedSource[]; } /** The executor {@link createKnowledgeTools} binds. */ @@ -111,7 +131,9 @@ const SEARCH_KNOWLEDGE_DESCRIPTION = + `${SEARCH_KNOWLEDGE_DEFAULT_TOP_K}, at most ${SEARCH_KNOWLEDGE_MAX_TOP_K}). Only passages the caller may read ` + 'are returned: a passage indexed from a record the caller cannot read is dropped; on an OAuth connection, the ' + 'person\'s own permissions decide, never more. No passage means nothing the caller may read matched: say so ' - + 'rather than answer from general knowledge.'; + + 'rather than answer from general knowledge. A source listed in `refused` could not be searched (its index is ' + + 'being rebuilt, for example): its passages are missing, not absent, so say that this source could not be ' + + 'searched rather than that it holds nothing.'; const SEARCH_KNOWLEDGE_PARAMETERS: Record = Object.freeze({ type: 'object', @@ -238,6 +260,18 @@ function hitOf(hit: KnowledgeHit, sources: ReadonlyMap) }; } +/** A knowledge service that also answers the sources that refused a search (`KnowledgeService.searchWithRefusals`). */ +interface RefusalReportingService { + searchWithRefusals( + query: string, + opts: Parameters[1], + ): Promise<{ hits: KnowledgeHit[]; refused: Array<{ sourceId: string; code: string; message: string }> }>; +} + +function hasRefusalReport(service: IKnowledgeService): service is IKnowledgeService & RefusalReportingService { + return typeof (service as Partial).searchWithRefusals === 'function'; +} + /** * Bind the `search_knowledge` executor to a knowledge service. The service is * read per call (`service` may be a getter), so the sources a call searches @@ -270,14 +304,24 @@ export function createKnowledgeTools(service: IKnowledgeService | (() => IKnowle if (targets.length === 0) return { hits: [], sources: summaries }; // [ADR-0090 D10] As the caller: the service re-checks every object-source // hit against this context's row-level security. - const hits = await knowledge.search(query, { + const searchOpts = { sourceIds: targets, topK: topK ?? SEARCH_KNOWLEDGE_DEFAULT_TOP_K, ...(context ? { executionContext: context } : {}), - }); + }; + // [ADR-0161 K7, rule 5] A refused source is named, never answered as + // empty: the knowledge service's report carries the refusals beside the + // hits; a service without it answers hits alone, as before. + const report = hasRefusalReport(knowledge) + ? await knowledge.searchWithRefusals(query, searchOpts) + : { hits: await knowledge.search(query, searchOpts), refused: [] }; + const refused = report.refused + .filter((r) => byId.has(r.sourceId)) + .map((r) => ({ sourceId: r.sourceId, code: r.code, message: r.message })); return { - hits: hits.filter((hit) => byId.has(hit.sourceId)).map((hit) => hitOf(hit, byId)), + hits: report.hits.filter((hit) => byId.has(hit.sourceId)).map((hit) => hitOf(hit, byId)), sources: summaries, + ...(refused.length > 0 ? { refused } : {}), }; }, }; diff --git a/packages/services/service-knowledge/src/split/index.ts b/packages/services/service-knowledge/src/split/index.ts index 15af641547a..904dc78ca07 100644 --- a/packages/services/service-knowledge/src/split/index.ts +++ b/packages/services/service-knowledge/src/split/index.ts @@ -3,6 +3,7 @@ export { DEFAULT_SPLIT_MAX_CHARS, DEFAULT_SPLIT_MIN_CHARS, + SPLIT_ALGORITHM_VERSION, SPLIT_TOKEN_BUDGET_SHARE, resolveSplit, splitDocument, diff --git a/packages/services/service-knowledge/src/split/splitter.ts b/packages/services/service-knowledge/src/split/splitter.ts index 97431e59e71..3ed71d7faa4 100644 --- a/packages/services/service-knowledge/src/split/splitter.ts +++ b/packages/services/service-knowledge/src/split/splitter.ts @@ -54,6 +54,16 @@ export const DEFAULT_SPLIT_MIN_CHARS = 200; /** The share of the embedder's input limit a passage may fill, by `estimateTokens`. */ export const SPLIT_TOKEN_BUDGET_SHARE = 0.8; +/** + * The version of this splitter's algorithm — one of the index fingerprint's + * components (ADR-0161 K7). Bump it in the change that makes the splitter + * give different passages for the same text and the same resolved split: + * every index built by an adapter that takes chunks then reads as built under + * another fingerprint, and is rebuilt as a new generation rather than mixing + * old passages with new ones. + */ +export const SPLIT_ALGORITHM_VERSION = 1; + /** The split a source resolves to: what {@link splitDocument} cuts by. */ export interface ResolvedSplit { strategy: KnowledgeSplitStrategy; diff --git a/packages/spec/src/contracts/embedder.ts b/packages/spec/src/contracts/embedder.ts index 0d3e9c7d308..42280431f96 100644 --- a/packages/spec/src/contracts/embedder.ts +++ b/packages/spec/src/contracts/embedder.ts @@ -31,6 +31,16 @@ export interface IEmbedder { * their fixed-width vector columns / index parameters. */ readonly dimensions: number; + /** + * The model's identity as the provider names it (e.g. + * `'text-embedding-3-small'`, `'bge-m3'`). A knowledge adapter reports it + * (`IKnowledgeAdapter.embedding.model`) to the knowledge service, whose + * index fingerprint reads it: vectors of two models are never ranked + * against each other (ADR-0161 K7; K8, item 7). `id` stays a label for + * logs. Absent: a change of model cannot be seen for the indexes built + * with this embedder. + */ + readonly model?: string; /** * Longest single input the model accepts, in tokens, as measured by the * shared `estimateTokens` (`@objectstack/spec/shared`). Absent when the diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 58fdd6683f9..229f916e26e 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -37,6 +37,53 @@ export interface AdapterContext { traceId?: string; /** Caller-supplied free-form diagnostics tag. */ reason?: 'event-sync' | 'reindex' | 'manual' | 'tool-call' | (string & {}); + /** + * What the knowledge service expects of the source's index (ADR-0161 K8, + * item 8 a), set by the service on every call it makes. Absent on a call + * that does not come through the service; an adapter then checks nothing + * against it. + */ + index?: AdapterIndexExpectation; +} + +/** + * The fingerprint and the recipe hash the knowledge service expects of a + * source's index (ADR-0161 K7; K8, item 8 a). Both are computed by the + * service, in one function each, over values: opaque to the adapter, which + * only compares and stores them. + */ +export interface AdapterIndexExpectation { + /** + * The index fingerprint: the embedding model (and any option of the adapter + * that changes the vectors it stores), the dimensions, the split + * configuration, the split algorithm version and the content recipe. Two + * vectors are comparable only under one fingerprint: a write or a search + * whose fingerprint differs from the active generation's is never served + * from it (K7, rules 1, 4 and 5). + */ + fingerprint: string; + /** + * The recipe hash: what assembly reads that the fingerprint leaves out — + * the source's `where`, its `metadataFields`, the title rule and the fields + * an index may not carry. A changed recipe hash is repaired by a complete + * rebuild inside the same generation; the adapter records it only at the + * end of a complete build (`completeBuild`). + */ + recipeHash: string; +} + +/** + * What an adapter holds for a source (ADR-0161 K8, item 8 b), as + * `indexStatus` answers it. Every member absent: the adapter holds nothing + * for the source. + */ +export interface AdapterIndexStatus { + /** The fingerprint of the active generation, when it has one. */ + fingerprint?: string; + /** The recipe hash recorded by the last complete build of the active generation. */ + recipeHash?: string; + /** `true` while a generation opened by `beginBuild` is under construction. */ + building?: boolean; } /** Options accepted by `IKnowledgeAdapter.search`. */ @@ -71,6 +118,14 @@ export interface AdapterSearchOptions { * re-read empties. */ organizationIds?: string[]; + /** + * What the knowledge service expects of the source's index (ADR-0161 K8, + * item 8 a): the fingerprint the query is embedded under. An adapter whose + * active generation holds another fingerprint refuses the search with the + * coded refusal `KNOWLEDGE_REBUILD_REQUIRED` (ADR-0161 K7, rule 5) and never + * answers it from that generation. Absent: no check. + */ + index?: { fingerprint: string }; /** Trace id for correlation. */ traceId?: string; } @@ -140,6 +195,25 @@ export interface AdapterEmbeddingDescriptor { * is checked. */ maxInputTokens?: number; + /** + * The identity of the model whose vectors the adapter stores, as the + * provider names it (`IEmbedder.model`). Read by the service's index + * fingerprint (ADR-0161 K7): a changed model is a new generation. Absent: + * a change of model cannot be seen for this adapter (K7, rule 8). + */ + model?: string; + /** + * The width of the vectors the adapter stores (`IEmbedder.dimensions`). + * Read by the index fingerprint, as `model` is. + */ + dimensions?: number; + /** + * An opaque string for an option of the adapter that changes the vectors it + * stores (a document-side prefix, a normalisation). Read by the index + * fingerprint, as `model` is. A query-side option (a query prefix) changes + * no stored vector and is not reported here. + */ + variant?: string; } /** @@ -191,6 +265,37 @@ export interface IKnowledgeAdapter { */ listDocuments?(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise; + /** + * What the adapter holds for `ctx.source` (ADR-0161 K8, item 8 b): the + * active generation's fingerprint, the recipe hash its last complete build + * recorded, and whether a build is under construction. Read by the service + * at boot and when a source's definition is reloaded, to decide whether + * the source is built, rebuilt inside its generation, or built anew + * (ADR-0161 K7, "What starts a rebuild"). + */ + indexStatus?(ctx: AdapterContext): Promise; + + /** + * The start of a complete build (ADR-0161 K8, item 8 c; K7, rule 3). The + * service calls it before a complete walk of `ctx.source`, never before a + * walk with a `limit` or a `dryRun`. When `ctx.index.fingerprint` is the + * active generation's (or the adapter holds nothing for the source), nothing + * opens and the walk rebuilds inside that generation; when it differs, the + * adapter opens a generation for it, or takes up the one it already has + * under construction for that fingerprint — or, when it cannot, refuses + * with a coded refusal and the walk does not run. The adapter keeps one + * builder per source. + */ + beginBuild?(ctx: AdapterContext): Promise; + + /** + * The end of a complete build (ADR-0161 K8, item 8 c). The service calls it + * once, after the walk and its purge, and never after a walk that failed. + * The adapter records `ctx.index` (fingerprint and recipe hash) as what it + * holds for the source, and makes a generation it built the active one. + */ + completeBuild?(ctx: AdapterContext): Promise; + /** * Optional liveness probe. When implemented, used by the service's * health endpoint and Studio "test connection" actions. From 45923c2b4e65bf2b74362f9a200b579f85c84400 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 17:59:40 +0000 Subject: [PATCH 02/11] wip(knowledge): memory reference generations, contract suite item-8 cases, tool names refused sources --- .../src/__tests__/contract.test.ts | 10 +- .../plugins/knowledge-memory/src/index.ts | 159 ++++++++++- .../src/__tests__/contract-stubs.test.ts | 20 +- .../src/__tests__/index-fingerprint.test.ts | 94 +++++++ .../src/__tests__/knowledge-tools.test.ts | 57 ++++ .../services/service-knowledge/src/testing.ts | 258 +++++++++++++++++- 6 files changed, 577 insertions(+), 21 deletions(-) create mode 100644 packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts diff --git a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts index a1ec02fb4e6..fd9217e64a7 100644 --- a/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-memory/src/__tests__/contract.test.ts @@ -10,5 +10,13 @@ import { KnowledgeMemoryAdapter } from '../index'; runKnowledgeAdapterContract({ name: 'knowledge-memory', makeAdapter: () => new KnowledgeMemoryAdapter('under_test'), - implements: { listDocuments: true, chunks: true, organizationIds: true }, + implements: { + listDocuments: true, + chunks: true, + organizationIds: true, + indexStatus: true, + builds: true, + refusesOtherFingerprint: true, + generations: true, + }, }); diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 2b793119f28..7b402d269ac 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -4,6 +4,7 @@ import type { IKnowledgeAdapter, IKnowledgeService, AdapterContext, + AdapterIndexStatus, AdapterListDocumentsOptions, AdapterListDocumentsPage, AdapterSearchOptions, @@ -40,35 +41,131 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; * that set — the filter runs before the scoring, so `topK` is filled from them * alone. An empty set ranks nothing; a document stored without an * organization is not ranked by a filtered search. + * + * The reference implementation of the index fingerprint's members (ADR-0161 + * K8, item 8; K7, rules 1 to 5). Per source it holds an ACTIVE generation and, + * while a build for another fingerprint runs, one generation UNDER + * CONSTRUCTION, each under one fingerprint: + * + * - A write (`upsert`, `listDocuments`) carrying `ctx.index` goes to the + * generation of that fingerprint — the active one, or the one under + * construction — and is refused `KNOWLEDGE_REBUILD_REQUIRED` when neither + * holds it: never written into a generation of another fingerprint. A + * source that holds nothing takes the first fingerprint it is handed as its + * active one (there is nothing to mix with). A call without `ctx.index` + * (not through the service) checks nothing and writes the active + * generation. A `delete` removes the document from every generation. + * - A search carrying `index` whose fingerprint is not the active + * generation's is refused `KNOWLEDGE_REBUILD_REQUIRED` ("needs a rebuild", + * or "is being rebuilt" while a build for that fingerprint runs) and never + * answered from the active generation. + * - `beginBuild` opens a generation for a new fingerprint, takes up the one + * already under construction for it, or opens nothing when the fingerprint + * is the active one. A build of another fingerprint left unfinished is + * dropped: a process holds one builder per source, and the knowledge + * service runs one walk of a source at a time. + * - `completeBuild` makes the generation it built the active one (the old one + * is dropped) and records the recipe hash; `indexStatus` answers both. + * + * It reports no `embedding` descriptor: its vectors are token counts, and its + * index does not outlive the process (K7, rule 8). */ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { readonly id: string; readonly capabilities = { chunks: true } as const; - /** source id → document id → the stored document. */ - private readonly store = new Map>(); + /** source id → its generations. */ + private readonly store = new Map(); constructor(id = 'memory') { this.id = id; } async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { - const byDoc = this.store.get(ctx.source.id) ?? new Map(); + const byDoc = this.writeTarget(ctx, true)!.docs; for (const doc of docs) byDoc.set(doc.id, { docHash: doc.docHash, chunks: embedPassages(doc) }); - this.store.set(ctx.source.id, byDoc); } async delete(documentIds: string[], ctx: AdapterContext): Promise { - const byDoc: Map | undefined = this.store.get(ctx.source.id); - if (!byDoc) return; - for (const id of documentIds) byDoc.delete(id); + const index = this.store.get(ctx.source.id); + for (const generation of [index?.active, index?.building]) { + if (!generation) continue; + for (const id of documentIds) generation.docs.delete(id); + } + } + + async indexStatus(ctx: AdapterContext): Promise { + const index = this.store.get(ctx.source.id); + const status: AdapterIndexStatus = {}; + if (index?.active?.fingerprint !== undefined) status.fingerprint = index.active.fingerprint; + if (index?.active?.recipeHash !== undefined) status.recipeHash = index.active.recipeHash; + if (index?.building !== undefined) status.building = true; + return status; + } + + async beginBuild(ctx: AdapterContext): Promise { + const fingerprint = requireIndex(ctx, 'beginBuild').fingerprint; + const index = this.sourceIndex(ctx.source.id); + if (index.active === undefined) { + index.active = { fingerprint, docs: new Map() }; + return; + } + if (index.active.fingerprint === fingerprint) return; + if (index.building?.fingerprint === fingerprint) return; + index.building = { fingerprint, docs: new Map() }; + } + + async completeBuild(ctx: AdapterContext): Promise { + const { fingerprint, recipeHash } = requireIndex(ctx, 'completeBuild'); + const index = this.sourceIndex(ctx.source.id); + if (index.building?.fingerprint === fingerprint) { + index.active = { ...index.building, recipeHash }; + index.building = undefined; + return; + } + if (index.active?.fingerprint === fingerprint) { + index.active.recipeHash = recipeHash; + return; + } + throw new Error( + `completeBuild: source '${ctx.source.id}' holds no generation for this fingerprint; call beginBuild first.`, + ); + } + + private sourceIndex(sourceId: string): SourceIndex { + let index = this.store.get(sourceId); + if (!index) { + index = {}; + this.store.set(sourceId, index); + } + return index; + } + + /** + * The generation a write carrying `ctx.index` goes to. A source that holds + * nothing gets an active generation under that fingerprint (`create`), or + * none (a listing of nothing). Refused when the fingerprint is neither the + * active generation's nor the one under construction. + */ + private writeTarget(ctx: AdapterContext, create: boolean): Generation | undefined { + const fingerprint = ctx.index?.fingerprint; + const index = this.sourceIndex(ctx.source.id); + if (index.active === undefined) { + if (!create) return undefined; + index.active = { fingerprint, docs: new Map() }; + return index.active; + } + if (fingerprint === undefined || index.active.fingerprint === fingerprint) return index.active; + if (index.building?.fingerprint === fingerprint) return index.building; + throw rebuildRequired(ctx.source.id, false); } 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)}`); } - // In id order, so a cursor stays valid across writes. - const byDoc = this.store.get(ctx.source.id) ?? new Map(); + // In id order, so a cursor stays valid across writes. The generation the + // writes go to (ADR-0161 K8, item 1). + const byDoc = this.writeTarget(ctx, false)?.docs ?? new Map(); const ids = [...byDoc.keys()] .filter((id) => opts.cursor === undefined || id > opts.cursor) .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); @@ -83,7 +180,14 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } async search(query: string, opts: AdapterSearchOptions): Promise { - const chunks = [...(this.store.get(opts.source.id)?.values() ?? [])].flatMap((d) => d.chunks); + const index = this.store.get(opts.source.id); + const active = index?.active; + // Vectors of two fingerprints are never ranked against each other + // (ADR-0161 K7, rule 5): refused, never answered from the other generation. + if (active !== undefined && opts.index !== undefined && active.fingerprint !== opts.index.fingerprint) { + throw rebuildRequired(opts.source.id, index?.building?.fingerprint === opts.index.fingerprint); + } + const chunks = [...(active?.docs.values() ?? [])].flatMap((d) => d.chunks); if (chunks.length === 0) return []; const qVec = embedTokens(tokenize(query)); const qNorm = vectorNorm(qVec); @@ -124,6 +228,41 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { } } +/** One source's generations (ADR-0161 K7, rule 1): the active one, and one under construction. */ +interface SourceIndex { + active?: Generation; + building?: Generation; +} + +/** One complete index of one source under one fingerprint. */ +interface Generation { + /** Absent for a generation written by calls that carried no `index`. */ + fingerprint?: string; + /** Recorded by `completeBuild`. */ + recipeHash?: string; + /** document id → the stored document. */ + docs: Map; +} + +/** The ADR-0112 code a refused write or search carries (ADR-0161 K7, rules 4 and 5). */ +export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; + +function rebuildRequired(sourceId: string, building: boolean): Error { + const message = building + ? `Knowledge source '${sourceId}' is being rebuilt under its new index fingerprint; it answers again when ` + + 'the rebuild completes.' + : `Knowledge source '${sourceId}' needs a rebuild: its index was built under another fingerprint (embedding ` + + 'model, dimensions, split or content recipe changed). Run a complete reindex of the source.'; + return Object.assign(new Error(message), { code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); +} + +function requireIndex(ctx: AdapterContext, member: string): NonNullable { + if (ctx.index === undefined) { + throw new Error(`${member}: the call carries no index fingerprint (ctx.index); it is made by the knowledge service.`); + } + return ctx.index; +} + interface StoredDocument { /** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */ docHash?: string; diff --git a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts index 18a37f87146..6282918f2ee 100644 --- a/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts +++ b/packages/services/service-knowledge/src/__tests__/contract-stubs.test.ts @@ -95,11 +95,27 @@ class StubAdapter implements IKnowledgeAdapter { runKnowledgeAdapterContract({ name: 'whole-stub (no capabilities)', makeAdapter: () => new StubAdapter(false), - implements: { listDocuments: false, chunks: false, organizationIds: false }, + implements: { + listDocuments: false, + chunks: false, + organizationIds: false, + indexStatus: false, + builds: false, + refusesOtherFingerprint: false, + generations: false, + }, }); runKnowledgeAdapterContract({ name: 'chunk-stub (capabilities.chunks)', makeAdapter: () => new StubAdapter(true), - implements: { listDocuments: false, chunks: true, organizationIds: false }, + implements: { + listDocuments: false, + chunks: true, + organizationIds: false, + indexStatus: false, + builds: false, + refusesOtherFingerprint: false, + generations: false, + }, }); diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts new file mode 100644 index 00000000000..34f1589684a --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -0,0 +1,94 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The index fingerprint and the recipe hash (ADR-0161 K7, rule 6): computed +// over values, in a fixed order, the same on every machine. The two hex +// digests below are the pin: a change to what either hash covers or how it +// serializes turns this file red, and then bumps INDEX_FINGERPRINT_VERSION or +// RECIPE_HASH_VERSION in the same change — every stored index then reads as +// built under another hash, never as matching one it was not built under. + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { + ASSEMBLY_RULE_VERSION, + INDEX_FINGERPRINT_VERSION, + RECIPE_HASH_VERSION, + computeIndexFingerprint, + computeRecipeHash, +} from '../knowledge-index-fingerprint.js'; +import { SPLIT_ALGORITHM_VERSION, resolveSplit } from '../split/index.js'; + +const source = (extra: Record = {}): KnowledgeSource => + ({ + id: 'kb_articles', + label: 'Articles', + adapter: 'pgvector', + source: { kind: 'object', object: 'article', contentFields: ['title', 'body'], metadataFields: ['status'], ...extra }, + }) as KnowledgeSource; + +const embedding = { model: 'text-embedding-3-large', dimensions: 3072, maxInputTokens: 8191 }; +const split = resolveSplit({ split: { strategy: 'markdown', maxChars: 600 }, maxInputTokens: 8191 }); + +describe('index fingerprint (ADR-0161 K7)', () => { + it('is pinned for a fixed input', () => { + expect([INDEX_FINGERPRINT_VERSION, SPLIT_ALGORITHM_VERSION, ASSEMBLY_RULE_VERSION]).toEqual(['fp1', 1, 1]); + expect(computeIndexFingerprint({ source: source(), embedding, split })).toBe( + computeIndexFingerprint({ source: source(), embedding: { ...embedding }, split: { ...split } }), + ); + expect(computeIndexFingerprint({ source: source(), embedding, split })).toMatchInlineSnapshot(`"fp1:1455ed0d278a0e58b26ccc2d423298c29d65162125032d76453847fbbc9b58ed"`); + }); + + it('changes with each of its five components', () => { + const base = computeIndexFingerprint({ source: source(), embedding, split }); + const variants = [ + computeIndexFingerprint({ source: source(), embedding: { ...embedding, model: 'bge-m3' }, split }), + computeIndexFingerprint({ source: source(), embedding: { ...embedding, variant: 'passage-prefix' }, split }), + computeIndexFingerprint({ source: source(), embedding: { ...embedding, dimensions: 1024 }, split }), + computeIndexFingerprint({ source: source(), embedding, split: { ...split, maxChars: 400 } }), + computeIndexFingerprint({ source: source(), embedding, split: { ...split, strategy: 'recursive' } }), + computeIndexFingerprint({ source: source(), embedding }), + computeIndexFingerprint({ source: source({ contentFields: ['body', 'title'] }), embedding, split }), + computeIndexFingerprint({ source: source({ object: 'faq' }), embedding, split }), + ]; + for (const v of variants) expect(v).not.toBe(base); + expect(new Set(variants).size).toBe(variants.length); + }); + + it('does not change with what only the recipe hash reads, nor with the maxInputTokens report itself', () => { + const base = computeIndexFingerprint({ source: source(), embedding, split }); + expect(computeIndexFingerprint({ source: source({ where: { status: 'published' }, metadataFields: [] }), embedding, split })).toBe(base); + // The limit reaches the fingerprint through the resolved split only. + expect(computeIndexFingerprint({ source: source(), embedding: { ...embedding, maxInputTokens: 1 }, split })).toBe(base); + }); +}); + +describe('recipe hash (ADR-0161 K7)', () => { + const schema = { + name: 'article', + fields: { + title: { type: 'text' }, + body: { type: 'textarea' }, + status: { type: 'select' }, + api_token: { type: 'password' }, + internal_note: { type: 'text', internal: true }, + }, + }; + + it('is pinned for a fixed input', () => { + expect(RECIPE_HASH_VERSION).toBe('rh1'); + expect(computeRecipeHash({ source: source({ where: { status: 'published' } }), schema })).toMatchInlineSnapshot(`"rh1:5def4262d86bc8f5a6e138e3139f369eb9c239f816ad974331cd195ddccf5326"`); + }); + + it('changes with where, metadataFields, the title field and the fields an index may not carry', () => { + const base = computeRecipeHash({ source: source(), schema }); + expect(computeRecipeHash({ source: source({ where: { status: 'published' } }), schema })).not.toBe(base); + expect(computeRecipeHash({ source: source({ metadataFields: [] }), schema })).not.toBe(base); + expect(computeRecipeHash({ source: source(), schema: { ...schema, nameField: 'status' } })).not.toBe(base); + const { internal_note: _dropped, ...rest } = schema.fields; + expect(computeRecipeHash({ source: source(), schema: { ...schema, fields: { ...rest, internal_note: { type: 'text' } } } })).not.toBe(base); + }); + + it('does not change with the content list, which is the fingerprint\'s', () => { + expect(computeRecipeHash({ source: source({ contentFields: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); + }); +}); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index f285b59ea30..fa5cca40d44 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -210,3 +210,60 @@ describe('search_knowledge — no searchable source', () => { expect(adapter.searched).toEqual([]); }); }); + +describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => { + const rebuild = () => + Object.assign(new Error("Knowledge source 'policy_clauses' needs a rebuild."), { + code: 'KNOWLEDGE_REBUILD_REQUIRED', + status: 409, + }); + + /** Two exposed sources; `refusing` throws a coded refusal, the other answers. */ + function twoSources(refusing: readonly string[], refusal: () => Error = rebuild) { + const adapter = adapterWith({ policy_clauses: [hit('policy_clauses', 'p1', 0.9)], faq: [hit('faq', 'f1', 0.4)] }); + const answer = adapter.search as unknown as ReturnType; + const inner = answer.getMockImplementation()!; + answer.mockImplementation(async (query: string, opts: { source: KnowledgeSource }) => { + if (refusing.includes(opts.source.id)) throw refusal(); + return inner(query, opts); + }); + const engine = { + find: vi.fn(async (_object: string, query: { where: { id: { $in: string[] } } }) => + query.where.id.$in.map((id) => ({ id }))), + } as unknown as IDataEngine; + const service = new KnowledgeService({ dataEngine: engine, logger: { warn: () => undefined } }); + service.registerAdapter('memory', adapter); + service.registerSource(objectSource('policy_clauses', 'policy_clause')); + service.registerSource(objectSource('faq', 'faq_entry')); + return service; + } + + it('names the refused source beside the hits of the source that answered', async () => { + const answer = await createKnowledgeTools(twoSources(['policy_clauses'])).searchKnowledge({ query: 'q' }, caller); + expect(answer.hits.map((h) => h.sourceId)).toEqual(['faq']); + expect(answer.refused).toEqual([ + { sourceId: 'policy_clauses', code: 'KNOWLEDGE_REBUILD_REQUIRED', message: "Knowledge source 'policy_clauses' needs a rebuild." }, + ]); + }); + + it('refuses the call whole, coded, when no searched source can answer — never an empty answer', async () => { + const tools = createKnowledgeTools(twoSources(['policy_clauses', 'faq'])); + await expect(tools.searchKnowledge({ query: 'q' }, caller)).rejects.toMatchObject({ + code: 'KNOWLEDGE_REBUILD_REQUIRED', + status: 409, + refused: [{ sourceId: 'policy_clauses' }, { sourceId: 'faq' }], + }); + }); + + it('control: a failure without a code is logged and skipped as before, and carries no refused list', async () => { + const answer = await createKnowledgeTools(twoSources(['policy_clauses'], () => new Error('socket hang up'))) + .searchKnowledge({ query: 'q' }, caller); + expect(answer.hits.map((h) => h.sourceId)).toEqual(['faq']); + expect(answer).not.toHaveProperty('refused'); + }); + + it('an answer with nothing refused carries no refused list', async () => { + const answer = await createKnowledgeTools(twoSources([])).searchKnowledge({ query: 'q' }, caller); + expect(answer).not.toHaveProperty('refused'); + }); +}); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 2580d99a3b0..782fadbeccc 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -10,7 +10,15 @@ * runKnowledgeAdapterContract({ * name: 'knowledge-memory', * makeAdapter: () => new KnowledgeMemoryAdapter(), - * implements: { listDocuments: true, chunks: true, organizationIds: true }, + * implements: { + * listDocuments: true, + * chunks: true, + * organizationIds: true, + * indexStatus: true, + * builds: true, + * refusesOtherFingerprint: true, + * generations: true, + * }, * }); * ``` * @@ -27,7 +35,14 @@ * receiving whole documents, and a `whole` document over the embedder's * budget is removed and reported, never truncated; and the organization filter * (ADR-0161 K8, item 9) — on the adapter alone, and through a real - * `KnowledgeService` under the `isolated`, `group` and `single` postures. + * `KnowledgeService` under the `isolated`, `group` and `single` postures; and + * the index fingerprint (ADR-0161 K7; K8, item 8) — every call through the + * service carries it, a complete reindex is one `beginBuild` / + * `completeBuild` pair and a partial one is neither, `indexStatus` answers + * what the last complete build recorded, a write or a search under another + * fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` and never served from the + * other generation, and — for an adapter that builds generations — a build + * under a new fingerprint switches to it at its end. * * Every optional member is DECLARED by the caller in `implements`, and the * suite asserts the declaration against the adapter: a member an adapter lacks @@ -38,7 +53,13 @@ */ import { describe, expect, it } from 'vitest'; -import type { IDataEngine, IKnowledgeAdapter, AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts'; +import type { + IDataEngine, + IKnowledgeAdapter, + AdapterContext, + AdapterIndexExpectation, + AdapterSearchOptions, +} from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; @@ -66,9 +87,32 @@ export interface KnowledgeAdapterContractOptions { * it is handed, filtering before it ranks. */ organizationIds: boolean; + /** `indexStatus` (ADR-0161 K8, item 8 b). */ + indexStatus: boolean; + /** `beginBuild` and `completeBuild`, which come as a pair (ADR-0161 K8, item 8 c). */ + builds: boolean; + /** + * A write or a search carrying an `index` fingerprint other than the active + * generation's is refused with the ADR-0112 code `KNOWLEDGE_REBUILD_REQUIRED` + * (ADR-0161 K7, rules 4 and 5). Asserted by behaviour. + */ + refusesOtherFingerprint: boolean; + /** + * `beginBuild` under a new fingerprint opens a generation beside the active + * one, and `completeBuild` switches to it (ADR-0161 K7, rules 1 to 3). + * Asserted by behaviour; needs `builds` and `refusesOtherFingerprint`. + */ + generations: boolean; }; } +/** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ +const REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; + +/** Two fixed fingerprints for the adapter-alone cases; opaque to the adapter. */ +const FP_OLD = { fingerprint: 'fp-contract:old', recipeHash: 'rh-contract:1' }; +const FP_NEW = { fingerprint: 'fp-contract:new', recipeHash: 'rh-contract:1' }; + /** Every case's source id starts with this, so a shared store can be told apart. */ const SOURCE_PREFIX = 'contract_'; @@ -81,8 +125,17 @@ function objectSource(id: string, extra: Partial = {}): K } as KnowledgeSource; } -function ctxOf(source: KnowledgeSource): AdapterContext { - return { source, reason: 'manual' }; +function ctxOf(source: KnowledgeSource, index?: AdapterIndexExpectation): AdapterContext { + return index === undefined ? { source, reason: 'manual' } : { source, reason: 'manual', index }; +} + +/** Asserts `promise` rejects with an ADR-0112 coded refusal: `code` and `status`, never a bare throw. */ +async function expectRebuildRefusal(promise: Promise): Promise { + const err = await promise.then( + () => { throw new Error('expected a KNOWLEDGE_REBUILD_REQUIRED refusal, got an answer'); }, + (e: unknown) => e, + ); + expect(err).toMatchObject({ code: REBUILD_REQUIRED, status: 409 }); } /** @@ -219,6 +272,10 @@ async function serviceOver( const upserted: string[][] = []; const received: KnowledgeDocument[] = []; const searched: AdapterSearchOptions[] = []; + /** Every context a write, delete or listing was handed, in order. */ + const contexts: AdapterContext[] = []; + /** `begin` / `complete`, in the order the service called them. */ + const builds: Array<'begin' | 'complete'> = []; // Delegation, not a prototype proxy: an adapter with `#private` fields only // answers when its methods are called on the adapter itself. The // descriptors are read through on every access, as the service reads them. @@ -233,15 +290,45 @@ async function serviceOver( upsert: async (docs, ctx) => { upserted.push(docs.map((d) => d.id)); received.push(...docs); + contexts.push(ctx); return adapter.upsert(docs, ctx); }, search: (query, searchOpts) => { searched.push(searchOpts); return adapter.search(query, searchOpts); }, - delete: (ids, ctx) => adapter.delete(ids, ctx), + delete: (ids, ctx) => { + contexts.push(ctx); + return adapter.delete(ids, ctx); + }, ...(typeof adapter.listDocuments === 'function' - ? { listDocuments: (ctx: AdapterContext, listOpts: { cursor?: string; limit: number }) => adapter.listDocuments!(ctx, listOpts) } + ? { + listDocuments: (ctx: AdapterContext, listOpts: { cursor?: string; limit: number }) => { + contexts.push(ctx); + return adapter.listDocuments!(ctx, listOpts); + }, + } + : {}), + ...(typeof adapter.indexStatus === 'function' + ? { indexStatus: (ctx: AdapterContext) => adapter.indexStatus!(ctx) } + : {}), + ...(typeof adapter.beginBuild === 'function' + ? { + beginBuild: (ctx: AdapterContext) => { + builds.push('begin'); + contexts.push(ctx); + return adapter.beginBuild!(ctx); + }, + } + : {}), + ...(typeof adapter.completeBuild === 'function' + ? { + completeBuild: (ctx: AdapterContext) => { + builds.push('complete'); + contexts.push(ctx); + return adapter.completeBuild!(ctx); + }, + } : {}), }; const posture = setup.posture; @@ -251,7 +338,7 @@ async function serviceOver( }); svc.registerAdapter('under_test', counting); svc.registerSource(source); - return { adapter, svc, upserted, received, searched }; + return { adapter, svc, upserted, received, searched, contexts, builds }; } /** The last element of `list`, or `undefined` when it is empty. */ @@ -304,6 +391,13 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.id).toBe('string'); expect(typeof adapter.listDocuments === 'function').toBe(opts.implements.listDocuments); expect(adapter.capabilities?.chunks === true).toBe(opts.implements.chunks); + expect(typeof adapter.indexStatus === 'function').toBe(opts.implements.indexStatus); + // The two ends of a build come together or not at all. + expect(typeof adapter.beginBuild === 'function').toBe(opts.implements.builds); + expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); + if (opts.implements.generations) { + expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); + } }); describe('upsert / search / delete', () => { @@ -547,6 +641,154 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + describe('the index fingerprint (ADR-0161 K7; K8, item 8)', () => { + it('every write, delete, listing and search through the service carries one fingerprint and recipe hash', async () => { + const rows = rowsOf(2); + const source = objectSource('fp_carry'); + const h = await serviceOver(make, rows, source); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + await h.svc.handleRecordDelete('article', 'r0'); + await h.svc.search('zebra1', { topK: 3, executionContext: SYSTEM }); + expect(h.contexts.length).toBeGreaterThan(0); + const [first] = h.contexts; + expect(first.index?.fingerprint).toMatch(/^fp1:[0-9a-f]{64}$/); + expect(first.index?.recipeHash).toMatch(/^rh1:[0-9a-f]{64}$/); + for (const ctx of h.contexts) expect(ctx.index).toEqual(first.index); + expect(lastOf(h.searched)?.index).toEqual({ fingerprint: first.index!.fingerprint }); + }); + + it('changes the fingerprint when the content recipe changes, and only the recipe hash when where or metadataFields do', async () => { + const rows = rowsOf(1); + const seen = async (extra: Partial) => { + const h = await serviceOver(make, rows, objectSource('fp_vary', extra)); + await h.svc.reindexSource(`${SOURCE_PREFIX}fp_vary`, { limit: 10 }); + return h.contexts[0].index!; + }; + const base = await seen({}); + expect(await seen({})).toEqual(base); // the same source, the same adapter: the same hashes + const content = await seen({ contentFields: ['body', 'status'] }); + expect(content.fingerprint).not.toBe(base.fingerprint); + const where = await seen({ where: { status: 'published' } }); + expect(where.fingerprint).toBe(base.fingerprint); + expect(where.recipeHash).not.toBe(base.recipeHash); + const metadata = await seen({ metadataFields: [] }); + expect(metadata.fingerprint).toBe(base.fingerprint); + expect(metadata.recipeHash).not.toBe(base.recipeHash); + }); + + if (opts.implements.builds) { + it('a complete reindex is one beginBuild / completeBuild pair; a limit or a dryRun calls neither', async () => { + const rows = rowsOf(3); + const source = objectSource('fp_pair'); + const h = await serviceOver(make, rows, source); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true }); + expect(h.builds).toEqual(['begin', 'complete']); + await h.svc.reindexSource(source.id, { limit: 10 }); + await h.svc.reindexSource(source.id, { dryRun: true }); + expect(h.builds).toEqual(['begin', 'complete']); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true }); + expect(h.builds).toEqual(['begin', 'complete', 'begin', 'complete']); + }); + } else { + it('without beginBuild / completeBuild a complete reindex walks as before', async () => { + const source = objectSource('fp_nobuild'); + const h = await serviceOver(make, rowsOf(2), source); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2 }); + expect(h.builds).toEqual([]); + }); + } + + if (opts.implements.indexStatus) { + it('indexStatus answers nothing before a build, and what the last complete build recorded after it', async () => { + const source = objectSource('fp_status'); + const h = await serviceOver(make, rowsOf(2), source); + const before = await h.adapter.indexStatus!(ctxOf(source)); + expect(before.recipeHash).toBeUndefined(); + expect(before.building ?? false).toBe(false); + await h.svc.reindexSource(source.id); + const carried = h.contexts[0].index!; + const after = await h.adapter.indexStatus!(ctxOf(source)); + expect(after.fingerprint).toBe(carried.fingerprint); + if (opts.implements.builds) expect(after.recipeHash).toBe(carried.recipeHash); + expect(after.building ?? false).toBe(false); + }); + } + + if (opts.implements.refusesOtherFingerprint) { + it('a search under another fingerprint is refused, coded, and never answered from the stored generation', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('fp_search'); + await adapter.upsert([doc(a, '1', 'basalt columns')], ctxOf(a, FP_OLD)); + expect((await adapter.search('basalt', { source: a, topK: 5, index: { fingerprint: FP_OLD.fingerprint } })).length).toBe(1); + await expectRebuildRefusal(adapter.search('basalt', { source: a, topK: 5, index: { fingerprint: FP_NEW.fingerprint } })); + }); + + it('a write under another fingerprint, with no build open for it, is refused and writes nothing', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('fp_write'); + await adapter.upsert([doc(a, '1', 'basalt columns')], ctxOf(a, FP_OLD)); + await expectRebuildRefusal(adapter.upsert([doc(a, '2', 'basalt quarry')], ctxOf(a, FP_NEW))); + const hits = await adapter.search('basalt', { source: a, topK: 5, index: { fingerprint: FP_OLD.fingerprint } }); + expect(hits.map((x) => x.documentId)).toEqual([`${a.id}:1`]); + }); + + it('through KnowledgeService: a changed recipe refuses the source by name, and the call whole only when none answers', async () => { + const rows = rowsOf(2); + const stale = objectSource('fp_stale'); + const h = await serviceOver(make, rows, stale); + await h.svc.reindexSource(stale.id); + // The content list changes: a new fingerprint the stored index was not built under. + h.svc.registerSource(objectSource('fp_stale', { contentFields: ['body', 'status'] })); + const whole = await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e, + ); + expect(whole).toMatchObject({ code: REBUILD_REQUIRED, status: 409, refused: [{ sourceId: stale.id, code: REBUILD_REQUIRED }] }); + // A second source that can be searched answers; the stale one is named, never read as empty. + const fresh = objectSource('fp_fresh'); + h.svc.registerSource(fresh); + await h.svc.reindexSource(fresh.id); + const report = await h.svc.searchWithRefusals('zebra1', { topK: 5, executionContext: SYSTEM }); + expect(report.hits.map((x) => x.sourceId)).toEqual([fresh.id]); + expect(report.refused).toEqual([expect.objectContaining({ sourceId: stale.id, code: REBUILD_REQUIRED, status: 409 })]); + expect((await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })).map((x) => x.sourceId)).toEqual([fresh.id]); + }); + } + + if (opts.implements.generations) { + it('a build under a new fingerprint fills a new generation and switches to it at completeBuild; the old one answers its own fingerprint until then', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('fp_gen'); + await adapter.upsert([doc(a, '1', 'granite quarry')], ctxOf(a, FP_OLD)); + await adapter.beginBuild!(ctxOf(a, FP_NEW)); + expect((await adapter.indexStatus?.(ctxOf(a)))?.building ?? true).toBe(true); + await adapter.upsert([doc(a, '1', 'marble quarry')], ctxOf(a, FP_NEW)); + // Resumed, not restarted: a second beginBuild for the same fingerprint keeps what was written. + await adapter.beginBuild!(ctxOf(a, FP_NEW)); + await expectRebuildRefusal(adapter.search('quarry', { source: a, topK: 5, index: { fingerprint: FP_NEW.fingerprint } })); + const old = await adapter.search('quarry', { source: a, topK: 5, index: { fingerprint: FP_OLD.fingerprint } }); + expect(old.map((x) => x.snippet)).toEqual(['granite quarry']); + await adapter.completeBuild!(ctxOf(a, FP_NEW)); + const now = await adapter.search('quarry', { source: a, topK: 5, index: { fingerprint: FP_NEW.fingerprint } }); + expect(now.map((x) => x.snippet)).toEqual(['marble quarry']); + await expectRebuildRefusal(adapter.search('quarry', { source: a, topK: 5, index: { fingerprint: FP_OLD.fingerprint } })); + expect(await adapter.indexStatus?.(ctxOf(a))).toEqual({ fingerprint: FP_NEW.fingerprint, recipeHash: FP_NEW.recipeHash }); + }); + + it('through KnowledgeService: a complete reindex after a recipe change builds the new generation and search answers again', async () => { + const rows = rowsOf(2); + const source = objectSource('fp_rebuild'); + const h = await serviceOver(make, rows, source); + await h.svc.reindexSource(source.id); + h.svc.registerSource(objectSource('fp_rebuild', { contentFields: ['body', 'status'] })); + await expectRebuildRefusal(h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM })); + expect(await h.svc.reindexSource(source.id)).toMatchObject({ ok: true, indexed: 2, skipped: 0 }); + const hits = await h.svc.search('zebra1', { topK: 5, executionContext: SYSTEM }); + expect(hits.map((x) => x.documentId)).toEqual([`${source.id}:r1`]); + }); + } + }); + describe('the chunk channel (ADR-0161 K8, item 5)', () => { const longBody = 'Glaciers carve valleys over centuries. Their ice holds ancient air bubbles. ' + From 1b8f7c03ddb4e978950bfca60991d4e693587fc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:15:33 +0000 Subject: [PATCH 03/11] wip(knowledge-pgvector): adapter, plugin, live PostgreSQL suites --- .changeset/config.json | 1 + packages/plugins/knowledge-pgvector/LICENSE | 202 ++++++ .../plugins/knowledge-pgvector/package.json | 68 ++ .../acceptance.live-postgres.test.ts | 229 ++++++ .../__tests__/contract.live-postgres.test.ts | 32 + .../src/__tests__/live-pg.testkit.ts | 106 +++ .../src/__tests__/not-ready.test.ts | 138 ++++ .../reindex-real-driver.live-postgres.test.ts | 111 +++ .../plugins/knowledge-pgvector/src/index.ts | 17 + .../src/pgvector-adapter.ts | 665 ++++++++++++++++++ .../plugins/knowledge-pgvector/src/plugin.ts | 169 +++++ .../plugins/knowledge-pgvector/src/sql.ts | 88 +++ .../plugins/knowledge-pgvector/tsconfig.json | 21 + .../knowledge-pgvector/tsconfig.test.json | 10 + .../knowledge-pgvector/vitest.config.ts | 68 ++ pnpm-lock.yaml | 37 + 16 files changed, 1962 insertions(+) create mode 100644 packages/plugins/knowledge-pgvector/LICENSE create mode 100644 packages/plugins/knowledge-pgvector/package.json create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/index.ts create mode 100644 packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts create mode 100644 packages/plugins/knowledge-pgvector/src/plugin.ts create mode 100644 packages/plugins/knowledge-pgvector/src/sql.ts create mode 100644 packages/plugins/knowledge-pgvector/tsconfig.json create mode 100644 packages/plugins/knowledge-pgvector/tsconfig.test.json create mode 100644 packages/plugins/knowledge-pgvector/vitest.config.ts diff --git a/.changeset/config.json b/.changeset/config.json index 8c102f4e23c..ae2e090afd0 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -78,6 +78,7 @@ "@objectstack/service-settings", "@objectstack/service-storage", "@objectstack/knowledge-memory", + "@objectstack/knowledge-pgvector", "@objectstack/knowledge-ragflow", "@objectstack/embedder-openai", "@objectstack/account", diff --git a/packages/plugins/knowledge-pgvector/LICENSE b/packages/plugins/knowledge-pgvector/LICENSE new file mode 100644 index 00000000000..16bc23f4043 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute + must include a readable copy of the attribution notices + contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, + in at least one of the following places: within a NOTICE + text file distributed as part of the Derivative Works; within + the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the + License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 ObjectStack + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/plugins/knowledge-pgvector/package.json b/packages/plugins/knowledge-pgvector/package.json new file mode 100644 index 00000000000..80f4f91211b --- /dev/null +++ b/packages/plugins/knowledge-pgvector/package.json @@ -0,0 +1,68 @@ +{ + "name": "@objectstack/knowledge-pgvector", + "version": "18.6.0", + "license": "Apache-2.0", + "description": "PostgreSQL + pgvector knowledge adapter for ObjectStack: an open vector store for self-hosted deployments.", + "type": "commonjs", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "sideEffects": false, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "scripts": { + "build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs", + "dev": "tsc -w", + "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/plugins/knowledge-pgvector --project tsconfig.test.json" + }, + "dependencies": { + "@objectstack/core": "workspace:*", + "@objectstack/spec": "workspace:*", + "pg": "^8.23.1" + }, + "devDependencies": { + "@objectstack/driver-sql": "workspace:*", + "@objectstack/objectql": "workspace:*", + "@objectstack/service-knowledge": "workspace:*", + "@types/node": "^26.6.5", + "@types/pg": "^8.15.6", + "tsx": "^4.23.15", + "typescript": "^6.0.3", + "vitest": "^4.1.11" + }, + "keywords": [ + "objectstack", + "knowledge", + "rag", + "pgvector", + "postgresql", + "vector-search" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/objectstack-ai/objectstack.git", + "directory": "packages/plugins/knowledge-pgvector" + }, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist", + "README.md", + "CHANGELOG.md" + ], + "engines": { + "node": ">=22.0.0" + } +} diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts new file mode 100644 index 00000000000..651dcb4800b --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts @@ -0,0 +1,229 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The acceptance cases of #37100 on a LIVE PostgreSQL with pgvector, beside + * the contract suite: a 3072-wide model, two organizations that never see each + * other's passages, an unchanged passage that is not embedded again, a changed + * fingerprint that is refused and never served, and the store's tables kept + * out of the connection's own schema. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KNOWLEDGE_REBUILD_REQUIRED } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector acceptance'); + +const store = liveStore('kpg_accept'); + +const source = (id: string): KnowledgeSource => + ({ + id, + label: id, + adapter: 'under_test', + source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'] }, + }) as KnowledgeSource; + +const FP_A = { fingerprint: 'fp-test:a', recipeHash: 'rh-test:1' }; +const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource, index = FP_A): AdapterContext => ({ source: s, reason: 'manual', index }); + +function doc(s: KnowledgeSource, n: string, content: string, extra: Partial = {}): KnowledgeDocument { + const id = `${s.id}:${n}`; + return { + id, + sourceId: s.id, + sourceRecordId: n, + content, + title: `Title ${n}`, + metadata: { status: 'published' }, + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], + ...extra, + }; +} + +const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as unknown as ExecutionContext; + +describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', () => { + afterAll(() => store.dropAll()); + + it('stores and ranks 3072-wide vectors: an exact scan, no index width limit', async () => { + const embedder = new FakeEmbedder(3072, 'fake-3072'); + const adapter = store.adapter({ embedder }); + const s = source('wide'); + await adapter.upsert([doc(s, '1', 'glacier valley ice'), doc(s, '2', 'harbour crane night')], ctx(s)); + const hits = await adapter.search('glacier ice', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:1`]); + expect(hits[0].score).toBeGreaterThan(0.5); + const width = await store.pool().query<{ t: string }>( + `SELECT format_type(a.atttypid, a.atttypmod) AS t FROM pg_attribute a + WHERE a.attrelid = to_regclass($1) AND a.attname = 'embedding'`, + [`"${(adapter as unknown as { schema: string }).schema}"."knowledge_vec_d3072"`], + ); + expect(width.rows[0]?.t).toBe('vector(3072)'); + }); + + it('two organizations never see each other\'s passages: the filter runs in SQL, before ranking', async () => { + const adapter = store.adapter(); + const s = source('orgs'); + // Organization B's passage would outrank A's for the query. + await adapter.upsert( + [ + doc(s, 'a', 'alpine meadow harbour', { organizationId: 'org_a' }), + doc(s, 'b', 'alpine meadow alpine meadow', { organizationId: 'org_b' }), + ], + ctx(s), + ); + const search = (organizationIds?: string[]) => + adapter.search('alpine meadow', { source: s, topK: 1, index: { fingerprint: FP_A.fingerprint }, ...(organizationIds ? { organizationIds } : {}) }); + expect((await search()).map((h) => h.documentId)).toEqual([`${s.id}:b`]); + expect((await search(['org_a'])).map((h) => h.documentId)).toEqual([`${s.id}:a`]); + expect((await search(['org_b'])).map((h) => h.documentId)).toEqual([`${s.id}:b`]); + expect(await search([])).toEqual([]); + expect(await search(['org_c'])).toEqual([]); + }); + + it('the metadata filter runs in SQL before ranking, so topK is filled from matching passages', async () => { + const adapter = store.adapter(); + const s = source('meta'); + await adapter.upsert( + [ + doc(s, '1', 'basalt basalt basalt', { metadata: { status: 'draft' } }), + doc(s, '2', 'basalt columns', { metadata: { status: 'published' } }), + ], + ctx(s), + ); + const hits = await adapter.search('basalt', { source: s, topK: 1, filter: { status: 'published' }, index: { fingerprint: FP_A.fingerprint } }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.id}:2`]); + expect(hits[0].metadata).toEqual({ status: 'published' }); + }); + + it('an unchanged passage is not embedded again; its metadata is rewritten', async () => { + const embedder = new FakeEmbedder(); + const adapter = store.adapter({ embedder }); + const s = source('same'); + await adapter.upsert([doc(s, '1', 'copper wire conducts heat')], ctx(s)); + expect(embedder.calls).toBe(1); + await adapter.upsert([doc(s, '1', 'copper wire conducts heat', { metadata: { status: 'archived' } })], ctx(s)); + expect(embedder.calls).toBe(1); + const [hit] = await adapter.search('copper', { source: s, topK: 1, index: { fingerprint: FP_A.fingerprint } }); + expect(hit.metadata).toEqual({ status: 'archived' }); + // A changed passage is embedded, and only it (the search above embedded its query). + const before = embedder.calls; + await adapter.upsert( + [{ ...doc(s, '1', 'x'), chunks: [ + { id: `${s.id}:1#0`, documentId: `${s.id}:1`, index: 0, content: 'copper wire conducts heat' }, + { id: `${s.id}:1#1`, documentId: `${s.id}:1`, index: 1, content: 'drawn through dies' }, + ] }], + ctx(s), + ); + expect(embedder.calls).toBe(before + 1); + expect(embedder.texts.slice(-1)).toEqual(['drawn through dies']); + }); + + it('through KnowledgeService: a second complete reindex of unchanged records embeds nothing', async () => { + const embedder = new FakeEmbedder(); + const adapter = store.adapter({ embedder }); + const rows = [ + { id: 'r1', body: 'granite quarry', status: 'published' }, + { id: 'r2', body: 'marble quarry', status: 'published' }, + ]; + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + svc.registerAdapter('under_test', adapter); + const s = source('svc_same'); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); + const after = embedder.calls; + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 0, skipped: 2 }); + expect(embedder.calls).toBe(after); + expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + }); + + it('a changed embedding model changes the fingerprint: search is refused by name, and the old rows are not served', async () => { + const embedder = new FakeEmbedder(384, 'model-one'); + const adapter = store.adapter({ embedder }); + const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'granite quarry', status: 'published' }]) }); + svc.registerAdapter('under_test', adapter); + const s = source('svc_model'); + svc.registerSource(s); + await svc.reindexSource(s.id); + expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1); + + embedder.model = 'model-two'; + const refused = await svc.search('granite', { topK: 3, executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message?: string }, + ); + expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + expect(refused?.message).toContain(s.id); + // A complete reindex under the new model is refused before anything is written, naming the SQL that clears the source. + const rebuilt = await svc.reindexSource(s.id); + expect(rebuilt.ok).toBe(false); + expect(rebuilt.message).toContain('DELETE FROM'); + }); + + it('beginBuild under another fingerprint is refused with the SQL that clears the source; under its own it is a no-op', async () => { + const adapter = store.adapter(); + const s = source('build'); + await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A)); + await expect(adapter.beginBuild(ctx(s, FP_A))).resolves.toBeUndefined(); + const err = await adapter.beginBuild(ctx(s, FP_B)).then(() => undefined, (e: unknown) => e as { code?: string; message?: string }); + expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + expect(err?.message).toContain(`WHERE source_id = '${s.id}'`); + // Nothing was served from, or written to, the stored generation under B. + await expect(adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } })).rejects.toMatchObject({ + code: KNOWLEDGE_REBUILD_REQUIRED, + }); + expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint }); + }); + + it('keeps its tables in its own schema, never the connection\'s current schema', async () => { + const adapter = store.adapter(); + const s = source('where'); + await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s)); + const own = (adapter as unknown as { schema: string }).schema; + const tables = await store.pool().query<{ table_schema: string; table_name: string }>( + `SELECT table_schema, table_name FROM information_schema.tables + WHERE table_name LIKE 'knowledge\\_%' AND table_schema IN ($1, current_schema()) ORDER BY table_name`, + [own], + ); + expect(tables.rows).toEqual([ + { table_schema: own, table_name: 'knowledge_generation' }, + { table_schema: own, table_name: 'knowledge_vec_d384' }, + ]); + }); +}); + +/** A data engine over fixed rows, for the service's walk: `find` with a keyset on `id`, and `count`. */ +function rowsEngine(rows: Array>) { + const sorted = [...rows].sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)); + const matches = (row: Record, where: Record | undefined): boolean => { + if (!where) return true; + return Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Array>).every((w) => matches(row, w)); + if (v !== null && typeof v === 'object') { + const cond = v as Record; + if ('$gt' in cond) return String(row[k]) > String(cond.$gt); + if ('$in' in cond) return (cond.$in as unknown[]).includes(row[k]); + throw new Error(`rowsEngine: condition ${JSON.stringify(v)} is not implemented`); + } + return row[k] === v; + }); + }; + return { + async find(_object: string, query: { where?: Record; limit?: number }) { + const out = sorted.filter((r) => matches(r, query?.where)); + return query?.limit === undefined ? out : out.slice(0, query.limit); + }, + async findOne(_object: string, query: { where?: Record }) { + return sorted.find((r) => matches(r, query?.where)) ?? null; + }, + async count(_object: string, query: { where?: Record }) { + return sorted.filter((r) => matches(r, query?.where)).length; + }, + } as never; +} diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts new file mode 100644 index 00000000000..6c3c827580d --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1) against a LIVE +// PostgreSQL with pgvector: the same suite the reference adapter runs, each +// case on a fresh adapter in a schema of its own. It does not build a second +// generation beside the first yet (#37101), so `generations` is false. + +import { afterAll, describe } from 'vitest'; +import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; +import { PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector contract'); + +const store = liveStore('kpg_contract'); + +describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { + afterAll(() => store.dropAll()); + + runKnowledgeAdapterContract({ + name: 'knowledge-pgvector', + makeAdapter: () => store.adapter(), + implements: { + listDocuments: true, + chunks: true, + organizationIds: true, + indexStatus: true, + builds: true, + refusesOtherFingerprint: true, + generations: false, + }, + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts b/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts new file mode 100644 index 00000000000..ec0439f0112 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts @@ -0,0 +1,106 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What the live PostgreSQL files of this package share: the URL, the named + * failure when a runner that declared the dialect matrix has none, a pool, + * a fresh schema per adapter, and a fixed fake embedder. + * + * Needs `OS_TEST_POSTGRES_URL` pointing at a PostgreSQL with the pgvector + * extension available (CI: the `pgvector/pgvector` service image); without one + * the files are a named skip, and `OS_EXPECT_LIVE_DIALECT_MATRIX=1` turns the + * skip into a failure, as in the platform's other live files. + */ + +import { createHash } from 'node:crypto'; +import { describe, it } from 'vitest'; +import pg from 'pg'; +import type { IEmbedder } from '@objectstack/spec/contracts'; +import { PgvectorKnowledgeAdapter, poolFromPg, type PgvectorKnowledgeAdapterOptions } from '../index.js'; + +export const PG_URL = process.env.OS_TEST_POSTGRES_URL; +const EXPECT_LIVE = process.env.OS_EXPECT_LIVE_DIALECT_MATRIX === '1'; + +/** Registers the failing case that stands in for a skipped live file on a provisioned runner. */ +export function requireLiveCell(name: string): void { + if (EXPECT_LIVE && !PG_URL) { + describe(`${name} — live PostgreSQL`, () => { + it('OS_TEST_POSTGRES_URL must be set on a runner that declared it provisioned', () => { + throw new Error('OS_EXPECT_LIVE_DIALECT_MATRIX=1 without OS_TEST_POSTGRES_URL: the live cell would have been skipped.'); + }); + }); + } +} + +/** + * A fixed embedder for tests: each lower-cased word hashed into one of + * `dimensions` slots, counted, and the vector scaled to unit length. Two texts + * sharing words point the same way; texts sharing none are orthogonal. It + * counts its calls and the texts it embedded. + */ +export class FakeEmbedder implements IEmbedder { + readonly id = 'fake'; + readonly dimensions: number; + model: string; + calls = 0; + texts: string[] = []; + + constructor(dimensions = 384, model = 'fake-bag-of-words') { + this.dimensions = dimensions; + this.model = model; + } + + async embed(texts: string[]): Promise { + this.calls += 1; + this.texts.push(...texts); + return texts.map((t) => this.vector(t)); + } + + private vector(text: string): number[] { + const v = new Array(this.dimensions).fill(0); + for (const word of text.toLowerCase().split(/[^a-z0-9一-鿿]+/i)) { + if (word === '') continue; + const slot = createHash('sha256').update(word).digest().readUInt32BE(0) % this.dimensions; + v[slot] += 1; + } + const norm = Math.sqrt(v.reduce((s, x) => s + x * x, 0)); + return norm === 0 ? v : v.map((x) => x / norm); + } +} + +/** + * One pool per file, and a fresh schema per adapter it makes; `dropAll` drops + * every schema it made. + */ +export function liveStore(prefix: string) { + let pool: pg.Pool | undefined; + let n = 0; + const schemas: string[] = []; + const run = `${process.pid}_${Date.now().toString(36)}`; + return { + pool(): pg.Pool { + pool ??= new pg.Pool({ connectionString: PG_URL, max: 4 }); + return pool; + }, + /** A fresh schema name, recorded for {@link dropAll}. */ + schema(): string { + const name = `${prefix}_${run}_${++n}`.toLowerCase(); + schemas.push(name); + return name; + }, + adapter(opts: Partial & { embedder?: PgvectorKnowledgeAdapterOptions['embedder'] } = {}) { + return new PgvectorKnowledgeAdapter({ + id: 'under_test', + pool: poolFromPg(this.pool()), + schema: this.schema(), + embedder: new FakeEmbedder(), + ...opts, + }); + }, + async dropAll(): Promise { + if (!pool) return; + for (const schema of schemas) await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + await pool.end(); + pool = undefined; + }, + }; +} diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts new file mode 100644 index 00000000000..fe1b7af0eec --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts @@ -0,0 +1,138 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Without a database that can hold the store, nothing is created, every call + * answers a readable `SERVICE_UNAVAILABLE` naming the SQL to run by hand, + * `healthCheck` answers `ok: false`, and boot goes on (card #37100). Runs + * everywhere: the database is a double that answers like PostgreSQL without + * the `vector` extension and without the right to create it. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { PluginContext } from '@objectstack/core'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { + KnowledgePgvectorPlugin, + PgvectorKnowledgeAdapter, + resolveStoreUrl, + vectorTable, + type PgPoolLike, +} from '../index.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { id: 's1', label: 's1', adapter: 'pgvector', source: { kind: 'object', object: 'a', contentFields: ['body'] } } as KnowledgeSource; + +/** A database without pgvector, where this connection may not create it; `installed` flips that. */ +function databaseWithoutVector() { + const statements: string[] = []; + let installed = false; + const pool: PgPoolLike = { + query: async (text: string) => { + statements.push(text); + if (text.includes('FROM pg_extension')) { + return { rows: (installed ? [{ schema: 'public', version: '0.8.0' }] : []) as R[] }; + } + if (text.startsWith('CREATE EXTENSION')) { + throw new Error('permission denied to create extension "vector"'); + } + return { rows: [] as R[] }; + }, + connect: async () => { + throw new Error('no transaction expected'); + }, + }; + return { pool, statements, install: () => { installed = true; } }; +} + +describe('knowledge-pgvector when the database is not ready', () => { + it('refuses every call SERVICE_UNAVAILABLE with the SQL to run, creates nothing, and is ready once the SQL has run', async () => { + const db = databaseWithoutVector(); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() }); + const ctx = { source, reason: 'manual' as const }; + + const err = await adapter.upsert([{ id: 'd1', sourceId: 's1', content: 'x' }], ctx).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message: string }, + ); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(err?.message).toContain("'vector' extension (pgvector) is not installed"); + expect(err?.message).toContain('permission denied'); + expect(err?.message).toContain('CREATE EXTENSION IF NOT EXISTS vector;'); + expect(err?.message).toContain('CREATE SCHEMA IF NOT EXISTS "os_knowledge";'); + await expect(adapter.search('x', { source, topK: 3 })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); + await expect(adapter.listDocuments(ctx, { limit: 5 })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); + + const health = await adapter.healthCheck(); + expect(health.ok).toBe(false); + expect(health.message).toContain('CREATE EXTENSION IF NOT EXISTS vector;'); + // Nothing past the extension was attempted. + expect(db.statements.some((s) => s.startsWith('CREATE SCHEMA') || s.startsWith('CREATE TABLE'))).toBe(false); + + // An operator runs the SQL; the next call succeeds without a restart. + db.install(); + expect((await adapter.healthCheck()).ok).toBe(true); + expect(db.statements.some((s) => s.startsWith('CREATE SCHEMA IF NOT EXISTS "os_knowledge"'))).toBe(true); + }); + + it('with no database at all, every call says why', async () => { + const adapter = new PgvectorKnowledgeAdapter({ embedder: new FakeEmbedder(), unavailable: 'the platform database (OS_DATABASE_URL) is not PostgreSQL.' }); + await expect(adapter.search('x', { source, topK: 3 })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + message: expect.stringContaining('OS_DATABASE_URL'), + }); + expect((await adapter.healthCheck()).ok).toBe(false); + }); + + it('the plugin registers the adapter and boot goes on, warning with the SQL', async () => { + const registered: string[] = []; + const warn = vi.fn(); + const ctx = { + getService: (name: string) => { + if (name === KNOWLEDGE_SERVICE) return { registerAdapter: (id: string) => registered.push(id) }; + throw new Error(`no service ${name}`); + }, + logger: { warn, info: vi.fn() }, + } as unknown as PluginContext; + const plugin = new KnowledgePgvectorPlugin({ env: { OS_DATABASE_URL: 'file:./data/app.db' } }); + await expect(plugin.start(ctx)).resolves.toBeUndefined(); + expect(registered).toEqual(['pgvector']); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('not ready')); + expect(warn.mock.calls[0][0]).toContain('is not PostgreSQL'); + await plugin.destroy(); + }); + + it('an embedder that is not registered is a readable SERVICE_UNAVAILABLE, not a crash', async () => { + const db = databaseWithoutVector(); + db.install(); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: () => undefined }); + expect(adapter.embedding).toBeUndefined(); + await expect(adapter.upsert([{ id: 'd1', sourceId: 's1', content: 'x' }], { source, reason: 'manual' })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + message: expect.stringContaining('no embedder'), + }); + }); +}); + +describe('knowledge-pgvector configuration', () => { + it('reads the store URL from the option, else the platform database when it is PostgreSQL', () => { + expect(resolveStoreUrl({ url: 'postgres://h/db', env: {} })).toEqual({ url: 'postgres://h/db', from: 'the plugin option `url`' }); + expect(resolveStoreUrl({ env: { OS_DATABASE_URL: 'postgresql://h/db' } })).toEqual({ url: 'postgresql://h/db', from: 'OS_DATABASE_URL' }); + expect(resolveStoreUrl({ env: { DATABASE_URL: 'postgres://h/legacy' } })).toEqual({ url: 'postgres://h/legacy', from: 'DATABASE_URL' }); + expect(resolveStoreUrl({ env: { OS_DATABASE_URL: 'mysql://h/db' } })).toMatchObject({ reason: expect.stringContaining('not PostgreSQL') }); + expect(resolveStoreUrl({ env: {} })).toMatchObject({ reason: expect.stringContaining('not set') }); + expect(resolveStoreUrl({ url: 'mysql://h/db', env: {} })).toMatchObject({ reason: expect.stringContaining('postgres://') }); + }); + + it('holds the schema to a lower-case identifier and the width to a positive integer', () => { + expect(() => new PgvectorKnowledgeAdapter({ embedder: new FakeEmbedder(), schema: 'Bad"Schema' })).toThrow(/lower-case identifier/); + expect(vectorTable(3072)).toBe('knowledge_vec_d3072'); + expect(() => vectorTable(0)).toThrow(RangeError); + expect(() => vectorTable(1.5)).toThrow(RangeError); + }); + + it('reports its embedder as the fingerprint reads it: model and dimensions', () => { + const adapter = new PgvectorKnowledgeAdapter({ embedder: new FakeEmbedder(1536, 'text-embedding-3-small') }); + expect(adapter.embedding).toEqual({ dimensions: 1536, model: 'text-embedding-3-small' }); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts new file mode 100644 index 00000000000..63491444851 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/reindex-real-driver.live-postgres.test.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A complete reindex over the REAL data path on a LIVE PostgreSQL: a real + * `ObjectQL` over a real `SqlDriver` as the knowledge service's data engine, + * and this store as its adapter (card #37100, comment 7145881825). + * + * The record ids are the ones a keyset walk and a listing in another order + * would disagree on: mixed case (`Ab`, `aB`, `AB`), numeric-looking (`9`, + * `10`, `010`), and enough of them to take several pages of the walk. Every + * record is indexed once, none is skipped or purged, and a second complete + * reindex writes nothing — the listing (byte order) and the walk (the + * database's order) agree on every id. + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector reindex over the real driver'); + +const store = liveStore('kpg_driver'); + +/** The walk's page (service-knowledge `REINDEX_PAGE_SIZE`): the ids below span more than two pages. */ +const REINDEX_PAGE_SIZE = 100; + +const OBJECT = 'kpg_article'; +const ARTICLE = { + name: OBJECT, + label: 'Article', + fields: { + body: { name: 'body', type: 'textarea' }, + status: { name: 'status', type: 'text' }, + }, +}; + +/** Ids the byte order and a collation's order put differently, past two pages of the walk. */ +function recordIds(): string[] { + const odd = ['Ab', 'aB', 'AB', 'ab', 'a-b', 'a_b', '9', '10', '010', '1e3', 'Z', 'z', 'Éclair', 'eclair']; + const filler = Array.from({ length: REINDEX_PAGE_SIZE * 2 + 13 }, (_, i) => (i % 2 === 0 ? `R${i}` : `${1000 + i}`)); + return [...odd, ...filler]; +} + +describe.skipIf(!PG_URL)('knowledge-pgvector — complete reindex over ObjectQL + SqlDriver on a LIVE PostgreSQL', { timeout: 60_000 }, () => { + const objectSchema = store.schema(); + let driver: SqlDriver; + let engine: ObjectQL; + let svc: KnowledgeService; + let upserted: string[]; + let embedder: FakeEmbedder; + const ids = recordIds(); + const source = { + id: 'driver_walk', + label: 'Driver walk', + adapter: 'pgvector', + source: { kind: 'object', object: OBJECT, contentFields: ['body'], metadataFields: ['status'] }, + } as KnowledgeSource; + + beforeAll(async () => { + await store.pool().query(`DROP SCHEMA IF EXISTS "${objectSchema}" CASCADE`); + await store.pool().query(`CREATE SCHEMA "${objectSchema}"`); + driver = new SqlDriver({ client: 'pg', connection: PG_URL, searchPath: [objectSchema] } as never); + await driver.initObjects([ARTICLE] as never); + for (const id of ids) { + // Seeded through the driver: data at rest, as an install holds it. + await driver.create(OBJECT, { id, body: `passage of record ${id} granite`, status: 'published' }); + } + engine = new ObjectQL(); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registry.registerObject(ARTICLE as never, 'com.objectstack.test.knowledge-pgvector'); + + embedder = new FakeEmbedder(); + const adapter = store.adapter({ id: 'pgvector', embedder }); + upserted = []; + const counting: IKnowledgeAdapter = Object.assign(Object.create(adapter) as IKnowledgeAdapter, { + upsert: (docs: Parameters[0], ctx: Parameters[1]) => { + upserted.push(...docs.map((d) => d.sourceRecordId ?? d.id)); + return adapter.upsert(docs, ctx); + }, + }); + svc = new KnowledgeService({ dataEngine: engine as never }); + svc.registerAdapter('pgvector', counting); + svc.registerSource(source); + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + await store.dropAll(); + }); + + it('indexes every record exactly once, skips none, purges none', async () => { + const first = await svc.reindexSource(source.id); + expect(first).toMatchObject({ ok: true, discovered: ids.length, indexed: ids.length, skipped: 0, failed: 0 }); + expect(first.purged ?? 0).toBe(0); + expect([...upserted].sort()).toEqual([...ids].sort()); + }); + + it('a second complete reindex writes nothing, embeds nothing, and purges nothing', async () => { + const before = { upserts: upserted.length, embeds: embedder.calls }; + const second = await svc.reindexSource(source.id); + expect(second).toMatchObject({ ok: true, discovered: ids.length, indexed: 0, skipped: ids.length, failed: 0 }); + expect(second.purged ?? 0).toBe(0); + expect(upserted.length).toBe(before.upserts); + expect(embedder.calls).toBe(before.embeds); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/index.ts b/packages/plugins/knowledge-pgvector/src/index.ts new file mode 100644 index 00000000000..5de2ec8e5dc --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/index.ts @@ -0,0 +1,17 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +export { + KNOWLEDGE_REBUILD_REQUIRED, + PgvectorKnowledgeAdapter, + type PgClientLike, + type PgPoolLike, + type PgQueryResult, + type PgvectorKnowledgeAdapterOptions, +} from './pgvector-adapter.js'; +export { + KnowledgePgvectorPlugin, + poolFromPg, + resolveStoreUrl, + type KnowledgePgvectorPluginOptions, +} from './plugin.js'; +export { DEFAULT_KNOWLEDGE_SCHEMA, GENERATION_TABLE, vectorTable } from './sql.js'; diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts new file mode 100644 index 00000000000..98108ae5306 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -0,0 +1,665 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { createHash } from 'node:crypto'; +import type { + AdapterContext, + AdapterEmbeddingDescriptor, + AdapterIndexStatus, + AdapterListDocumentsOptions, + AdapterListDocumentsPage, + AdapterSearchOptions, + IEmbedder, + IKnowledgeAdapter, +} from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai'; +import { + DEFAULT_KNOWLEDGE_SCHEMA, + GENERATION_TABLE, + SAFE_IDENTIFIER, + qualified, + schemaDdl, + vectorLiteral, + vectorTable, + vectorTableDdl, +} from './sql.js'; + +/** One answer of a query: its rows. */ +export interface PgQueryResult> { + rows: R[]; +} + +/** What the adapter needs of a checked-out connection: a query, and its release. */ +export interface PgClientLike { + query>(text: string, params?: unknown[]): Promise>; + release(err?: Error | boolean): void; +} + +/** + * What the adapter needs of a connection pool (`pg.Pool` has it — see + * `poolFromPg`): a one-shot query, which takes a connection and gives it back, + * and a checkout for a transaction. + */ +export interface PgPoolLike { + query>(text: string, params?: unknown[]): Promise>; + connect(): Promise; +} + +/** Options of {@link PgvectorKnowledgeAdapter}. */ +export interface PgvectorKnowledgeAdapterOptions { + /** Adapter id, the value of `KnowledgeSource.adapter`. @default 'pgvector' */ + id?: string; + /** + * The pool the store queries through. Absent: the store has no database, + * and every call answers `SERVICE_UNAVAILABLE` naming `unavailable`. + */ + pool?: PgPoolLike; + /** Why there is no pool, said by every call when `pool` is absent. */ + unavailable?: string; + /** + * The embedder the store calls, or a getter read at each call (the kernel's + * `embedder` service may register after this adapter). Its `dimensions` + * choose the passage table; its `model` and `dimensions` are what the + * adapter reports to the knowledge service's index fingerprint. + */ + embedder: IEmbedder | (() => IEmbedder | undefined); + /** + * The schema the store's tables live in. + * @default 'os_knowledge' + */ + schema?: string; + /** + * Text put before every QUERY before it is embedded, for an asymmetric + * model that embeds questions and passages differently (BGE's + * `'Represent this sentence for searching relevant passages: '`). Passages + * are embedded as they are. It changes no stored vector, so it is not part + * of the index fingerprint (ADR-0161 K8, item 15). + */ + queryPrefix?: string; +} + +/** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ +export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; + +/** A generation row: one complete index of one source under one fingerprint. */ +interface GenerationRow { + generation: number; + fingerprint: string | null; + recipe_hash: string | null; + dim: number; +} + +/** What the store learned when it became ready. */ +interface Readiness { + /** The schema the `vector` extension is installed in, quoted for SQL. */ + extensionSchema: string; + /** The extension's version. */ + version: string; +} + +/** + * `PgvectorKnowledgeAdapter` — an `IKnowledgeAdapter` on PostgreSQL with the + * pgvector extension: the open vector store for self-hosted deployments + * (cloud ADR-0119 D5; ADR-0161 Execution, row 8a). + * + * ## Storage + * + * In its own schema ({@link DEFAULT_KNOWLEDGE_SCHEMA}, outside the + * connection's `search_path`, so no table can collide with an object table or + * be read as schema drift): a generation table, `knowledge_generation` (source, + * generation, fingerprint, recipe hash, vector width, model, state), and one + * passage table per vector width, `knowledge_vec_d`, created the first + * time a width is written. A passage row holds its source, generation, chunk + * and document ids, record id, organization, text, title, heading path, + * document hash, chunk hash, metadata and vector. The text is stored: it is + * as sensitive as the record it came from, and it is in every backup of the database. + * + * ## Search + * + * An exact scan by cosine distance — no approximate index, so a 3072-wide + * model works (pgvector's HNSW index stops at 2000 dimensions; adding one is an + * operator's step, documented with the package). The organization filter + * (ADR-0161 K8, item 9) and the metadata-equality `filter` run in the same + * `WHERE`, before ranking. A passage whose cosine similarity is not positive is + * not a hit. + * + * ## The index fingerprint (ADR-0161 K7; K8, item 8) + * + * The generation row holds the fingerprint the source was built under. A write + * or a search carrying another is refused `KNOWLEDGE_REBUILD_REQUIRED` and is + * never served from the stored generation. A source that holds nothing takes + * the first fingerprint it is handed. `beginBuild` under the stored fingerprint + * rebuilds inside the generation; under another it is refused, with the SQL + * that drops the source's index so it can be built afresh — this store does + * not yet build a second generation beside the first. `completeBuild` records + * the recipe hash; `indexStatus` answers both. + * + * ## Writes + * + * The adapter takes the service's passages (`capabilities.chunks`) and hashes + * the text of each (`chunk_hash`). A passage whose hash is already stored is + * not embedded again: its row's metadata is rewritten. Every embed call runs + * before a connection is taken for the write, so no pooled connection waits on + * the embedder. + * + * ## When the database is not ready + * + * Without the `vector` extension (and the right to create it), or without the + * right to create the schema, the adapter creates nothing; every call answers + * `SERVICE_UNAVAILABLE` with the SQL to run by hand, `healthCheck` answers + * `ok: false`, and the next call tries again. + */ +export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { + readonly id: string; + readonly capabilities = { chunks: true } as const; + private readonly pool?: PgPoolLike; + private readonly unavailable?: string; + private readonly resolveEmbedder: () => IEmbedder | undefined; + private readonly schema: string; + private readonly queryPrefix: string; + private readiness?: Readiness; + /** Widths whose passage table this adapter has created or found. */ + private readonly tables = new Set(); + + constructor(opts: PgvectorKnowledgeAdapterOptions) { + this.id = opts.id ?? 'pgvector'; + this.pool = opts.pool; + this.unavailable = opts.unavailable; + const embedder = opts.embedder; + this.resolveEmbedder = typeof embedder === 'function' ? embedder : () => embedder; + this.schema = opts.schema ?? DEFAULT_KNOWLEDGE_SCHEMA; + if (!SAFE_IDENTIFIER.test(this.schema)) { + throw new Error( + `knowledge-pgvector: schema '${this.schema}' is not a lower-case identifier (letters, digits, underscores).`, + ); + } + this.queryPrefix = opts.queryPrefix ?? ''; + } + + /** What the adapter reports about its embedder (ADR-0161 K8, item 6), read now. */ + get embedding(): AdapterEmbeddingDescriptor | undefined { + const embedder = this.resolveEmbedder(); + if (!embedder) return undefined; + return { + dimensions: embedder.dimensions, + ...(embedder.model === undefined ? {} : { model: embedder.model }), + ...(embedder.maxInputTokens === undefined ? {} : { maxInputTokens: embedder.maxInputTokens }), + }; + } + + async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { + if (docs.length === 0) return; + const pool = this.requirePool(); + const readiness = await this.ready(); + const embedder = this.requireEmbedder(); + const generation = (await this.writeTarget(ctx, embedder, true))!; + await this.ensureVectorTable(generation.dim, readiness); + const table = qualified(this.schema, vectorTable(generation.dim)); + const sourceId = ctx.source.id; + + const planned = docs.map((doc) => ({ + doc, + passages: passagesOf(doc).map((p) => ({ ...p, hash: chunkHash(p.content) })), + })); + const stored = new Map(); + const existing = await pool.query<{ chunk_id: string; chunk_hash: string }>( + `SELECT chunk_id, chunk_hash FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = ANY($3::text[])`, + [sourceId, generation.generation, docs.map((d) => d.id)], + ); + for (const row of existing.rows) stored.set(row.chunk_id, row.chunk_hash); + + // Embed what changed, before any connection is taken for the write. + const toEmbed = planned.flatMap((p) => p.passages).filter((p) => stored.get(p.id) !== p.hash); + const vectors = toEmbed.length === 0 ? [] : await embedder.embed(toEmbed.map((p) => p.content)); + if (vectors.length !== toEmbed.length) { + throw new Error( + `knowledge-pgvector: the embedder answered ${vectors.length} vector(s) for ${toEmbed.length} passage(s); nothing was written.`, + ); + } + const vectorOf = new Map(); + toEmbed.forEach((p, i) => { + const v = vectors[i]; + if (!Array.isArray(v) || v.length !== generation.dim) { + throw new Error( + `knowledge-pgvector: the embedder answered a ${Array.isArray(v) ? v.length : 'missing'}-wide vector for ` + + `passage '${p.id}', and this source's index holds ${generation.dim}-wide vectors; nothing was written.`, + ); + } + vectorOf.set(p.id, v); + }); + + await this.transaction(async (client) => { + for (const { doc, passages } of planned) { + await client.query( + `DELETE FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = $3 AND NOT (chunk_id = ANY($4::text[]))`, + [sourceId, generation.generation, doc.id, passages.map((p) => p.id)], + ); + for (const p of passages) { + const common = [ + sourceId, + generation.generation, + p.id, + doc.id, + doc.sourceRecordId ?? null, + doc.organizationId ?? null, + p.content, + doc.title ?? null, + doc.docHash ?? null, + p.hash, + JSON.stringify(doc.metadata ?? {}), + p.headingPath === undefined ? null : JSON.stringify(p.headingPath), + ]; + const vector = vectorOf.get(p.id); + if (vector === undefined) { + // Unchanged text: the stored vector stands; the rest of the row is rewritten. + await client.query( + `UPDATE ${table} SET document_id = $4, source_record_id = $5, organization_id = $6, content = $7, title = $8, + doc_hash = $9, chunk_hash = $10, metadata = $11::jsonb, heading_path = $12::jsonb + WHERE source_id = $1 AND generation = $2 AND chunk_id = $3`, + common, + ); + } else { + await client.query( + `INSERT INTO ${table} (source_id, generation, chunk_id, document_id, source_record_id, organization_id, content, + title, doc_hash, chunk_hash, metadata, heading_path, embedding) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12::jsonb, $13::${readiness.extensionSchema}.vector) + ON CONFLICT (source_id, generation, chunk_id) DO UPDATE SET document_id = EXCLUDED.document_id, + source_record_id = EXCLUDED.source_record_id, organization_id = EXCLUDED.organization_id, + content = EXCLUDED.content, title = EXCLUDED.title, doc_hash = EXCLUDED.doc_hash, + chunk_hash = EXCLUDED.chunk_hash, metadata = EXCLUDED.metadata, heading_path = EXCLUDED.heading_path, + embedding = EXCLUDED.embedding`, + [...common, vectorLiteral(vector)], + ); + } + } + } + }); + } + + async delete(documentIds: string[], ctx: AdapterContext): Promise { + if (documentIds.length === 0) return; + const pool = this.requirePool(); + await this.ready(); + // From every generation of the source: a removed document leaves them all. + const widths = await pool.query<{ dim: number }>( + `SELECT DISTINCT dim FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1`, + [ctx.source.id], + ); + for (const { dim } of widths.rows) { + if (!(await this.tableExists(Number(dim)))) continue; + await pool.query( + `DELETE FROM ${qualified(this.schema, vectorTable(Number(dim)))} WHERE source_id = $1 AND document_id = ANY($2::text[])`, + [ctx.source.id, documentIds], + ); + } + } + + 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)}`); + } + const pool = this.requirePool(); + await this.ready(); + // The generation the writes go to (ADR-0161 K8, item 1). + const generation = await this.writeTarget(ctx, undefined, false); + if (!generation || !(await this.tableExists(generation.dim))) return { documents: [] }; + // In byte order ("C"), both the order and the cursor's comparison, so a + // cursor stays valid whatever the database's collation. + const params: unknown[] = [ctx.source.id, generation.generation, opts.limit + 1]; + const after = opts.cursor === undefined ? '' : `AND document_id COLLATE "C" > $4`; + if (opts.cursor !== undefined) params.push(opts.cursor); + const page = await pool.query<{ document_id: string; doc_hash: string | null }>( + `SELECT document_id, max(doc_hash) AS doc_hash FROM ${qualified(this.schema, vectorTable(generation.dim))} + WHERE source_id = $1 AND generation = $2 ${after} + GROUP BY document_id ORDER BY document_id COLLATE "C" LIMIT $3`, + params, + ); + const rows = page.rows.slice(0, opts.limit); + return { + documents: rows.map((r) => (r.doc_hash === null ? { documentId: r.document_id } : { documentId: r.document_id, docHash: r.doc_hash })), + ...(page.rows.length > opts.limit ? { nextCursor: rows[rows.length - 1].document_id } : {}), + }; + } + + async search(query: string, opts: AdapterSearchOptions): Promise { + // An empty organization set ranks nothing (ADR-0161 K8, item 9). + if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; + const pool = this.requirePool(); + const readiness = await this.ready(); + const generation = await this.activeGeneration(opts.source.id); + if (!generation) return []; + // Vectors of two fingerprints are never ranked against each other (K7, rule 5). + if (opts.index !== undefined && generation.fingerprint !== opts.index.fingerprint) { + throw rebuildRequired(opts.source.id, this.dropSql(opts.source.id)); + } + const embedder = this.requireEmbedder(); + if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, this.dropSql(opts.source.id)); + if (!(await this.tableExists(generation.dim))) return []; + const topK = Math.max(0, Math.floor(opts.topK)); + if (topK === 0) return []; + + // The query is embedded before a connection is taken. + const [vector] = await embedder.embed([`${this.queryPrefix}${query}`]); + if (!Array.isArray(vector) || vector.length !== generation.dim) { + throw new Error( + `knowledge-pgvector: the embedder answered a ${Array.isArray(vector) ? vector.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${generation.dim}-wide vectors.`, + ); + } + if (vector.every((x) => x === 0)) return []; + + const ext = readiness.extensionSchema; + const params: unknown[] = [opts.source.id, generation.generation, vectorLiteral(vector), topK]; + const where = ['source_id = $1', 'generation = $2']; + if (opts.organizationIds !== undefined) { + params.push(opts.organizationIds); + where.push(`organization_id = ANY($${params.length}::text[])`); + } + for (const [key, value] of Object.entries(opts.filter ?? {})) { + params.push(key, JSON.stringify(value === undefined ? null : value)); + where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`); + } + const result = await pool.query<{ + chunk_id: string; + document_id: string; + source_record_id: string | null; + content: string; + title: string | null; + metadata: Record | null; + distance: number; + }>( + `SELECT * FROM ( + SELECT chunk_id, document_id, source_record_id, content, title, metadata, + embedding OPERATOR(${ext}.<=>) $3::${ext}.vector AS distance + FROM ${qualified(this.schema, vectorTable(generation.dim))} + WHERE ${where.join(' AND ')} + ) ranked + WHERE distance < 1 + ORDER BY distance, chunk_id + LIMIT $4`, + params, + ); + return result.rows.map((r) => ({ + chunkId: r.chunk_id, + documentId: r.document_id, + sourceId: opts.source.id, + ...(r.source_record_id === null ? {} : { sourceRecordId: r.source_record_id }), + score: 1 - Number(r.distance), + snippet: r.content, + ...(r.title === null ? {} : { title: r.title }), + metadata: r.metadata ?? {}, + })); + } + + async indexStatus(ctx: AdapterContext): Promise { + this.requirePool(); + await this.ready(); + const generation = await this.activeGeneration(ctx.source.id); + const status: AdapterIndexStatus = {}; + if (generation?.fingerprint != null) status.fingerprint = generation.fingerprint; + if (generation?.recipe_hash != null) status.recipeHash = generation.recipe_hash; + return status; + } + + async beginBuild(ctx: AdapterContext): Promise { + const index = requireIndex(ctx, 'beginBuild'); + this.requirePool(); + await this.ready(); + const embedder = this.requireEmbedder(); + const generation = (await this.activeGeneration(ctx.source.id)) + ?? (await this.openFirstGeneration(ctx.source.id, index.fingerprint, embedder)); + if (generation.fingerprint === index.fingerprint && generation.dim === embedder.dimensions) return; + throw Object.assign( + new Error( + `Knowledge source '${ctx.source.id}' was indexed under another fingerprint (embedding model, dimensions, ` + + 'split or content recipe changed), and this store does not yet build a second generation beside the ' + + 'first. Either restore the earlier embedding and split configuration, or drop the source\'s index and ' + + `reindex it: ${this.dropSql(ctx.source.id)}`, + ), + { code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }, + ); + } + + async completeBuild(ctx: AdapterContext): Promise { + const index = requireIndex(ctx, 'completeBuild'); + const pool = this.requirePool(); + await this.ready(); + const updated = await pool.query( + `UPDATE ${qualified(this.schema, GENERATION_TABLE)} SET recipe_hash = $3 + WHERE source_id = $1 AND state = 'active' AND fingerprint = $2 RETURNING generation`, + [ctx.source.id, index.fingerprint, index.recipeHash], + ); + if (updated.rows.length === 0) { + throw new Error( + `completeBuild: source '${ctx.source.id}' holds no active generation under this fingerprint; call beginBuild first.`, + ); + } + } + + async healthCheck(): Promise<{ ok: boolean; message?: string }> { + try { + this.requirePool(); + const r = await this.ready(); + return { ok: true, message: `pgvector ${r.version}, tables in schema '${this.schema}'` }; + } catch (err) { + return { ok: false, message: err instanceof Error ? err.message : String(err) }; + } + } + + // ── Internals ───────────────────────────────────────────────────── + + private requirePool(): PgPoolLike { + if (!this.pool) { + throw notReady(this.unavailable ?? 'it has no PostgreSQL connection.', []); + } + return this.pool; + } + + private requireEmbedder(): IEmbedder { + const embedder = this.resolveEmbedder(); + if (!embedder) { + throw Object.assign( + new Error( + 'knowledge-pgvector has no embedder: register an embedder service (Settings → AI & Embedder) or pass ' + + '`embedder` to the plugin. Passages are sent to that embedder\'s provider.', + ), + { code: 'SERVICE_UNAVAILABLE', status: 503 }, + ); + } + return embedder; + } + + /** + * Make the store ready once: the `vector` extension (created when it is + * missing and the connection may), then the schema and the generation + * table. Until that succeeds nothing is created past the step that failed, + * and the refusal carries the SQL to run by hand; the next call tries again. + */ + private async ready(): Promise { + if (this.readiness) return this.readiness; + const pool = this.requirePool(); + const ddl = schemaDdl(this.schema); + let ext: { schema: string; version: string } | undefined; + try { + ext = await this.findExtension(pool); + if (!ext) { + await pool.query('CREATE EXTENSION IF NOT EXISTS vector'); + ext = await this.findExtension(pool); + } + } catch (err) { + throw notReady( + `the PostgreSQL 'vector' extension (pgvector) is not installed in this database, and this connection could not ` + + `install it (${errorText(err)}).`, + ['CREATE EXTENSION IF NOT EXISTS vector;', ...ddl.map((s) => `${s};`)], + ); + } + if (!ext) { + throw notReady("the PostgreSQL 'vector' extension (pgvector) is not installed in this database.", [ + 'CREATE EXTENSION IF NOT EXISTS vector;', + ...ddl.map((s) => `${s};`), + ]); + } + try { + for (const statement of ddl) await pool.query(statement); + } catch (err) { + throw notReady( + `its schema '${this.schema}' and generation table could not be created (${errorText(err)}).`, + ddl.map((s) => `${s};`), + ); + } + this.readiness = { extensionSchema: `"${ext.schema}"`, version: ext.version }; + return this.readiness; + } + + private async findExtension(pool: PgPoolLike): Promise<{ schema: string; version: string } | undefined> { + const found = await pool.query<{ schema: string; version: string }>( + `SELECT n.nspname AS schema, e.extversion AS version + FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname = 'vector'`, + ); + return found.rows[0]; + } + + private async ensureVectorTable(dimensions: number, readiness: Readiness): Promise { + if (this.tables.has(dimensions)) return; + const pool = this.requirePool(); + const ddl = vectorTableDdl(this.schema, dimensions, `${readiness.extensionSchema}.vector`); + try { + for (const statement of ddl) await pool.query(statement); + } catch (err) { + throw notReady( + `its ${dimensions}-wide passage table could not be created (${errorText(err)}).`, + ddl.map((s) => `${s};`), + ); + } + this.tables.add(dimensions); + } + + private async tableExists(dimensions: number): Promise { + if (this.tables.has(dimensions)) return true; + const found = await this.requirePool().query<{ present: string | null }>( + 'SELECT to_regclass($1) AS present', + [qualified(this.schema, vectorTable(dimensions))], + ); + const present = found.rows[0]?.present != null; + if (present) this.tables.add(dimensions); + return present; + } + + private async activeGeneration(sourceId: string): Promise { + const found = await this.requirePool().query( + `SELECT generation, fingerprint, recipe_hash, dim FROM ${qualified(this.schema, GENERATION_TABLE)} + WHERE source_id = $1 AND state = 'active' ORDER BY generation DESC LIMIT 1`, + [sourceId], + ); + const row = found.rows[0]; + return row === undefined ? undefined : { ...row, generation: Number(row.generation), dim: Number(row.dim) }; + } + + /** A source that holds nothing takes the first fingerprint it is handed (there is nothing to mix with). */ + private async openFirstGeneration(sourceId: string, fingerprint: string | undefined, embedder: IEmbedder): Promise { + await this.requirePool().query( + `INSERT INTO ${qualified(this.schema, GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) + VALUES ($1, 1, $2, $3, $4, 'active') ON CONFLICT (source_id, generation) DO NOTHING`, + [sourceId, fingerprint ?? null, embedder.dimensions, embedder.model ?? null], + ); + return (await this.activeGeneration(sourceId))!; + } + + /** + * The generation a write carrying `ctx.index` goes to: the active one, when + * its fingerprint is the one carried (or none is carried); refused when it is + * another, or when the embedder's width is not the generation's. A source + * that holds nothing gets its first generation (`create`), or none. + */ + private async writeTarget( + ctx: AdapterContext, + embedder: IEmbedder | undefined, + create: boolean, + ): Promise { + const active = await this.activeGeneration(ctx.source.id); + if (!active) { + if (!create || !embedder) return undefined; + const opened = await this.openFirstGeneration(ctx.source.id, ctx.index?.fingerprint, embedder); + return this.checkTarget(ctx, opened, embedder); + } + return this.checkTarget(ctx, active, embedder); + } + + private checkTarget(ctx: AdapterContext, generation: GenerationRow, embedder: IEmbedder | undefined): GenerationRow { + const fingerprint = ctx.index?.fingerprint; + if (fingerprint !== undefined && generation.fingerprint !== fingerprint) { + throw rebuildRequired(ctx.source.id, this.dropSql(ctx.source.id)); + } + if (embedder !== undefined && embedder.dimensions !== generation.dim) { + throw rebuildRequired(ctx.source.id, this.dropSql(ctx.source.id)); + } + return generation; + } + + /** The SQL that drops everything this store holds for a source, so it can be built afresh. */ + private dropSql(sourceId: string): string { + const literal = `'${sourceId.replace(/'/g, "''")}'`; + return ( + `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = ${literal}; ` + + `and from each ${qualified(this.schema, 'knowledge_vec_d')} table, DELETE ... WHERE source_id = ${literal};` + ); + } + + private async transaction(work: (client: PgClientLike) => Promise): Promise { + const client = await this.requirePool().connect(); + try { + await client.query('BEGIN'); + await work(client); + await client.query('COMMIT'); + client.release(); + } catch (err) { + await client.query('ROLLBACK').catch(() => undefined); + client.release(err instanceof Error ? err : true); + throw err; + } + } +} + +/** The passages of a document: the service's `chunks`, or the whole text as one. Empty passages are not stored. */ +function passagesOf(doc: KnowledgeDocument): Array<{ id: string; content: string; headingPath?: string[] }> { + const passages: Array<{ id: string; content: string; headingPath?: string[] }> = + doc.chunks ?? [{ id: `${doc.id}#0`, content: doc.content }]; + return passages + .filter((p) => p.content.trim() !== '') + .map((p) => ({ id: p.id, content: p.content, ...(p.headingPath === undefined ? {} : { headingPath: p.headingPath }) })); +} + +/** The hash of the text the adapter embeds for a passage. */ +function chunkHash(text: string): string { + return `c1:${createHash('sha256').update(text).digest('hex')}`; +} + +function requireIndex(ctx: AdapterContext, member: string): NonNullable { + if (ctx.index === undefined) { + throw new Error(`${member}: the call carries no index fingerprint (ctx.index); it is made by the knowledge service.`); + } + return ctx.index; +} + +function rebuildRequired(sourceId: string, dropSql: string): Error { + return Object.assign( + new Error( + `Knowledge source '${sourceId}' needs a rebuild: its index was built under another fingerprint (embedding ` + + 'model, dimensions, split or content recipe changed), and its stored vectors are not compared with new ' + + `ones. Run a complete reindex of the source; if the store refuses to begin it, drop its index first: ${dropSql}`, + ), + { code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }, + ); +} + +function notReady(reason: string, sql: string[]): Error { + const remedy = sql.length === 0 ? '' : ` Run as a database owner, then retry (no restart needed):\n${sql.join('\n')}`; + return Object.assign(new Error(`knowledge-pgvector is not ready: ${reason}${remedy}`), { + code: 'SERVICE_UNAVAILABLE', + status: 503, + }); +} + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} diff --git a/packages/plugins/knowledge-pgvector/src/plugin.ts b/packages/plugins/knowledge-pgvector/src/plugin.ts new file mode 100644 index 00000000000..557daea5ec9 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/plugin.ts @@ -0,0 +1,169 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import pg from 'pg'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import type { IEmbedder, IKnowledgeService } from '@objectstack/spec/contracts'; +import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { PgvectorKnowledgeAdapter, type PgPoolLike } from './pgvector-adapter.js'; + +/** Options of {@link KnowledgePgvectorPlugin}. */ +export interface KnowledgePgvectorPluginOptions { + /** Adapter id, the value of `KnowledgeSource.adapter`. @default 'pgvector' */ + id?: string; + /** + * The PostgreSQL URL of the store. Absent: the platform database's URL + * (`OS_DATABASE_URL`, else the legacy `DATABASE_URL`) when it is a + * PostgreSQL one. Absent both, the adapter registers and answers every call + * `SERVICE_UNAVAILABLE`, saying so. + */ + url?: string; + /** The schema the store's tables live in. @default 'os_knowledge' */ + schema?: string; + /** Connections in the store's own pool. @default 4 */ + poolMax?: number; + /** Text put before every query before it is embedded (see the adapter's option). */ + queryPrefix?: string; + /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ + embedder?: IEmbedder; + /** The environment the URL is read from. @default process.env */ + env?: Record; +} + +/** The PostgreSQL URL the store connects to, and where it was read from. */ +export function resolveStoreUrl( + opts: Pick, +): { url: string; from: string } | { url?: undefined; reason: string } { + if (opts.url !== undefined && opts.url.trim() !== '') { + const url = opts.url.trim(); + if (!isPostgresUrl(url)) { + return { reason: "its `url` option is not a postgres:// or postgresql:// URL." }; + } + return { url, from: 'the plugin option `url`' }; + } + const env = opts.env ?? process.env; + for (const name of ['OS_DATABASE_URL', 'DATABASE_URL']) { + const value = env[name]?.trim(); + if (!value) continue; + if (isPostgresUrl(value)) return { url: value, from: name }; + return { + reason: + `the platform database (${name}) is not PostgreSQL, and the plugin was given no \`url\` of a PostgreSQL ` + + 'database with the pgvector extension.', + }; + } + return { reason: 'it was given no `url`, and the platform database URL (OS_DATABASE_URL) is not set.' }; +} + +function isPostgresUrl(url: string): boolean { + return /^postgres(ql)?:\/\//i.test(url); +} + +/** A `pg.Pool` seen as the adapter's {@link PgPoolLike}. */ +export function poolFromPg(pool: pg.Pool): PgPoolLike { + return { + query: async (text: string, params?: unknown[]) => { + const result = await pool.query(text, params as unknown[] | undefined); + return { rows: result.rows as R[] }; + }, + connect: async () => { + const client = await pool.connect(); + return { + query: async (text: string, params?: unknown[]) => { + const result = await client.query(text, params as unknown[] | undefined); + return { rows: result.rows as R[] }; + }, + release: (err?: Error | boolean) => client.release(err), + }; + }, + }; +} + +/** + * `KnowledgePgvectorPlugin` — registers a {@link PgvectorKnowledgeAdapter} + * with the host's `IKnowledgeService` during `start()`. + * + * It opens a small pool of its own (`poolMax`, default 4) to the store's + * database: the platform database when that is PostgreSQL, else the `url` it + * is given. When the database cannot hold the store yet (no pgvector + * extension, no right to create it or the schema) the adapter still + * registers: boot continues, the warning names the SQL to run, its + * `healthCheck` answers `ok: false`, and every call answers + * `SERVICE_UNAVAILABLE` until the SQL has been run. + * + * With separate databases per organization, the store is in the ONE database + * this plugin connects to — the platform's, not each organization's — and + * organizations are kept apart by the `organization_id` column, which every + * search filters on. + */ +export class KnowledgePgvectorPlugin implements Plugin { + name = 'com.objectstack.plugin.knowledge-pgvector'; + version = '0.1.0'; + type = 'standard' as const; + + private readonly opts: KnowledgePgvectorPluginOptions; + private pool?: pg.Pool; + private embedderService?: IEmbedder; + + constructor(opts: KnowledgePgvectorPluginOptions = {}) { + this.opts = opts; + } + + async init(_ctx: PluginContext): Promise { + // No-op: registration happens in start() once IKnowledgeService is up. + } + + async start(ctx: PluginContext): Promise { + let svc: IKnowledgeService | undefined; + try { + svc = ctx.getService(KNOWLEDGE_SERVICE); + } catch { + ctx.logger.warn?.( + 'KnowledgePgvectorPlugin: IKnowledgeService not registered — install KnowledgeServicePlugin first.', + ); + return; + } + + const target = resolveStoreUrl(this.opts); + if (target.url !== undefined) { + this.pool = new pg.Pool({ connectionString: target.url, max: this.opts.poolMax ?? 4 }); + // An idle connection's error (the server restarted) must not end the process. + this.pool.on('error', (err) => ctx.logger.warn?.(`KnowledgePgvectorPlugin: idle connection error: ${err.message}`)); + } + + const embedder = (): IEmbedder | undefined => { + if (this.opts.embedder) return this.opts.embedder; + if (this.embedderService) return this.embedderService; + try { + this.embedderService = ctx.getService(EMBEDDER_SERVICE); + } catch { + return undefined; + } + return this.embedderService; + }; + + const adapter = new PgvectorKnowledgeAdapter({ + id: this.opts.id, + ...(this.pool ? { pool: poolFromPg(this.pool) } : { unavailable: target.url === undefined ? target.reason : undefined }), + embedder, + schema: this.opts.schema, + queryPrefix: this.opts.queryPrefix, + }); + svc.registerAdapter(adapter.id, adapter); + + const health = await adapter.healthCheck(); + if (health.ok) { + ctx.logger.info?.(`KnowledgePgvectorPlugin: adapter '${adapter.id}' registered (${health.message}).`); + } else { + ctx.logger.warn?.( + `KnowledgePgvectorPlugin: adapter '${adapter.id}' registered but not ready; its sources answer ` + + `SERVICE_UNAVAILABLE until this is fixed. ${health.message ?? ''}`, + ); + } + } + + async destroy(): Promise { + const pool = this.pool; + this.pool = undefined; + await pool?.end(); + } +} diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts new file mode 100644 index 00000000000..e30000a1a78 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -0,0 +1,88 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The SQL of the pgvector store: its schema, its two kinds of table, and the + * statements the adapter runs. Identifiers are inlined (PostgreSQL cannot bind + * one) and so are held to {@link SAFE_IDENTIFIER} before they reach a string; + * every value is a bind parameter. + */ + +/** A lower-case PostgreSQL identifier this module inlines: a schema name. */ +export const SAFE_IDENTIFIER = /^[a-z_][a-z0-9_]{0,62}$/; + +/** + * The schema the store's tables live in, unless the plugin is given another. + * A schema of its own, never the platform's: object tables live in the + * connection's `search_path` schema (`current_schema()`), and the platform's + * schema-drift readings (`os migrate plan`, the driver's introspection) read + * that schema only — so a table here can neither collide with an object table + * nor be reported as drift. + */ +export const DEFAULT_KNOWLEDGE_SCHEMA = 'os_knowledge'; + +/** The generation table: one row per generation of a source. */ +export const GENERATION_TABLE = 'knowledge_generation'; + +/** The passage table of one vector width: `knowledge_vec_d`. */ +export function vectorTable(dimensions: number): string { + if (!Number.isInteger(dimensions) || dimensions < 1) { + throw new RangeError(`knowledge-pgvector: vector dimensions must be a positive integer, got ${String(dimensions)}`); + } + return `knowledge_vec_d${dimensions}`; +} + +/** `"schema"."table"`, for an identifier already held to {@link SAFE_IDENTIFIER}. */ +export function qualified(schema: string, table: string): string { + return `"${schema}"."${table}"`; +} + +/** The statements that make the store's schema and its generation table. */ +export function schemaDdl(schema: string): string[] { + return [ + `CREATE SCHEMA IF NOT EXISTS "${schema}"`, + `CREATE TABLE IF NOT EXISTS ${qualified(schema, GENERATION_TABLE)} ( + source_id text NOT NULL, + generation integer NOT NULL, + fingerprint text, + recipe_hash text, + dim integer NOT NULL, + model text, + state text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (source_id, generation) +)`, + ]; +} + +/** + * The statements that make the passage table of one width. `vectorType` is + * the extension's `vector` type, qualified with the schema the extension is + * installed in. + */ +export function vectorTableDdl(schema: string, dimensions: number, vectorType: string): string[] { + const table = vectorTable(dimensions); + return [ + `CREATE TABLE IF NOT EXISTS ${qualified(schema, table)} ( + source_id text NOT NULL, + generation integer NOT NULL, + chunk_id text NOT NULL, + document_id text NOT NULL, + source_record_id text, + organization_id text, + content text NOT NULL, + title text, + heading_path jsonb, + doc_hash text, + chunk_hash text NOT NULL, + metadata jsonb NOT NULL DEFAULT '{}'::jsonb, + embedding ${vectorType}(${dimensions}) NOT NULL, + PRIMARY KEY (source_id, generation, chunk_id) +)`, + `CREATE INDEX IF NOT EXISTS "${table}_document" ON ${qualified(schema, table)} (source_id, generation, document_id)`, + ]; +} + +/** The text a vector is bound as: pgvector's `[x,y,…]` literal. */ +export function vectorLiteral(vector: readonly number[]): string { + return `[${vector.map((x) => (Number.isFinite(x) ? String(x) : '0')).join(',')}]`; +} diff --git a/packages/plugins/knowledge-pgvector/tsconfig.json b/packages/plugins/knowledge-pgvector/tsconfig.json new file mode 100644 index 00000000000..db389588d2f --- /dev/null +++ b/packages/plugins/knowledge-pgvector/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "target": "ES2020", + // module re-set from the base's NodeNext: tsup bundles this package and it declares no "type": "module", so tsc resolves the way the bundler does. + "module": "ES2020", + "moduleResolution": "bundler", + "declaration": true, + "outDir": "./dist", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "forceConsistentCasingInFileNames": true, + "types": ["node"], + "rootDir": "./src" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/plugins/knowledge-pgvector/tsconfig.test.json b/packages/plugins/knowledge-pgvector/tsconfig.test.json new file mode 100644 index 00000000000..0e01c20f3c1 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/tsconfig.test.json @@ -0,0 +1,10 @@ +// The TEST-layer type-check program, the `packages/plugins/**` family's shape +// (see `../knowledge-memory/tsconfig.test.json` for the reasons, which hold +// here unchanged). Module semantics only, as vitest executes the tests; +// strictness, `paths` and `types` are all inherited from `tsconfig.json`. +// No `test-typecheck-debt.json` beside it: its absence is the zero. +{ + "extends": ["./tsconfig.json", "../../../tsconfig.test.base.json"], + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/plugins/knowledge-pgvector/vitest.config.ts b/packages/plugins/knowledge-pgvector/vitest.config.ts new file mode 100644 index 00000000000..4bf9c2f3d65 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/vitest.config.ts @@ -0,0 +1,68 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineConfig } from 'vitest/config'; +import path from 'path'; + +export default defineConfig({ + test: { + // A late console.* must not redden a green suite (#10374): vitest's worker + // forwards console output over RPC and discards the promise, and a write + // landing after teardown's rpcDone() snapshot is rejected into an unhandled + // error — a fully green run that exits 1. Disarming removes the mechanism. + // Mechanism + measured costs: examples/app-showcase/vitest.config.ts. + // Enforced repo-wide by scripts/check-console-intercept-disarm.mjs. + disableConsoleIntercept: true, + globals: true, + environment: 'node', + }, + resolve: { + alias: [ + // Subpath BEFORE the bare package: `@objectstack/core` is a PREFIX match with a + // FILE replacement, so without this entry it swallows the published `./logger` + // subpath and resolves it to `…/core/src/index.ts/logger` — ENOTDIR at run time. + // Pinned by the published-subpath rule in `scripts/check-test-source-alias.mjs`, + // which derives the population from `@objectstack/core`'s own `exports` map. + { 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\/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 + // of the hand-maintained list of the subpaths this package's tests happened + // to reach. A string `find` matches by PREFIX, so with a FILE replacement the + // bare `@objectstack/spec` entry also swallowed every published namespace the + // list had not reached — `cloud`, `integration` and `studio` among them — and + // resolved it to `…/spec/src/index.ts/`: `ENOTDIR`, at run time, from a + // config that reads as correct, naming whichever module performed the import + // rather than this table. + // + // spec's export map is UNIFORM — every published namespace is + // `src//index.ts`, with no FILE-shaped subpath of the kind + // `@objectstack/platform-objects/plugin` is — so one rule covers all of them + // and cannot go stale as tests reach new namespaces. Same shape as + // `packages/qa/downstream-contract` (PR #8129), `service-knowledge`, + // `service-settings` and `plugin-audit`; `packages/runtime` carries the pin + // over the rule (`src/spec-subpath-alias-coverage.pin.test.ts`). + // + // Kept from the enumeration because the reasons outlive it: `security` is + // reached transitively via `@objectstack/types` ([ADR-0105 D1] tenancy + // posture) and `shared` via `@objectstack/core`'s plural→singular fold + // (`pluralToSingular`, #7378). Neither is a reason to keep listing + // namespaces by hand. + { + find: /^@objectstack\/spec\/([a-z-]+)$/, + replacement: path.join(path.resolve(__dirname, '../..'), 'spec/src/$1/index.ts'), + }, + { find: /^@objectstack\/spec$/, replacement: path.resolve(__dirname, '../../spec/src/index.ts') }, + ], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bb4202367ba..ef7f262b0b3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1764,6 +1764,43 @@ importers: specifier: ^4.1.11 version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + packages/plugins/knowledge-pgvector: + dependencies: + '@objectstack/core': + specifier: workspace:* + version: link:../../core + '@objectstack/spec': + specifier: workspace:* + version: link:../../spec + pg: + specifier: ^8.23.1 + version: 8.23.1 + devDependencies: + '@objectstack/driver-sql': + specifier: workspace:* + version: link:../../drivers/driver-sql + '@objectstack/objectql': + specifier: workspace:* + version: link:../../objectql + '@objectstack/service-knowledge': + specifier: workspace:* + version: link:../../services/service-knowledge + '@types/node': + specifier: ^26.6.5 + version: 26.6.5 + '@types/pg': + specifier: ^8.15.6 + version: 8.23.1 + tsx: + specifier: ^4.23.15 + version: 4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6) + typescript: + specifier: ^6.0.3 + version: 6.0.3 + vitest: + specifier: ^4.1.11 + version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1)) + packages/plugins/knowledge-ragflow: dependencies: '@objectstack/core': From 2dda2561694b64a4fcef7c906cf4a717c7cbb174 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:22:49 +0000 Subject: [PATCH 04/11] wip(knowledge-pgvector): ledger, docs, CI step, changeset --- .changeset/37100-knowledge-pgvector.md | 21 +++ .github/workflows/ci.yml | 34 ++++- content/docs/ai/knowledge-rag.mdx | 22 ++- content/docs/protocol/knowledge.mdx | 134 ++++++++++++++++-- .../docs/references/api/automation-api.mdx | 3 +- content/docs/references/api/contract.mdx | 3 +- .../docs/references/api/error-code-ledger.mdx | 1 + .../src/__tests__/openai-embedder.test.ts | 10 ++ packages/plugins/embedder-openai/src/index.ts | 8 +- packages/plugins/knowledge-pgvector/README.md | 76 ++++++++++ packages/spec/api-surface/contracts.json | 2 + packages/spec/export-origins/contracts.json | 2 + .../spec/src/api/error-code-ledger.zod.ts | 14 ++ 13 files changed, 310 insertions(+), 20 deletions(-) create mode 100644 .changeset/37100-knowledge-pgvector.md create mode 100644 packages/plugins/knowledge-pgvector/README.md diff --git a/.changeset/37100-knowledge-pgvector.md b/.changeset/37100-knowledge-pgvector.md new file mode 100644 index 00000000000..15d8db90ae4 --- /dev/null +++ b/.changeset/37100-knowledge-pgvector.md @@ -0,0 +1,21 @@ +--- +'@objectstack/knowledge-pgvector': patch +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-memory': patch +'@objectstack/embedder-openai': patch +--- + +feat(knowledge): an open vector store on PostgreSQL with pgvector, and the index fingerprint every knowledge index is built under + +Clause-②: yes +Metadata-protocol: none + +ADR-0161 Execution row 8a and K8 item 8 (#37100). + +- **New package `@objectstack/knowledge-pgvector`.** `KnowledgePgvectorPlugin` registers a `PgvectorKnowledgeAdapter` (adapter id `pgvector`): passages and vectors in PostgreSQL with the pgvector extension, in a schema of its own (`os_knowledge`, option `schema`) — a generation table `knowledge_generation` and one passage table per vector width, `knowledge_vec_d` — so no table collides with an object table or is read as schema drift. The database is the platform's when `OS_DATABASE_URL` is PostgreSQL, else the `url` option; the plugin keeps its own small pool (`poolMax`, default 4) and no pooled connection waits on the embedder. Search is an exact cosine scan (a 3072-wide model works); the organization filter and the metadata `filter` run in the same `WHERE`, before ranking. A passage whose text is unchanged is not embedded again. `queryPrefix` is put before every query before it is embedded. Without the `vector` extension, or the right to create it or the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL to run, `healthCheck` answers `ok: false`, and every call answers `503 SERVICE_UNAVAILABLE` naming that SQL until it has run. The store does not yet build a second generation beside the first: `beginBuild` under a new fingerprint is refused with the SQL that clears the source. An approximate (HNSW) index is an operator's step, documented with the package. +- **The index fingerprint (ADR-0161 K7).** The knowledge service computes, per source and adapter, a fingerprint over the embedding model and dimensions the adapter reports, the resolved split and the splitter's version, and the content recipe; and a recipe hash over `where`, `metadataFields`, the title rule and the withheld fields. New exports from `@objectstack/service-knowledge`: `computeIndexFingerprint`, `computeRecipeHash`, `indexExpectation`, `INDEX_FINGERPRINT_VERSION`, `RECIPE_HASH_VERSION`, `ASSEMBLY_RULE_VERSION`, `TITLE_RULE_VERSION`, `SPLIT_ALGORITHM_VERSION`. Every adapter call carries them: `AdapterContext.index` and `AdapterSearchOptions.index` (`@objectstack/spec/contracts`). +- **Adapter contract members (all optional).** `AdapterEmbeddingDescriptor` gains `model`, `dimensions` and `variant`; `IKnowledgeAdapter` gains `indexStatus`, and `beginBuild` / `completeBuild` as a pair: a complete reindex calls `beginBuild` before it lists or writes, and `completeBuild` once every row is written and the purge is done. `IEmbedder` gains `model`; `OpenAIEmbedder` reports the model it sends. +- **A refused source is named, never read as empty.** A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger). `KnowledgeService.search` over several sources answers from the searchable ones and logs each refused one; it throws the refusal (code, status, and `refused` naming every source) only when none could be searched. `KnowledgeService.searchWithRefusals` returns both, and the `search_knowledge` tool adds `refused` to its output when a source is refused. +- **`knowledge-memory` is the reference.** It keeps an active generation and, while a build of another fingerprint runs, one under construction, switching at `completeBuild`. +- **Contract suite.** `runKnowledgeAdapterContract`'s `implements` gains `indexStatus`, `builds`, `refusesOtherFingerprint` and `generations`, with cases for each. `knowledge-pgvector` runs the suite, the card's acceptance cases and a complete reindex over a real ObjectQL + SqlDriver against a live PostgreSQL in the `Temporal Conformance` job. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8aea0d1764..f602ef99fda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -794,6 +794,10 @@ jobs: # be added here by hand), and this file. temporal_live: - 'packages/plugins/knowledge-pgvector/**' + # [#37100] The adapter contract suite the pgvector store runs + # against the live PostgreSQL: a change to it is a change to that + # step's verdict. + - 'packages/services/service-knowledge/src/testing.ts' - 'packages/drivers/driver-sql/**' - 'packages/metadata-protocol/src/**/*live-mysql*' - 'packages/metadata-protocol/src/**/*live-postgres*' @@ -2568,11 +2572,11 @@ jobs: ${{ runner.os }}-turbo-build-core-${{ github.ref_name }}- ${{ runner.os }}-turbo-build-core- - # Turbo remote cache (#22077), on all four of this job's build steps: the + # Turbo remote cache (#22077), on all five of this job's build steps: the # four TURBO_* lines are Build Core's, verbatim, and Build Core's "Turbo # remote cache (#21186)" comment holds the write rule, the signing and the # PINS. Each of these plans is all `build` tasks with Build Core's hashes - # (8, 18, 14 and 31 nodes, measured). The suites between them run vitest + # (8, 18, 14, 31 and 20 nodes, measured). The suites between them run vitest # through `pnpm --filter`, not turbo, and carry no credentials. - name: Build driver-sql and its dependencies env: @@ -2798,6 +2802,32 @@ jobs: pnpm --filter @objectstack/runtime exec vitest run --project local \ cascade-delete-multivalue-lookup-real-driver + # ── The pgvector knowledge store, on the live PostgreSQL (#37100) ── + # + # The service image above is pgvector's for this package: the + # `IKnowledgeAdapter` contract suite (`@objectstack/service-knowledge/testing`), + # the card's acceptance cases (a 3072-wide model, two organizations, no + # re-embedding, a refused fingerprint) and a complete reindex over a real + # ObjectQL + SqlDriver, each in a schema of its own. Without a URL these + # files are a named skip; the flag turns that into a red, as on the legs + # above. The positional is a SUBSTRING, not a glob (see the + # metadata-protocol step): it selects the three `*.live-postgres.test.ts` + # files; the unit file runs in Test Core. + - name: Build knowledge-pgvector and its dependencies + env: + TURBO_CACHE: ${{ (github.event_name == 'merge_group' || ((github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main')) && 'local:rw,remote:rw' || 'local:rw,remote:r' }} + TURBO_TOKEN: ${{ (github.event_name == 'merge_group' || github.ref == 'refs/heads/main') && secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY != '' && secrets.TURBO_TOKEN || '' }} + TURBO_TEAM: ${{ vars.TURBO_TEAM }} + TURBO_REMOTE_CACHE_SIGNATURE_KEY: ${{ (github.event_name == 'merge_group' || github.ref == 'refs/heads/main') && secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY || '' }} + run: pnpm exec turbo run build --filter=@objectstack/knowledge-pgvector... --concurrency=4 + + - name: Run the pgvector knowledge store against live PostgreSQL + env: + OS_TEST_POSTGRES_URL: postgres://postgres:postgres@127.0.0.1:5432/postgres + OS_EXPECT_LIVE_DIALECT_MATRIX: '1' + run: | + pnpm --filter @objectstack/knowledge-pgvector exec vitest run live-postgres + dogfood: # Sharded 3-way: the suite is ~60 independent test files, each booting its # own in-process app; a single 4-vCPU runner needed ~7½ minutes for the diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 2edce821cd2..3bf075de88e 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -9,7 +9,7 @@ Part of the [AI module](/docs/ai) — how agents retrieve knowledge through the ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable backends (RAGFlow, LlamaIndex, Dify, custom pgvector, …) with one call: `KnowledgeService.search(query, { sourceIds?, topK? })`. The framework defines the contract and runs permission-aware filtering; the adapter plugin does the actual retrieval. See [the protocol design](/docs/protocol/knowledge) for the rationale. -**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge). +**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`, `@objectstack/knowledge-pgvector`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge). ## Wiring @@ -112,6 +112,7 @@ Every embedding model accepts a text up to some length, counted in tokens. A pro - The limit comes from the known-model table, which carries each provider's documented per-input limit (OpenAI `text-embedding-3-*` 8192, DashScope `text-embedding-v3` 8192, BigModel `embedding-3` 3072, SiliconFlow `BAAI/bge-m3` 8192, `BAAI/bge-large-*-v1.5` 512, …). Set `maxInputTokens` to override it. - A model that is not in the table, with no `maxInputTokens`, has no limit — its inputs are sent at any length — and the embedder warns once when it is constructed. - The embedder reports the limit it applies as `maxInputTokens` (`IEmbedder.maxInputTokens`), so a knowledge adapter can pass it on (`embedding.maxInputTokens`) and the service's passages fit it. +- It reports the model it sends as `model` (`IEmbedder.model`), so a knowledge adapter can pass it on (`embedding.model`) and the index fingerprint sees a model change. ```ts new OpenAIEmbedder({ @@ -139,6 +140,25 @@ The sum is multiplied by 1.1 and rounded up. On the sampled classes — Chinese, Known residual: text made mostly of random hex or base64 — UUIDs, sha256 digests, encoded blobs — tokenizes at about 1–1.4 characters per token and can estimate below its real count. Emoji and rare ideographs (CJK Extension B and later) may also estimate low: `cl100k` spends two to four tokens on each. Other providers' tokenizers are not sampled. +## When the model or the split changes: rebuild + +Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and checks on every write and every search. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint). + +## Self-hosted vector store: PostgreSQL + pgvector + +`@objectstack/knowledge-pgvector` keeps passages and vectors in PostgreSQL with the pgvector extension — the platform database when that is PostgreSQL, else a `url` you give it — in a schema of its own (`os_knowledge`), so nothing collides with your objects' tables. Register it beside the knowledge service and point a source at it with `adapter: 'pgvector'`: + +```ts +new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */ }), +``` + +- It searches by an exact scan, so a 3072-wide model works; the organization filter and the metadata `filter` run in SQL before ranking. +- An unchanged passage is not sent to the embedder again on a reindex. +- Without the `vector` extension (or the right to create it), boot goes on: the plugin warns with the SQL a database owner runs, and its sources answer `SERVICE_UNAVAILABLE` until then. +- It stores each passage's text, which is as sensitive as the record it came from and is in every backup. + +Details — the tables, an approximate index as an operator's step, rebuilds — are in [the protocol's pgvector section](/docs/protocol/knowledge#41-knowledge-pgvector--the-open-vector-store-on-postgresql). + ## Why we did not build a vector DB Mature OSS (RAGFlow, LlamaIndex, Dify) already nail embedding, hybrid retrieval, rerank, and OCR. ObjectStack's value is **the metadata-native source declaration, one structural split for every adapter, and the permission-aware filter on top of those engines** — not yet-another-RAG-stack. Customers pick the retrieval engine that matches their data; we make sure it talks to ObjectStack the same way every time. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 11764f95a80..72b6700a371 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -82,9 +82,9 @@ delegates the rest to plugins. │ • Search router → adapter.search │ │ (dev/test only) │ │ • Permission wrapper (RLS filter) │ │ • knowledge-ragflow │ │ • Event sync (record.* → upsert) │ │ (reference impl, REST) │ -│ • Audit + metrics │ │ │ -│ │ │ (llamaindex / dify / │ -│ Registers `knowledge` service │ │ pgvector: planned) │ +│ • Audit + metrics │ │ • knowledge-pgvector │ +│ │ │ (PostgreSQL + pgvector) │ +│ Registers `knowledge` service │ │ (llamaindex / dify: planned)│ └──────────────────────────────────────┘ └──────────────────────────────┘ ▲ │ consumes @@ -258,7 +258,10 @@ and [3.5 The split](#35-the-split). interface IKnowledgeAdapter { readonly id: string; readonly capabilities?: { chunks?: boolean }; // takes the service's passages - readonly embedding?: { maxInputTokens?: number }; // what its embedder accepts + readonly embedding?: { // what its embedder is + maxInputTokens?: number; // longest input it accepts + model?: string; dimensions?: number; variant?: string; // what its vectors are + }; upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; search(query: string, opts: AdapterSearchOptions): Promise; delete(documentIds: string[], ctx: AdapterContext): Promise; @@ -266,6 +269,9 @@ interface IKnowledgeAdapter { ctx: AdapterContext, opts: { cursor?: string; limit: number }, ): Promise<{ documents: { documentId: string; docHash?: string }[]; nextCursor?: string }>; + indexStatus?(ctx: AdapterContext): Promise<{ fingerprint?: string; recipeHash?: string; building?: boolean }>; + beginBuild?(ctx: AdapterContext): Promise; // with completeBuild, as a pair + completeBuild?(ctx: AdapterContext): Promise; healthCheck?(): Promise<{ ok: boolean; message?: string }>; } ``` @@ -293,6 +299,8 @@ 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. +`indexStatus`, `beginBuild` and `completeBuild` carry the index fingerprint — +see [§3.6](#36-the-index-fingerprint). **The contract test suite.** Every adapter package runs the same suite against its own factory: @@ -303,7 +311,10 @@ import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/test runKnowledgeAdapterContract({ name: 'my-adapter', makeAdapter: () => new MyAdapter(/* a fresh, empty store */), - implements: { listDocuments: true, chunks: true, organizationIds: true }, + implements: { + listDocuments: true, chunks: true, organizationIds: true, + indexStatus: true, builds: true, refusesOtherFingerprint: true, generations: true, + }, }); ``` @@ -313,10 +324,14 @@ It covers upsert / search / delete, `listDocuments` page boundaries and organization under `isolated` and `group`, and the chunk channel: an adapter that takes chunks receives the service's passages and indexes them unchanged, one that does not keeps receiving whole documents, and a `whole` document over -the embedder's budget is removed and reported. `implements` declares the optional members, and the suite +the embedder's budget is removed and reported; and the index fingerprint of +§3.6 — that every call carries one, that a write or a search under another +is refused by code, a complete reindex as one build, and, for an adapter that +keeps generations, the switch at the end of a build. `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. +`knowledge-memory` runs it as the reference implementation; `knowledge-pgvector` +runs it against a live PostgreSQL in CI. ### 3.5 The split @@ -366,12 +381,54 @@ The estimate runs high on purpose — on Chinese text about 1.4× a real tokenizer — so a `whole` document's usable length is about **60%** of the model's limit; choose `recursive` or `markdown` for longer documents. -**What a split change does not yet do.** `docHash` covers the assembled -document, not its passages, so changing `split`, `chunk_target` or the -embedder's limit does not by itself make a complete reindex rewrite an -unchanged document: a document is re-split the next time its content, title or -metadata changes. The index fingerprint (ADR-0161 K7), which hashes the -resolved split, is what will rebuild a source when its split changes. +**A split change is a new index.** `docHash` covers the assembled document, +not its passages, so the skip alone would keep an unchanged document under +its old passages. The index fingerprint (§3.6) hashes the resolved split, so +changing `split`, `chunk_target` or the embedder's limit changes the +fingerprint: the source's stored index is refused until a complete reindex +rebuilds it. + +### 3.6 The index fingerprint + +Vectors from two embedding models — or from two splits of the same text — +are not comparable, and ranking one against the other answers with noise +that looks like an answer (ADR-0161 K7). So every index is built under one +**fingerprint**, which the knowledge service computes and hands to the +adapter on every call (`AdapterContext.index`, `AdapterSearchOptions.index`): + +| Component | Read from | +|:--|:--| +| embedding model, `variant`, dimensions | the adapter's `embedding` descriptor — what it reports for the embedder it calls (`IEmbedder.model`, `IEmbedder.dimensions`) | +| split configuration and the splitter's version | the split the service applies, as resolved; absent for an adapter that splits for itself | +| content recipe | the object, the ordered content list, and the assembly rule's version | + +Beside it rides a **recipe hash** of what assembly reads but no vector +depends on: the source's `where`, its `metadataFields`, the title field and +the fields an index may not carry. Both are SHA-256 over values in a fixed +order, so the same source and the same adapter give the same hashes on every +machine; no key on a source sets either. An adapter that reports no +`embedding` descriptor gives the fingerprint no model, so a model change +cannot be seen for it. + +**What the adapter does with it.** A write or a search carrying a +fingerprint other than the one the source's stored index was built under is +refused `KNOWLEDGE_REBUILD_REQUIRED` (409), never written into or answered +from that index. A source that holds nothing takes the first fingerprint it +is handed. A complete reindex is one build: the service calls `beginBuild` +before it lists or writes anything, and `completeBuild` once every row is +written and the purge is done; `completeBuild` records the recipe hash, +which `indexStatus` reads back. An adapter that keeps **generations** +(`knowledge-memory` does) builds a new fingerprint's index beside the active +one and switches to it at `completeBuild`; until then the old one answers +its own fingerprint. An adapter that does not refuses `beginBuild` under a +new fingerprint and says how to clear the source so it can be built afresh. + +**What a caller sees.** `KnowledgeService.search` over several sources +answers from the sources it can search, and logs each refused one by name; it +throws the refusal (with its code and status, and `refused` naming every +source) only when no source could be searched. The `search_knowledge` tool +adds a `refused` list naming each refused source, so an agent never reads a +source that needs a rebuild as one with nothing to say. --- @@ -384,6 +441,7 @@ Adapters ship as standalone npm packages, registered via the standard import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; import { KnowledgeRagflowPlugin } from '@objectstack/knowledge-ragflow'; +import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector'; defineStack({ plugins: [ @@ -393,6 +451,7 @@ defineStack({ endpoint: process.env.RAGFLOW_URL!, apiKey: process.env.RAGFLOW_KEY!, }), + new KnowledgePgvectorPlugin(), // self-hosted, PostgreSQL + pgvector ], }); ``` @@ -411,6 +470,53 @@ Each plugin: Multiple adapters can co-exist; sources pick which one to use via the `adapter` field. +### 4.1 `knowledge-pgvector` — the open vector store on PostgreSQL + +`@objectstack/knowledge-pgvector` keeps a source's passages and vectors in +PostgreSQL with the [pgvector](https://github.com/pgvector/pgvector) +extension, for a self-hosted deployment that wants no separate vector +service. It takes the service's passages, embeds them with the kernel's +`embedder` service (or the `embedder` it is given), and answers a search by +an exact scan. + +- **Which database.** The platform database when that is PostgreSQL + (`OS_DATABASE_URL`), else the `url` option. Its own small pool (`poolMax`, + default 4); no pooled connection waits on the embedder. Where organizations + have databases of their own, the store is still the ONE database the + plugin connects to; organizations are kept apart by its + `organization_id` column, which every search filters on before ranking. +- **Where the tables are.** In their own schema, `os_knowledge` (option + `schema`): `knowledge_generation`, one row per source and fingerprint, and + one passage table per vector width, `knowledge_vec_d`. Object + tables live in the connection's own schema, and the platform's drift + checks read only that one — so no store table can collide with an object + table or be reported as drift. +- **When the database is not ready.** Without the `vector` extension — and + the right to create it — or the right to create the schema, the plugin + still registers and boot goes on: it creates nothing, warns with the SQL a + database owner runs (`CREATE EXTENSION IF NOT EXISTS vector;` and the + schema's DDL), `healthCheck` answers `ok: false`, and every call answers + `SERVICE_UNAVAILABLE` until the SQL has run. No restart is needed after. +- **Search.** An exact scan by cosine distance, so any width works — + including a 3072-wide model. The organization filter and the metadata + `filter` (equality per key) run in the same `WHERE`, before ranking. + `queryPrefix` is put before every query before it is embedded, for a model + that embeds questions and passages differently. +- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is + not embedded again; its row's metadata is rewritten. +- **Rebuilds.** A changed fingerprint is refused (§3.6). This store does not + yet build a second generation beside the first: `beginBuild` under a new + fingerprint is refused with the SQL that clears the source, after which a + complete reindex builds it afresh. +- **An approximate index is an operator's step.** The store creates no + HNSW or IVFFlat index; add one by hand when a table outgrows an exact scan + (`CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding + vector_cosine_ops);`). pgvector's HNSW index takes at most 2,000 + dimensions, so a 3072-wide table stays on the exact scan. +- **The text is stored.** Each row holds its passage's text: it is as + sensitive as the record it came from, and it is in every backup of the + database. + --- ## 5. Permission-aware retrieval (the unique value-add) @@ -712,7 +818,7 @@ up. | Audit + metrics | ⏳ Phase 2 | | | `knowledge-llamaindex` | ⏳ Phase 2 | | | `knowledge-dify` | ⏳ Phase 3 / community | | -| `knowledge-pgvector` | ⏳ Phase 3 | | +| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization and metadata filter in SQL, index fingerprint (§4.1) | ### 7.1 Non-goals for Phase 1 diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index fc99a77682c..554c7a82d89 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -425,7 +425,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +380 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +381 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -646,6 +646,7 @@ const result = AutomationApiErrorCode.parse(data); * `INVITE_SMS_FAILED` * `IP_NOT_ALLOWED` * `ITEM_LOCKED` +* `KNOWLEDGE_REBUILD_REQUIRED` * `LAST_LOCAL_CREDENTIAL` * `LEGACY_ORGANIZATION_ROWS_UNREADABLE` * `MANIFEST_CONFLICT` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 1660e81c3fc..6324c0f6581 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +380 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +381 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -256,6 +256,7 @@ const result = ApiErrorSchema.parse(data); * `INVITE_SMS_FAILED` * `IP_NOT_ALLOWED` * `ITEM_LOCKED` +* `KNOWLEDGE_REBUILD_REQUIRED` * `LAST_LOCAL_CREDENTIAL` * `LEGACY_ORGANIZATION_ROWS_UNREADABLE` * `MANIFEST_CONFLICT` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index 317cc7145ee..dbc5ec775a4 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -423,6 +423,7 @@ const result = ErrorCode.parse(data); * `INVITE_SMS_FAILED` * `IP_NOT_ALLOWED` * `ITEM_LOCKED` +* `KNOWLEDGE_REBUILD_REQUIRED` * `LAST_LOCAL_CREDENTIAL` * `LEGACY_ORGANIZATION_ROWS_UNREADABLE` * `MANIFEST_CONFLICT` diff --git a/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts b/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts index a23ea4c9af8..5fe1c39bdd9 100644 --- a/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts +++ b/packages/plugins/embedder-openai/src/__tests__/openai-embedder.test.ts @@ -28,6 +28,16 @@ describe('OpenAIEmbedder', () => { expect(e.dimensions).toBe(1536); }); + it('reports the model it sends as IEmbedder.model, for the knowledge index fingerprint (ADR-0161 K8, item 7)', async () => { + const fetchImpl = mockFetch({ data: [{ index: 0, embedding: [0.1, 0.2] }] }); + expect(new OpenAIEmbedder({ apiKey: 'k', fetch: fetchImpl }).model).toBe('text-embedding-3-small'); + const e = new OpenAIEmbedder({ apiKey: 'k', model: 'BAAI/bge-m3', fetch: fetchImpl }); + expect(e.model).toBe('BAAI/bge-m3'); + await e.embed(['x']); + const sent = JSON.parse(String((fetchImpl as unknown as ReturnType).mock.calls[0][1].body)); + expect(sent.model).toBe(e.model); + }); + it('looks up dimensions for known Chinese models', () => { const e = new OpenAIEmbedder({ apiKey: 'k', diff --git a/packages/plugins/embedder-openai/src/index.ts b/packages/plugins/embedder-openai/src/index.ts index 5244f8e12c5..08fb39e4d00 100644 --- a/packages/plugins/embedder-openai/src/index.ts +++ b/packages/plugins/embedder-openai/src/index.ts @@ -222,7 +222,13 @@ const KNOWN_DIMENSIONS: Record = { export class OpenAIEmbedder implements IEmbedder { readonly id: string; readonly dimensions: number; - private readonly model: string; + /** + * `IEmbedder.model`: the model this embedder sends in every request, as the + * provider names it (the `model` option, else `text-embedding-3-small`). A + * knowledge adapter reports it to the knowledge service, whose index + * fingerprint reads it (ADR-0161 K7; K8, item 7). + */ + readonly model: string; private readonly baseUrl: string; private readonly apiKey: string; private readonly fetchImpl: typeof fetch; diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md new file mode 100644 index 00000000000..60cc32d1d38 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/README.md @@ -0,0 +1,76 @@ +# @objectstack/knowledge-pgvector + +`IKnowledgeAdapter` on PostgreSQL with the [pgvector](https://github.com/pgvector/pgvector) extension — the open vector store for self-hosted ObjectStack deployments. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in PostgreSQL, and answers `search()` by an exact cosine scan. + +```ts +import { ObjectKernel } from '@objectstack/core'; +import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; +import { KnowledgePgvectorPlugin } from '@objectstack/knowledge-pgvector'; + +const kernel = new ObjectKernel(); +kernel.use(new KnowledgeServicePlugin({ + sources: [{ id: 'task_notes', label: 'Notes', adapter: 'pgvector', + source: { kind: 'object', object: 'task', contentFields: ['notes'] }}], +})); +kernel.use(new KnowledgePgvectorPlugin()); +``` + +## Options + +| Option | Default | | +|:--|:--|:--| +| `id` | `'pgvector'` | The adapter id a source names in `adapter`. | +| `url` | the platform database | A `postgres://` URL. Absent: `OS_DATABASE_URL` (else the legacy `DATABASE_URL`) when it is PostgreSQL. | +| `schema` | `'os_knowledge'` | The schema the store's tables live in. | +| `poolMax` | `4` | Connections in the store's own pool. | +| `queryPrefix` | `''` | Text put before every query before it is embedded (BGE's `'Represent this sentence for searching relevant passages: '`). Passages are embedded as they are. | +| `embedder` | the kernel's `embedder` service | The embedder to call. | + +## Which database, and where + +The store is in ONE database: the platform's when that is PostgreSQL, else the `url` given. Where organizations have databases of their own, the store is still that one database; organizations are kept apart by the `organization_id` column, which every search filters on in SQL before ranking. + +Its tables are in their own schema, `os_knowledge` — never the connection's own schema, where object tables live and which the platform's schema-drift checks read: + +- `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model. +- `knowledge_vec_d` — one passage table per vector width (`knowledge_vec_d1536`, `knowledge_vec_d3072`, …), created the first time a width is written. + +## Setup when the connection may not create them + +On boot the plugin creates the `vector` extension (if it is missing and the connection may), the schema and the generation table. When it cannot, the plugin still registers and boot goes on: it warns with the SQL to run, its `healthCheck` answers `ok: false`, and every call answers `SERVICE_UNAVAILABLE` until a database owner has run: + +```sql +CREATE EXTENSION IF NOT EXISTS vector; +CREATE SCHEMA IF NOT EXISTS "os_knowledge"; +-- and the generation table, as the warning prints it +``` + +The next call retries; no restart is needed. + +## An approximate index is an operator's step + +The store creates no approximate index: every search is an exact scan, which is right for small and medium sources and works at any width. When a table outgrows it, add an index by hand: + +```sql +CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding vector_cosine_ops); +``` + +pgvector's HNSW index takes at most 2,000 dimensions (`vector` type); a 3072-wide table stays on the exact scan. + +## Rebuilds + +Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors. This store does not yet build a second generation beside the first: when the fingerprint changes, a complete reindex is refused with the SQL that clears the source; run it, and reindex. + +A passage whose text is unchanged is not embedded again on a reindex. + +## What it stores + +Each row holds its passage's text, title and metadata as well as its vector: the text is as sensitive as the record it came from, and it is in every backup of the database. + +## Tests + +`pnpm test` runs the unit cases everywhere. The contract suite and the acceptance cases run against a live PostgreSQL with pgvector when `OS_TEST_POSTGRES_URL` is set (CI: the `Temporal Conformance` job's `pgvector/pgvector` service), each in a schema of its own. + +## License + +Apache-2.0. See [LICENSING.md](../../../LICENSING.md). diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index dbd0f4d45ea..bbc4d74a845 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -37,6 +37,8 @@ "AdapterCapabilities (interface)", "AdapterContext (interface)", "AdapterEmbeddingDescriptor (interface)", + "AdapterIndexExpectation (interface)", + "AdapterIndexStatus (interface)", "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index a95aa66d464..bddca730059 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -37,6 +37,8 @@ "AdapterCapabilities": "src/contracts/knowledge-adapter.ts#AdapterCapabilities (interface)", "AdapterContext": "src/contracts/knowledge-adapter.ts#AdapterContext (interface)", "AdapterEmbeddingDescriptor": "src/contracts/knowledge-adapter.ts#AdapterEmbeddingDescriptor (interface)", + "AdapterIndexExpectation": "src/contracts/knowledge-adapter.ts#AdapterIndexExpectation (interface)", + "AdapterIndexStatus": "src/contracts/knowledge-adapter.ts#AdapterIndexStatus (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)", diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 0384070c612..3f496f9c96a 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1656,6 +1656,20 @@ export const ERROR_CODE_LEDGER = { 'DATASOURCE_ADMIN_ERROR', // lifecycle/validation refusal from the datasource-admin service 'EXTERNAL_DATASOURCE_ERROR', // introspection/connection-test refusal from the external-datasource service ], + // [#37100] ADR-0161 K7 rules 4 and 5: a write or a search carrying an index + // fingerprint other than the one the source's stored generation was built + // under is refused 409 with this code, never served from or written into + // that generation. Stamped by each knowledge adapter that keeps generations, + // and asserted by name in the adapter contract suite (`./testing`). + '@objectstack/service-knowledge': [ + 'KNOWLEDGE_REBUILD_REQUIRED', + ], + '@objectstack/knowledge-memory': [ + 'KNOWLEDGE_REBUILD_REQUIRED', + ], + '@objectstack/knowledge-pgvector': [ + 'KNOWLEDGE_REBUILD_REQUIRED', + ], '@objectstack/plugin-audit': [ 'FEEDS_DISABLED', 'FILES_DISABLED', From bc2ea33e9d67a3c1cc3535f54ec26dbc89a449c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:33:12 +0000 Subject: [PATCH 05/11] test(knowledge-pgvector): the acceptance engine double serves find and count only --- .../src/__tests__/acceptance.live-postgres.test.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts index 651dcb4800b..e8630e0b526 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts @@ -219,9 +219,6 @@ function rowsEngine(rows: Array>) { const out = sorted.filter((r) => matches(r, query?.where)); return query?.limit === undefined ? out : out.slice(0, query.limit); }, - async findOne(_object: string, query: { where?: Record }) { - return sorted.find((r) => matches(r, query?.where)) ?? null; - }, async count(_object: string, query: { where?: Record }) { return sorted.filter((r) => matches(r, query?.where)).length; }, From 6faa37209efd8888b437184612c0e4ebf4e6c434 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:33:34 +0000 Subject: [PATCH 06/11] docs(spec): llms.txt counts the new knowledge-pgvector package --- packages/spec/llms.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 06d9b78d091..49428e2bcbc 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -178,9 +178,9 @@ function registerObject(rawConfig: unknown) { --- -## 7. Package Ecosystem (76 packages) +## 7. Package Ecosystem (77 packages) -The workspace publishes 76 packages under the `@objectstack` scope. The table +The workspace publishes 77 packages under the `@objectstack` scope. The table below is a curated entry-point list, not the full set — drivers, connectors, triggers, plugins and kernel-managed services each form their own family. From 41391b14d37e8bfec4e6a3dcac205e410d96d96d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:42:01 +0000 Subject: [PATCH 07/11] test(knowledge-pgvector): ObjectQL and SqlDriver resolve to source in the package's tests --- packages/plugins/knowledge-pgvector/vitest.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/plugins/knowledge-pgvector/vitest.config.ts b/packages/plugins/knowledge-pgvector/vitest.config.ts index 4bf9c2f3d65..e25cb0d3084 100644 --- a/packages/plugins/knowledge-pgvector/vitest.config.ts +++ b/packages/plugins/knowledge-pgvector/vitest.config.ts @@ -32,6 +32,9 @@ export default defineConfig({ find: /^@objectstack\/service-knowledge\/testing$/, replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'), }, + // The real-driver reindex case (#37100) runs ObjectQL over SqlDriver from source, as every other verdict here. + { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../../drivers/driver-sql/src/index.ts') }, + { find: /^@objectstack\/objectql$/, replacement: path.resolve(__dirname, '../../objectql/src/index.ts') }, { find: /^@objectstack\/service-knowledge$/, replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'), From b505ecc5dae2b115e229650a06532ce7d2d2a1b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:44:41 +0000 Subject: [PATCH 08/11] docs(permissions): the knowledge search elevation row names searchWithRefusals; memory delete reads a typed map --- content/docs/permissions/system-context.mdx | 4 ++-- packages/plugins/knowledge-memory/src/index.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 5fb41770505..abe6626504b 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -189,7 +189,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources`, `search` | +| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources`, `searchWithRefusals` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -703,7 +703,7 @@ and CI refuses one that differs from what the tree produces. | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | | `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | -| `packages/services/service-knowledge/src/knowledge-service.ts#search` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service.ts#searchWithRefusals` | 1 | 46 | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/packages/plugins/knowledge-memory/src/index.ts b/packages/plugins/knowledge-memory/src/index.ts index 7b402d269ac..1a688134c45 100644 --- a/packages/plugins/knowledge-memory/src/index.ts +++ b/packages/plugins/knowledge-memory/src/index.ts @@ -89,7 +89,8 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter { const index = this.store.get(ctx.source.id); for (const generation of [index?.active, index?.building]) { if (!generation) continue; - for (const id of documentIds) generation.docs.delete(id); + const docs: Map = generation.docs; + for (const id of documentIds) docs.delete(id); } } From 4ab06c2f0ab82479938696301e70d1ad0ef44435 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:01:12 +0000 Subject: [PATCH 09/11] test(service-knowledge): the refused-source cases type the mock implementation they wrap --- .../service-knowledge/src/__tests__/knowledge-tools.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index fa5cca40d44..3568718e25c 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -222,7 +222,7 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => { function twoSources(refusing: readonly string[], refusal: () => Error = rebuild) { const adapter = adapterWith({ policy_clauses: [hit('policy_clauses', 'p1', 0.9)], faq: [hit('faq', 'f1', 0.4)] }); const answer = adapter.search as unknown as ReturnType; - const inner = answer.getMockImplementation()!; + const inner = answer.getMockImplementation()! as (query: string, opts: { source: KnowledgeSource }) => Promise; answer.mockImplementation(async (query: string, opts: { source: KnowledgeSource }) => { if (refusing.includes(opts.source.id)) throw refusal(); return inner(query, opts); From 7027f4572d4534e19bd594ce1c04a7f2fed0e56d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:48:58 +0000 Subject: [PATCH 10/11] =?UTF-8?q?fix(knowledge-pgvector):=20review=20rewor?= =?UTF-8?q?k=20=E2=80=94=20embedder=20before=20fingerprint,=20exact=20clea?= =?UTF-8?q?r-the-source=20SQL,=20no=20adoption=20of=20leftovers,=20operato?= =?UTF-8?q?r=20text=20kept=20from=20callers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - search resolves the embedder before comparing fingerprints: no embedder is 503, never a 409 on a healthy index - the clear-the-source remedy is exact statements (each passage table, then the generation row); a first generation deletes passage rows left behind as it opens - refusal messages are one caller sentence; driver text and SQL travel in the error's remedy (healthCheck, boot warning, reindex result, log); an unreachable database is no longer reported as a missing extension - an unchanged passage whose row a concurrent write removed is planned again, not lost - the plugin reads the kernel embedder at each call and sets a connect timeout - service: reindex results carry the remedy; a source refused in the refill round is dropped whole; the chunk target is read once per search; indexExpectation exported - docs, README, changeset and contract TSDoc corrected (url precedence, generation key, shared-database schema) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbX5BF433x8ooJNQVRp --- .changeset/37100-knowledge-pgvector.md | 4 +- content/docs/ai/knowledge-rag.mdx | 4 +- content/docs/protocol/knowledge.mdx | 24 +- packages/plugins/knowledge-pgvector/README.md | 11 +- .../acceptance.live-postgres.test.ts | 100 ++++++- .../src/__tests__/not-ready.test.ts | 99 ++++++- .../src/pgvector-adapter.ts | 271 +++++++++++++----- .../plugins/knowledge-pgvector/src/plugin.ts | 35 ++- .../src/__tests__/knowledge-service.test.ts | 50 ++++ .../services/service-knowledge/src/index.ts | 1 + .../src/knowledge-service.ts | 66 +++-- .../spec/src/contracts/knowledge-adapter.ts | 16 +- 12 files changed, 549 insertions(+), 132 deletions(-) diff --git a/.changeset/37100-knowledge-pgvector.md b/.changeset/37100-knowledge-pgvector.md index 15d8db90ae4..7ca023b29d8 100644 --- a/.changeset/37100-knowledge-pgvector.md +++ b/.changeset/37100-knowledge-pgvector.md @@ -13,9 +13,9 @@ Metadata-protocol: none ADR-0161 Execution row 8a and K8 item 8 (#37100). -- **New package `@objectstack/knowledge-pgvector`.** `KnowledgePgvectorPlugin` registers a `PgvectorKnowledgeAdapter` (adapter id `pgvector`): passages and vectors in PostgreSQL with the pgvector extension, in a schema of its own (`os_knowledge`, option `schema`) — a generation table `knowledge_generation` and one passage table per vector width, `knowledge_vec_d` — so no table collides with an object table or is read as schema drift. The database is the platform's when `OS_DATABASE_URL` is PostgreSQL, else the `url` option; the plugin keeps its own small pool (`poolMax`, default 4) and no pooled connection waits on the embedder. Search is an exact cosine scan (a 3072-wide model works); the organization filter and the metadata `filter` run in the same `WHERE`, before ranking. A passage whose text is unchanged is not embedded again. `queryPrefix` is put before every query before it is embedded. Without the `vector` extension, or the right to create it or the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL to run, `healthCheck` answers `ok: false`, and every call answers `503 SERVICE_UNAVAILABLE` naming that SQL until it has run. The store does not yet build a second generation beside the first: `beginBuild` under a new fingerprint is refused with the SQL that clears the source. An approximate (HNSW) index is an operator's step, documented with the package. +- **New package `@objectstack/knowledge-pgvector`.** `KnowledgePgvectorPlugin` registers a `PgvectorKnowledgeAdapter` (adapter id `pgvector`): passages and vectors in PostgreSQL with the pgvector extension, in a schema of its own (`os_knowledge`, option `schema`) — a generation table `knowledge_generation` and one passage table per vector width, `knowledge_vec_d` — so no table collides with an object table or is read as schema drift. The database is the `url` option when given, else the platform's when `OS_DATABASE_URL` is PostgreSQL; the plugin keeps its own small pool (`poolMax`, default 4; `connectTimeoutMs`, default 5000, so an unreachable host does not hold boot), no pooled connection waits on the embedder, and the kernel's embedder is read at each call. Two deployments sharing one database set their own `schema`. Search is an exact cosine scan (a 3072-wide model works); the organization filter and the metadata `filter` run in the same `WHERE`, before ranking. A passage whose text is unchanged is not embedded again; one whose row a concurrent write removed is embedded and written, not lost. `queryPrefix` is put before every query before it is embedded. Without the `vector` extension, or the right to create it or the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL to run, `healthCheck` answers `ok: false` with that SQL, and every call answers `503 SERVICE_UNAVAILABLE` until it has run; a database it cannot reach is reported as unreachable, with no SQL. A caller reads one sentence; the driver's text and the SQL travel in the error's `remedy`, for the operator. The store does not yet build a second generation beside the first: `beginBuild` under a new fingerprint is refused, and the reindex result carries the exact statements that clear the source (passages, then the generation row); a first generation never takes over passage rows left behind. An approximate (HNSW) index is an operator's step, documented with the package. - **The index fingerprint (ADR-0161 K7).** The knowledge service computes, per source and adapter, a fingerprint over the embedding model and dimensions the adapter reports, the resolved split and the splitter's version, and the content recipe; and a recipe hash over `where`, `metadataFields`, the title rule and the withheld fields. New exports from `@objectstack/service-knowledge`: `computeIndexFingerprint`, `computeRecipeHash`, `indexExpectation`, `INDEX_FINGERPRINT_VERSION`, `RECIPE_HASH_VERSION`, `ASSEMBLY_RULE_VERSION`, `TITLE_RULE_VERSION`, `SPLIT_ALGORITHM_VERSION`. Every adapter call carries them: `AdapterContext.index` and `AdapterSearchOptions.index` (`@objectstack/spec/contracts`). - **Adapter contract members (all optional).** `AdapterEmbeddingDescriptor` gains `model`, `dimensions` and `variant`; `IKnowledgeAdapter` gains `indexStatus`, and `beginBuild` / `completeBuild` as a pair: a complete reindex calls `beginBuild` before it lists or writes, and `completeBuild` once every row is written and the purge is done. `IEmbedder` gains `model`; `OpenAIEmbedder` reports the model it sends. -- **A refused source is named, never read as empty.** A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger). `KnowledgeService.search` over several sources answers from the searchable ones and logs each refused one; it throws the refusal (code, status, and `refused` naming every source) only when none could be searched. `KnowledgeService.searchWithRefusals` returns both, and the `search_knowledge` tool adds `refused` to its output when a source is refused. +- **A refused source is named, never read as empty.** A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger). `KnowledgeService.search` over several sources answers from the searchable ones and logs each refused one with the adapter's `remedy`; a source that refuses the refill round is refused for the whole search, its first-round hits dropped; it throws the refusal (code, status, and `refused` naming every source) only when none could be searched. A caller is given the code and the adapter's one-sentence message, never its `remedy`; a reindex result carries the `remedy`. `KnowledgeService.searchWithRefusals` returns both, and the `search_knowledge` tool adds `refused` to its output when a source is refused. - **`knowledge-memory` is the reference.** It keeps an active generation and, while a build of another fingerprint runs, one under construction, switching at `completeBuild`. - **Contract suite.** `runKnowledgeAdapterContract`'s `implements` gains `indexStatus`, `builds`, `refusesOtherFingerprint` and `generations`, with cases for each. `knowledge-pgvector` runs the suite, the card's acceptance cases and a complete reindex over a real ObjectQL + SqlDriver against a live PostgreSQL in the `Temporal Conformance` job. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index b7c7c9c3dc1..7214c704c1d 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -161,11 +161,11 @@ Known residual: text made mostly of random hex or base64 — UUIDs, sha256 diges ## When the model or the split changes: rebuild -Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and checks on every write and every search. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint). +Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and carries on every write and every search, and the adapter checks against the index it holds. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint). ## Self-hosted vector store: PostgreSQL + pgvector -`@objectstack/knowledge-pgvector` keeps passages and vectors in PostgreSQL with the pgvector extension — the platform database when that is PostgreSQL, else a `url` you give it — in a schema of its own (`os_knowledge`), so nothing collides with your objects' tables. Register it beside the knowledge service and point a source at it with `adapter: 'pgvector'`: +`@objectstack/knowledge-pgvector` keeps passages and vectors in PostgreSQL with the pgvector extension — a `url` you give it, else the platform database when that is PostgreSQL — in a schema of its own (`os_knowledge`), so nothing collides with your objects' tables. Register it beside the knowledge service and point a source at it with `adapter: 'pgvector'`: ```ts new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */ }), diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index d476c355883..ad4aadbd35f 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -519,14 +519,16 @@ service. It takes the service's passages, embeds them with the kernel's `embedder` service (or the `embedder` it is given), and answers a search by an exact scan. -- **Which database.** The platform database when that is PostgreSQL - (`OS_DATABASE_URL`), else the `url` option. Its own small pool (`poolMax`, - default 4); no pooled connection waits on the embedder. Where organizations +- **Which database.** The `url` option when it is given, else the platform + database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool + (`poolMax`, default 4; a connection that takes more than + `connectTimeoutMs`, default 5000, fails); no pooled connection waits on the + embedder. Where organizations have databases of their own, the store is still the ONE database the plugin connects to; organizations are kept apart by its `organization_id` column, which every search filters on before ranking. - **Where the tables are.** In their own schema, `os_knowledge` (option - `schema`): `knowledge_generation`, one row per source and fingerprint, and + `schema`): `knowledge_generation`, one row per source and generation, and one passage table per vector width, `knowledge_vec_d`. Object tables live in the connection's own schema, and the platform's drift checks read only that one — so no store table can collide with an object @@ -535,8 +537,11 @@ an exact scan. the right to create it — or the right to create the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL a database owner runs (`CREATE EXTENSION IF NOT EXISTS vector;` and the - schema's DDL), `healthCheck` answers `ok: false`, and every call answers - `SERVICE_UNAVAILABLE` until the SQL has run. No restart is needed after. + schema's DDL), `healthCheck` answers `ok: false` with that SQL, and every + call answers `SERVICE_UNAVAILABLE` until the SQL has run. No restart is + needed after. A database it cannot reach is reported as unreachable, with + no SQL. A caller reads one sentence; the driver's text and the SQL go only + to the operator — the health check, the boot warning and the log. - **Search.** An exact scan by cosine distance, so any width works — including a 3072-wide model. The organization filter and the metadata `filter` (equality per key) run in the same `WHERE`, before ranking. @@ -546,8 +551,11 @@ an exact scan. not embedded again; its row's metadata is rewritten. - **Rebuilds.** A changed fingerprint is refused (§3.6). This store does not yet build a second generation beside the first: `beginBuild` under a new - fingerprint is refused with the SQL that clears the source, after which a - complete reindex builds it afresh. + fingerprint is refused, and the reindex result carries the exact + statements that clear the source — one `DELETE` per passage table, then + the generation row — after which a complete reindex builds it afresh. A + first generation never takes over passage rows left behind without a + generation row: they are deleted when it opens. - **An approximate index is an operator's step.** The store creates no HNSW or IVFFlat index; add one by hand when a table outgrows an exact scan (`CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 60cc32d1d38..ec7b9b480e1 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -23,21 +23,24 @@ kernel.use(new KnowledgePgvectorPlugin()); | `url` | the platform database | A `postgres://` URL. Absent: `OS_DATABASE_URL` (else the legacy `DATABASE_URL`) when it is PostgreSQL. | | `schema` | `'os_knowledge'` | The schema the store's tables live in. | | `poolMax` | `4` | Connections in the store's own pool. | +| `connectTimeoutMs` | `5000` | How long a new connection may take before it fails; boot waits on the store's first check. | | `queryPrefix` | `''` | Text put before every query before it is embedded (BGE's `'Represent this sentence for searching relevant passages: '`). Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call. | ## Which database, and where -The store is in ONE database: the platform's when that is PostgreSQL, else the `url` given. Where organizations have databases of their own, the store is still that one database; organizations are kept apart by the `organization_id` column, which every search filters on in SQL before ranking. +The store is in ONE database: the `url` given, else the platform's when that is PostgreSQL. Where organizations have databases of their own, the store is still that one database; organizations are kept apart by the `organization_id` column, which every search filters on in SQL before ranking. Its tables are in their own schema, `os_knowledge` — never the connection's own schema, where object tables live and which the platform's schema-drift checks read: - `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model. - `knowledge_vec_d` — one passage table per vector width (`knowledge_vec_d1536`, `knowledge_vec_d3072`, …), created the first time a width is written. +Rows are keyed by source id. Two deployments that share one database — staging and production, say — must each set their own `schema`, or a source id they both use would be one index. + ## Setup when the connection may not create them -On boot the plugin creates the `vector` extension (if it is missing and the connection may), the schema and the generation table. When it cannot, the plugin still registers and boot goes on: it warns with the SQL to run, its `healthCheck` answers `ok: false`, and every call answers `SERVICE_UNAVAILABLE` until a database owner has run: +On boot the plugin creates the `vector` extension (if it is missing and the connection may), the schema and the generation table. When it cannot, the plugin still registers and boot goes on: it warns with the SQL to run, its `healthCheck` answers `ok: false` with that SQL, and every call answers `SERVICE_UNAVAILABLE` (one sentence; the SQL and the driver's text go only to the health check, the boot warning and the log) until a database owner has run: ```sql CREATE EXTENSION IF NOT EXISTS vector; @@ -45,7 +48,7 @@ CREATE SCHEMA IF NOT EXISTS "os_knowledge"; -- and the generation table, as the warning prints it ``` -The next call retries; no restart is needed. +The next call retries; no restart is needed. A database the plugin cannot reach is reported as unreachable, with the driver's error and no SQL. ## An approximate index is an operator's step @@ -59,7 +62,7 @@ pgvector's HNSW index takes at most 2,000 dimensions (`vector` type); a 3072-wid ## Rebuilds -Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors. This store does not yet build a second generation beside the first: when the fingerprint changes, a complete reindex is refused with the SQL that clears the source; run it, and reindex. +Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors. This store does not yet build a second generation beside the first: when the fingerprint changes, a complete reindex is refused, and its result carries the exact statements that clear the source — one `DELETE` per passage table, then the generation row. Run them as printed, and reindex. A first generation never takes over passage rows left without a generation row: they are deleted when it opens, so deleting only the generation row cannot carry old vectors into the new index. A passage whose text is unchanged is not embedded again on a reindex. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts index e8630e0b526..07bec7cf942 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts @@ -4,8 +4,10 @@ * The acceptance cases of #37100 on a LIVE PostgreSQL with pgvector, beside * the contract suite: a 3072-wide model, two organizations that never see each * other's passages, an unchanged passage that is not embedded again, a changed - * fingerprint that is refused and never served, and the store's tables kept - * out of the connection's own schema. + * fingerprint that is refused and never served, the printed statements that + * clear a source run as printed, a first generation that never adopts rows left + * behind, a passage removed under a concurrent write that is not lost, and the + * store's tables kept out of the connection's own schema. */ import { afterAll, describe, expect, it } from 'vitest'; @@ -13,7 +15,7 @@ import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; import type { AdapterContext } from '@objectstack/spec/contracts'; import { KnowledgeService } from '@objectstack/service-knowledge'; import type { ExecutionContext } from '@objectstack/spec/kernel'; -import { KNOWLEDGE_REBUILD_REQUIRED } from '../index.js'; +import { KNOWLEDGE_REBUILD_REQUIRED, poolFromPg, type PgPoolLike } from '../index.js'; import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; requireLiveCell('knowledge-pgvector acceptance'); @@ -160,20 +162,108 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( ); expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); expect(refused?.message).toContain(s.id); + // The caller is told the source needs a rebuild, never the SQL. + expect(refused?.message).not.toContain('DELETE'); // A complete reindex under the new model is refused before anything is written, naming the SQL that clears the source. const rebuilt = await svc.reindexSource(s.id); expect(rebuilt.ok).toBe(false); expect(rebuilt.message).toContain('DELETE FROM'); }); + it('the printed statements clear the source exactly; run as printed, the next complete reindex embeds afresh', async () => { + const embedder = new FakeEmbedder(384, 'model-one'); + const adapter = store.adapter({ embedder }); + const schema = (adapter as unknown as { schema: string }).schema; + const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'granite quarry', status: 'published' }]) }); + svc.registerAdapter('under_test', adapter); + const s = source('svc_clear'); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + + embedder.model = 'model-two'; + const refused = await svc.reindexSource(s.id); + expect(refused.ok).toBe(false); + const statements = (refused.message ?? '').split('\n').filter((line) => line.startsWith('DELETE FROM')); + // Passages first, then the generation row; every table named exactly. + expect(statements).toEqual([ + `DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = '${s.id}';`, + `DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = '${s.id}';`, + ]); + for (const statement of statements) await store.pool().query(statement); + + const before = embedder.calls; + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + expect(embedder.calls).toBe(before + 1); + expect(await adapter.indexStatus({ source: s, reason: 'manual' })).toMatchObject({ fingerprint: expect.any(String) }); + expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1); + }); + + it('a first generation never adopts passages left behind: a generation row deleted alone does not carry its vectors over', async () => { + const embedder = new FakeEmbedder(384, 'model-one'); + const adapter = store.adapter({ embedder }); + const schema = (adapter as unknown as { schema: string }).schema; + const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'granite quarry', status: 'published' }]) }); + svc.registerAdapter('under_test', adapter); + const s = source('svc_leftover'); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 }); + + // Same width, another model; an operator deletes only the generation row. + embedder.model = 'model-two'; + await store.pool().query(`DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = $1`, [s.id]); + const before = embedder.calls; + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1, skipped: 0 }); + // The passage was embedded again under the new model: the old vector was not adopted. + expect(embedder.calls).toBe(before + 1); + expect(embedder.texts.slice(-1)).toEqual(['granite quarry']); + const rows = await store.pool().query<{ n: string }>( + `SELECT count(*) AS n FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1`, + [s.id], + ); + expect(Number(rows.rows[0].n)).toBe(1); + }); + + it('an unchanged passage removed by a concurrent write before this one commits is embedded and kept, not lost', async () => { + const embedder = new FakeEmbedder(); + const base = poolFromPg(store.pool()); + let interfere: (() => Promise) | undefined; + const pool: PgPoolLike = { + query: (text, params) => base.query(text, params), + connect: async () => { + // The concurrent write lands between this write's read of the stored + // hashes and its transaction. + const run = interfere; + interfere = undefined; + if (run) await run(); + return base.connect(); + }, + }; + const adapter = store.adapter({ embedder, pool }); + const schema = (adapter as unknown as { schema: string }).schema; + const s = source('race'); + await adapter.upsert([doc(s, '1', 'copper wire conducts heat')], ctx(s)); + expect(embedder.calls).toBe(1); + interfere = async () => { + await base.query(`DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1`, [s.id]); + }; + await adapter.upsert([doc(s, '1', 'copper wire conducts heat', { metadata: { status: 'archived' } })], ctx(s)); + expect(embedder.calls).toBe(2); + const [hit] = await adapter.search('copper', { source: s, topK: 1, index: { fingerprint: FP_A.fingerprint } }); + expect(hit).toMatchObject({ documentId: `${s.id}:1`, metadata: { status: 'archived' } }); + }); + it('beginBuild under another fingerprint is refused with the SQL that clears the source; under its own it is a no-op', async () => { const adapter = store.adapter(); const s = source('build'); await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A)); await expect(adapter.beginBuild(ctx(s, FP_A))).resolves.toBeUndefined(); - const err = await adapter.beginBuild(ctx(s, FP_B)).then(() => undefined, (e: unknown) => e as { code?: string; message?: string }); + const err = await adapter.beginBuild(ctx(s, FP_B)).then( + () => undefined, + (e: unknown) => e as { code?: string; message?: string; remedy?: string }, + ); expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); - expect(err?.message).toContain(`WHERE source_id = '${s.id}'`); + expect(err?.message).not.toContain('DELETE'); + expect(err?.remedy).toContain(`WHERE source_id = '${s.id}'`); // Nothing was served from, or written to, the stored generation under B. await expect(adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } })).rejects.toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts index fe1b7af0eec..e59e6802339 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts @@ -2,16 +2,17 @@ /** * Without a database that can hold the store, nothing is created, every call - * answers a readable `SERVICE_UNAVAILABLE` naming the SQL to run by hand, - * `healthCheck` answers `ok: false`, and boot goes on (card #37100). Runs - * everywhere: the database is a double that answers like PostgreSQL without - * the `vector` extension and without the right to create it. + * answers a readable `SERVICE_UNAVAILABLE` — one sentence for the caller, the + * SQL to run by hand in its operator `remedy` — `healthCheck` answers + * `ok: false` with that SQL, and boot goes on (card #37100). Runs everywhere: + * the database is a double that answers like PostgreSQL without the `vector` + * extension and without the right to create it. */ import { describe, expect, it, vi } from 'vitest'; import type { PluginContext } from '@objectstack/core'; import type { KnowledgeSource } from '@objectstack/spec/ai'; -import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; +import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; import { KnowledgePgvectorPlugin, PgvectorKnowledgeAdapter, @@ -53,13 +54,18 @@ describe('knowledge-pgvector when the database is not ready', () => { const err = await adapter.upsert([{ id: 'd1', sourceId: 's1', content: 'x' }], ctx).then( () => undefined, - (e: unknown) => e as { code?: string; status?: number; message: string }, + (e: unknown) => e as { code?: string; status?: number; message: string; remedy?: string }, ); expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); expect(err?.message).toContain("'vector' extension (pgvector) is not installed"); - expect(err?.message).toContain('permission denied'); - expect(err?.message).toContain('CREATE EXTENSION IF NOT EXISTS vector;'); - expect(err?.message).toContain('CREATE SCHEMA IF NOT EXISTS "os_knowledge";'); + // The caller's sentence carries no driver text, no SQL, no schema name … + expect(err?.message).not.toContain('permission denied'); + expect(err?.message).not.toContain('CREATE'); + expect(err?.message).not.toContain('os_knowledge'); + // … the operator's remedy carries all three. + expect(err?.remedy).toContain('permission denied'); + expect(err?.remedy).toContain('CREATE EXTENSION IF NOT EXISTS vector;'); + expect(err?.remedy).toContain('CREATE SCHEMA IF NOT EXISTS "os_knowledge";'); await expect(adapter.search('x', { source, topK: 3 })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); await expect(adapter.listDocuments(ctx, { limit: 5 })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); @@ -75,13 +81,63 @@ describe('knowledge-pgvector when the database is not ready', () => { expect(db.statements.some((s) => s.startsWith('CREATE SCHEMA IF NOT EXISTS "os_knowledge"'))).toBe(true); }); - it('with no database at all, every call says why', async () => { + it('with no database at all, every call says so, and the operator reads why', async () => { const adapter = new PgvectorKnowledgeAdapter({ embedder: new FakeEmbedder(), unavailable: 'the platform database (OS_DATABASE_URL) is not PostgreSQL.' }); await expect(adapter.search('x', { source, topK: 3 })).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', - message: expect.stringContaining('OS_DATABASE_URL'), + message: expect.stringContaining('has no PostgreSQL database'), + remedy: expect.stringContaining('OS_DATABASE_URL'), + }); + const health = await adapter.healthCheck(); + expect(health.ok).toBe(false); + expect(health.message).toContain('OS_DATABASE_URL'); + }); + + it('an unreachable database is said to be unreachable, never a missing extension, and no SQL is offered', async () => { + const pool: PgPoolLike = { + query: async () => { + throw new Error('connect ECONNREFUSED 10.1.2.3:5432'); + }, + connect: async () => { + throw new Error('connect ECONNREFUSED 10.1.2.3:5432'); + }, + }; + const adapter = new PgvectorKnowledgeAdapter({ pool, embedder: new FakeEmbedder() }); + const err = await adapter.search('x', { source, topK: 3 }).then( + () => undefined, + (e: unknown) => e as { code?: string; message: string; remedy?: string }, + ); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE' }); + expect(err?.message).toContain('cannot reach its PostgreSQL database'); + expect(err?.message).not.toContain('extension'); + expect(err?.message).not.toContain('10.1.2.3'); + expect(err?.remedy).toContain('ECONNREFUSED'); + expect(err?.remedy).not.toContain('CREATE'); + const health = await adapter.healthCheck(); + expect(health).toMatchObject({ ok: false, message: expect.stringContaining('ECONNREFUSED') }); + }); + + it('with no embedder, a search is SERVICE_UNAVAILABLE, never a rebuild refusal of a healthy index', async () => { + // A ready store holding one generation, searched under a fingerprint that + // differs only because the embedder (model, width) is not registered yet. + const pool: PgPoolLike = { + query: async (text: string) => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.7' }] as R[] }; + if (text.includes('SELECT generation, fingerprint')) { + return { rows: [{ generation: 1, fingerprint: 'fp-with-model', recipe_hash: null, dim: 384 }] as R[] }; + } + return { rows: [] as R[] }; + }, + connect: async () => { + throw new Error('no transaction expected'); + }, + }; + const adapter = new PgvectorKnowledgeAdapter({ pool, embedder: () => undefined }); + await expect(adapter.search('x', { source, topK: 3, index: { fingerprint: 'fp-without-model' } })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + message: expect.stringContaining('no embedder'), }); - expect((await adapter.healthCheck()).ok).toBe(false); }); it('the plugin registers the adapter and boot goes on, warning with the SQL', async () => { @@ -102,6 +158,25 @@ describe('knowledge-pgvector when the database is not ready', () => { await plugin.destroy(); }); + it("the plugin reads the kernel's embedder at each call, so a re-registered one is reported at once", async () => { + let embedder = new FakeEmbedder(384, 'model-one'); + let adapter: PgvectorKnowledgeAdapter | undefined; + const ctx = { + getService: (name: string) => { + if (name === KNOWLEDGE_SERVICE) return { registerAdapter: (_id: string, a: PgvectorKnowledgeAdapter) => { adapter = a; } }; + if (name === EMBEDDER_SERVICE) return embedder; + throw new Error(`no service ${name}`); + }, + logger: { warn: vi.fn(), info: vi.fn() }, + } as unknown as PluginContext; + const plugin = new KnowledgePgvectorPlugin({ env: {} }); + await plugin.start(ctx); + expect(adapter?.embedding).toEqual({ dimensions: 384, model: 'model-one' }); + embedder = new FakeEmbedder(1536, 'model-two'); + expect(adapter?.embedding).toEqual({ dimensions: 1536, model: 'model-two' }); + await plugin.destroy(); + }); + it('an embedder that is not registered is a readable SERVICE_UNAVAILABLE, not a crash', async () => { const db = databaseWithoutVector(); db.install(); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 539227de41b..07d17cd0c29 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -80,6 +80,9 @@ export interface PgvectorKnowledgeAdapterOptions { /** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; +/** How many times {@link PgvectorKnowledgeAdapter.upsert} plans a batch again when a concurrent write removed a passage it meant to keep. */ +const UPSERT_ATTEMPTS = 3; + /** A generation row: one complete index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -127,26 +130,39 @@ interface Readiness { * The generation row holds the fingerprint the source was built under. A write * or a search carrying another is refused `KNOWLEDGE_REBUILD_REQUIRED` and is * never served from the stored generation. A source that holds nothing takes - * the first fingerprint it is handed. `beginBuild` under the stored fingerprint - * rebuilds inside the generation; under another it is refused, with the SQL - * that drops the source's index so it can be built afresh — this store does - * not yet build a second generation beside the first. `completeBuild` records + * the first fingerprint it is handed, and passage rows of the source left + * without a generation row are deleted as that generation opens: it never + * adopts vectors of another fingerprint. `beginBuild` under the stored + * fingerprint rebuilds inside the generation; under another it is refused, + * its `remedy` carrying the exact statements that clear the source (one + * DELETE per passage table, then the generation row) — this store does not + * yet build a second generation beside the first. `completeBuild` records * the recipe hash; `indexStatus` answers both. * * ## Writes * * The adapter takes the service's passages (`capabilities.chunks`) and hashes * the text of each (`chunk_hash`). A passage whose hash is already stored is - * not embedded again: its row's metadata is rewritten. Every embed call runs - * before a connection is taken for the write, so no pooled connection waits on - * the embedder. + * not embedded again: its row's metadata is rewritten; when that row is gone + * by the time the write runs (a concurrent write removed it), the batch is + * planned again, so the passage is embedded rather than lost. Every embed call + * runs before a connection is taken for the write, so no pooled connection + * waits on the embedder. * * ## When the database is not ready * * Without the `vector` extension (and the right to create it), or without the * right to create the schema, the adapter creates nothing; every call answers - * `SERVICE_UNAVAILABLE` with the SQL to run by hand, `healthCheck` answers - * `ok: false`, and the next call tries again. + * `SERVICE_UNAVAILABLE`, `healthCheck` answers `ok: false` with the SQL to run + * by hand, and the next call tries again. A database it cannot reach is + * reported as unreachable, with no SQL. + * + * ## What a caller reads + * + * A refusal's message is one sentence: no driver text, no SQL, no schema + * name. Operator text travels in the error's `remedy`, which `healthCheck`, + * the plugin's boot warning and the knowledge service's reindex result and + * log show. */ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { readonly id: string; @@ -188,13 +204,42 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { async upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise { if (docs.length === 0) return; - const pool = this.requirePool(); + this.requirePool(); const readiness = await this.ready(); const embedder = this.requireEmbedder(); const generation = (await this.writeTarget(ctx, embedder, true))!; await this.ensureVectorTable(generation.dim, readiness); + // An unchanged passage is rewritten in place, keeping its vector. When its + // row is gone by the time the write runs (a concurrent rewrite of the same + // document removed it), the write is rolled back and planned again, so the + // passage is embedded and inserted rather than lost. + for (let attempt = 1; ; attempt++) { + const missing = await this.writePassages(docs, ctx.source.id, generation, readiness, embedder); + if (missing === undefined) return; + if (attempt >= UPSERT_ATTEMPTS) { + throw new Error( + `knowledge-pgvector: passage '${missing}' of source '${ctx.source.id}' was removed by a concurrent write ` + + `${UPSERT_ATTEMPTS} times while this write ran; nothing of this batch was written. Retry the write.`, + ); + } + } + } + + /** + * One attempt of {@link upsert}: read the stored chunk hashes, embed what + * changed, write in one transaction. Answers `undefined` when written, or the + * id of an unchanged passage whose row was gone (the transaction is rolled + * back). + */ + private async writePassages( + docs: KnowledgeDocument[], + sourceId: string, + generation: GenerationRow, + readiness: Readiness, + embedder: IEmbedder, + ): Promise { + const pool = this.requirePool(); const table = qualified(this.schema, vectorTable(generation.dim)); - const sourceId = ctx.source.id; const planned = docs.map((doc) => ({ doc, @@ -227,7 +272,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { vectorOf.set(p.id, v); }); - await this.transaction(async (client) => { + let missing: string | undefined; + const written = await this.transaction(async (client) => { for (const { doc, passages } of planned) { await client.query( `DELETE FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = $3 AND NOT (chunk_id = ANY($4::text[]))`, @@ -251,12 +297,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const vector = vectorOf.get(p.id); if (vector === undefined) { // Unchanged text: the stored vector stands; the rest of the row is rewritten. - await client.query( + const updated = await client.query( `UPDATE ${table} SET document_id = $4, source_record_id = $5, organization_id = $6, content = $7, title = $8, doc_hash = $9, chunk_hash = $10, metadata = $11::jsonb, heading_path = $12::jsonb - WHERE source_id = $1 AND generation = $2 AND chunk_id = $3`, + WHERE source_id = $1 AND generation = $2 AND chunk_id = $3 AND chunk_hash = $10 + RETURNING chunk_id`, common, ); + if (updated.rows.length === 0) { + missing = p.id; + return false; + } } else { await client.query( `INSERT INTO ${table} (source_id, generation, chunk_id, document_id, source_record_id, organization_id, content, @@ -272,7 +323,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } } + return true; }); + return written ? undefined : missing; } async delete(documentIds: string[], ctx: AdapterContext): Promise { @@ -325,14 +378,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; const pool = this.requirePool(); const readiness = await this.ready(); + // The embedder first: without one the service's fingerprint carries no + // model or width, and comparing it would refuse a healthy index as one to + // rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call. + const embedder = this.requireEmbedder(); const generation = await this.activeGeneration(opts.source.id); if (!generation) return []; // Vectors of two fingerprints are never ranked against each other (K7, rule 5). if (opts.index !== undefined && generation.fingerprint !== opts.index.fingerprint) { - throw rebuildRequired(opts.source.id, this.dropSql(opts.source.id)); + throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id)); } - const embedder = this.requireEmbedder(); - if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, this.dropSql(opts.source.id)); + if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id)); if (!(await this.tableExists(generation.dim))) return []; const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; @@ -415,14 +471,19 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const generation = (await this.activeGeneration(ctx.source.id)) ?? (await this.openFirstGeneration(ctx.source.id, index.fingerprint, embedder)); if (generation.fingerprint === index.fingerprint && generation.dim === embedder.dimensions) return; + const sql = await this.clearSql(ctx.source.id); throw Object.assign( new Error( - `Knowledge source '${ctx.source.id}' was indexed under another fingerprint (embedding model, dimensions, ` + - 'split or content recipe changed), and this store does not yet build a second generation beside the ' + - 'first. Either restore the earlier embedding and split configuration, or drop the source\'s index and ' + - `reindex it: ${this.dropSql(ctx.source.id)}`, + `Knowledge source '${ctx.source.id}' was indexed under another embedding model, split or content recipe, ` + + 'and this store does not yet build a second index beside the first.', ), - { code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }, + { + code: KNOWLEDGE_REBUILD_REQUIRED, + status: 409, + remedy: + 'Either restore the earlier embedding and split configuration, or clear the source\'s index and run a ' + + `complete reindex. Run as a database owner:\n${sql.join('\n')}`, + }, ); } @@ -448,7 +509,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const r = await this.ready(); return { ok: true, message: `pgvector ${r.version}, tables in schema '${this.schema}'` }; } catch (err) { - return { ok: false, message: err instanceof Error ? err.message : String(err) }; + const remedy = remedyOf(err); + return { ok: false, message: `${errorText(err)}${remedy === undefined ? '' : ` ${remedy}`}` }; } } @@ -456,7 +518,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { private requirePool(): PgPoolLike { if (!this.pool) { - throw notReady(this.unavailable ?? 'it has no PostgreSQL connection.', []); + throw notReady('it has no PostgreSQL database', this.unavailable ?? 'It was given no PostgreSQL connection.', []); } return this.pool; } @@ -488,32 +550,41 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { let ext: { schema: string; version: string } | undefined; try { ext = await this.findExtension(pool); - if (!ext) { - await pool.query('CREATE EXTENSION IF NOT EXISTS vector'); - ext = await this.findExtension(pool); - } } catch (err) { + // The first query failed: the database is not reachable (or refuses this + // role). Not a missing extension, and no SQL would fix it. throw notReady( - `the PostgreSQL 'vector' extension (pgvector) is not installed in this database, and this connection could not ` + - `install it (${errorText(err)}).`, - ['CREATE EXTENSION IF NOT EXISTS vector;', ...ddl.map((s) => `${s};`)], + 'it cannot reach its PostgreSQL database', + `The connection failed: ${errorText(err)}. Check the store's URL, the network and the role's access.`, + [], ); } if (!ext) { - throw notReady("the PostgreSQL 'vector' extension (pgvector) is not installed in this database.", [ - 'CREATE EXTENSION IF NOT EXISTS vector;', - ...ddl.map((s) => `${s};`), - ]); + let refusal: unknown; + try { + await pool.query('CREATE EXTENSION IF NOT EXISTS vector'); + ext = await this.findExtension(pool); + } catch (err) { + refusal = err; + } + if (!ext) { + throw notReady( + "the PostgreSQL 'vector' extension (pgvector) is not installed in its database", + `This connection could not install it${refusal === undefined ? '' : ` (${errorText(refusal)})`}.`, + ['CREATE EXTENSION IF NOT EXISTS vector;', ...ddl.map((statement) => `${statement};`)], + ); + } } try { for (const statement of ddl) await pool.query(statement); } catch (err) { throw notReady( - `its schema '${this.schema}' and generation table could not be created (${errorText(err)}).`, - ddl.map((s) => `${s};`), + 'its schema and generation table could not be created', + `Creating schema '${this.schema}' failed (${errorText(err)}).`, + ddl.map((statement) => `${statement};`), ); } - this.readiness = { extensionSchema: `"${ext.schema}"`, version: ext.version }; + this.readiness = { extensionSchema: quoteIdentifier(ext.schema), version: ext.version }; return this.readiness; } @@ -534,8 +605,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { for (const statement of ddl) await pool.query(statement); } catch (err) { throw notReady( - `its ${dimensions}-wide passage table could not be created (${errorText(err)}).`, - ddl.map((s) => `${s};`), + `its ${dimensions}-wide passage table could not be created`, + `Creating ${qualified(this.schema, vectorTable(dimensions))} failed (${errorText(err)}).`, + ddl.map((statement) => `${statement};`), ); } this.tables.add(dimensions); @@ -562,16 +634,42 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { return row === undefined ? undefined : { ...row, generation: Number(row.generation), dim: Number(row.dim) }; } - /** A source that holds nothing takes the first fingerprint it is handed (there is nothing to mix with). */ + /** + * A source that holds nothing takes the first fingerprint it is handed + * (there is nothing to mix with). "Holds nothing" is made true: passage rows + * of the source left in any passage table without a generation row (a + * generation row deleted by hand, its passages not) are deleted in the same + * transaction that opens the generation, so a first generation never adopts + * vectors embedded under another fingerprint. Only the call whose insert + * opened the generation clears; a concurrent one waits on the key and finds + * it open. + */ private async openFirstGeneration(sourceId: string, fingerprint: string | undefined, embedder: IEmbedder): Promise { - await this.requirePool().query( - `INSERT INTO ${qualified(this.schema, GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) - VALUES ($1, 1, $2, $3, $4, 'active') ON CONFLICT (source_id, generation) DO NOTHING`, - [sourceId, fingerprint ?? null, embedder.dimensions, embedder.model ?? null], - ); + await this.transaction(async (client) => { + const opened = await client.query( + `INSERT INTO ${qualified(this.schema, GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) + VALUES ($1, 1, $2, $3, $4, 'active') ON CONFLICT (source_id, generation) DO NOTHING RETURNING generation`, + [sourceId, fingerprint ?? null, embedder.dimensions, embedder.model ?? null], + ); + if (opened.rows.length === 0) return true; + for (const width of await this.passageWidths(client)) { + await client.query(`DELETE FROM ${qualified(this.schema, vectorTable(width))} WHERE source_id = $1`, [sourceId]); + } + return true; + }); return (await this.activeGeneration(sourceId))!; } + /** The widths of the passage tables that exist in the store's schema. */ + private async passageWidths(client: Pick = this.requirePool()): Promise { + const found = await client.query<{ table_name: string }>( + `SELECT table_name FROM information_schema.tables + WHERE table_schema = $1 AND table_name ~ '^knowledge_vec_d[0-9]+$' ORDER BY table_name`, + [this.schema], + ); + return found.rows.map((r) => Number(r.table_name.slice('knowledge_vec_d'.length))); + } + /** * The generation a write carrying `ctx.index` goes to: the active one, when * its fingerprint is the one carried (or none is carried); refused when it is @@ -592,33 +690,45 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { return this.checkTarget(ctx, active, embedder); } - private checkTarget(ctx: AdapterContext, generation: GenerationRow, embedder: IEmbedder | undefined): GenerationRow { + private async checkTarget( + ctx: AdapterContext, + generation: GenerationRow, + embedder: IEmbedder | undefined, + ): Promise { const fingerprint = ctx.index?.fingerprint; if (fingerprint !== undefined && generation.fingerprint !== fingerprint) { - throw rebuildRequired(ctx.source.id, this.dropSql(ctx.source.id)); + throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id)); } if (embedder !== undefined && embedder.dimensions !== generation.dim) { - throw rebuildRequired(ctx.source.id, this.dropSql(ctx.source.id)); + throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id)); } return generation; } - /** The SQL that drops everything this store holds for a source, so it can be built afresh. */ - private dropSql(sourceId: string): string { + /** + * The statements that clear everything this store holds for a source, so it + * can be built afresh: one DELETE per passage table that exists, then the + * generation rows — passages first, so no generation row is ever missing + * while its passages remain. + */ + private async clearSql(sourceId: string): Promise { const literal = `'${sourceId.replace(/'/g, "''")}'`; - return ( - `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = ${literal}; ` + - `and from each ${qualified(this.schema, 'knowledge_vec_d')} table, DELETE ... WHERE source_id = ${literal};` - ); + const widths = await this.passageWidths().catch(() => [] as number[]); + return [ + ...widths.map((width) => `DELETE FROM ${qualified(this.schema, vectorTable(width))} WHERE source_id = ${literal};`), + `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = ${literal};`, + ]; } - private async transaction(work: (client: PgClientLike) => Promise): Promise { + /** Run `work` in one transaction: committed when it answers `true`, rolled back when it answers `false` or throws. */ + private async transaction(work: (client: PgClientLike) => Promise): Promise { const client = await this.requirePool().connect(); try { await client.query('BEGIN'); - await work(client); - await client.query('COMMIT'); + const commit = await work(client); + await client.query(commit ? 'COMMIT' : 'ROLLBACK'); client.release(); + return commit; } catch (err) { await client.query('ROLLBACK').catch(() => undefined); client.release(err instanceof Error ? err : true); @@ -648,25 +758,54 @@ function requireIndex(ctx: AdapterContext, member: string): NonNullable ctx.logger.warn?.(`KnowledgePgvectorPlugin: idle connection error: ${err.message}`)); } + // Read at each call, never cached: the kernel's embedder may register + // after this plugin starts, or be replaced (ADR-0161 K8, item 6), and the + // adapter reports the embedder it will actually call. const embedder = (): IEmbedder | undefined => { if (this.opts.embedder) return this.opts.embedder; - if (this.embedderService) return this.embedderService; try { - this.embedderService = ctx.getService(EMBEDDER_SERVICE); + return ctx.getService(EMBEDDER_SERVICE); } catch { return undefined; } - return this.embedderService; }; const adapter = new PgvectorKnowledgeAdapter({ 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 60cdf9cc38e..61b1279a365 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -332,6 +332,56 @@ describe('KnowledgeService — reindex', () => { expect(adapter.upsertSpy).not.toHaveBeenCalled(); }); + it('a refused beginBuild stops a complete reindex before any listing or write: ok:false, the remedy carried', async () => { + const find = vi.fn(async () => [{ id: 'r1', title: 'T1', notes: 'N1' }]); + const listDocuments = vi.fn(async () => ({ documents: [] })); + const completeBuild = vi.fn(async () => undefined); + const adapter = Object.assign(makeAdapter('memory'), { + listDocuments, + completeBuild, + beginBuild: vi.fn(async () => { + throw Object.assign(new Error("Knowledge source 's1' needs a rebuild."), { + code: 'KNOWLEDGE_REBUILD_REQUIRED', + status: 409, + remedy: 'DELETE FROM "os_knowledge"."knowledge_generation" WHERE source_id = \'s1\';', + }); + }), + }); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine }); + svc.registerAdapter('memory', adapter); + svc.registerSource(objectSource('s1', 'task')); + const res = await svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, indexed: 0, purged: null }); + expect(res.message).toContain('needs a rebuild'); + expect(res.message).toContain('DELETE FROM'); + expect(listDocuments).not.toHaveBeenCalled(); + expect(find).not.toHaveBeenCalled(); + expect(adapter.upsertSpy).not.toHaveBeenCalled(); + expect(adapter.deleteSpy).not.toHaveBeenCalled(); + expect(completeBuild).not.toHaveBeenCalled(); + }); + + it('a completeBuild that throws turns a complete reindex into ok:false, though every page was written', async () => { + const find = vi.fn(async (_obj: string, query: { where?: unknown }) => + (query.where === undefined ? [{ id: 'r1', title: 'T1', notes: 'N1' }] : [])); + const adapter = Object.assign(makeAdapter('memory'), { + listDocuments: vi.fn(async () => ({ documents: [] })), + beginBuild: vi.fn(async () => undefined), + completeBuild: vi.fn(async () => { + throw new Error('the generation row could not be written'); + }), + }); + const svc = new KnowledgeService({ dataEngine: { find } as unknown as IDataEngine }); + svc.registerAdapter('memory', adapter); + svc.registerSource(objectSource('s1', 'task')); + const res = await svc.reindexSource('s1'); + expect(res).toMatchObject({ ok: false, indexed: 1 }); + expect(res.message).toContain('did not complete the build'); + expect(res.message).toContain('the generation row could not be written'); + expect(adapter.upsertSpy).toHaveBeenCalledOnce(); + expect(adapter.completeBuild).toHaveBeenCalledOnce(); + }); + it('returns ok:false when no dataEngine is bound', async () => { const svc = new KnowledgeService(); svc.registerAdapter('memory', makeAdapter('memory')); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index ff73df5e23d..c7c67ea8e9a 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -14,6 +14,7 @@ export { TITLE_RULE_VERSION, computeIndexFingerprint, computeRecipeHash, + indexExpectation, } from './knowledge-index-fingerprint.js'; export type { IndexFingerprintInput, RecipeHashInput } from './knowledge-index-fingerprint.js'; export { SPLIT_ALGORITHM_VERSION } from './split/index.js'; diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 38e3cd6f53c..d2b5674891d 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -258,11 +258,15 @@ export class KnowledgeService implements IKnowledgeService { * documents were cut by. Never cached: the settings, the descriptor and the * object definition may each change between two calls. */ - private async planIndex(source: KnowledgeSource, adapter: IKnowledgeAdapter): Promise { + private async planIndex( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + chunkTarget: () => Promise = () => this.readChunkTarget(), + ): Promise { const split = adapter.capabilities?.chunks === true ? resolveSplit({ split: source.source.kind === 'object' ? (source.source as ObjectKnowledgeSource).split : undefined, - chunkTarget: await this.readChunkTarget(), + chunkTarget: await chunkTarget(), maxInputTokens: adapter.embedding?.maxInputTokens, }) : undefined; @@ -536,7 +540,7 @@ export class KnowledgeService implements IKnowledgeService { purged: null, failed: 0, failures: [], - message: `reindex of source '${source.id}' refused: the adapter did not begin the build (${errorText(err)}); nothing was written.`, + message: `reindex of source '${source.id}' refused: the adapter did not begin the build, and nothing was written. ${operatorText(err)}`, }; } } @@ -626,7 +630,7 @@ export class KnowledgeService implements IKnowledgeService { try { await adapter.upsert(prepared.ready, ctx); } catch (err) { - return stopped(`the adapter upsert failed: ${errorText(err)}`); + return stopped(`the adapter upsert failed: ${operatorText(err)}`); } } // A document the split cannot index is removed — an older passage of it @@ -636,7 +640,7 @@ export class KnowledgeService implements IKnowledgeService { try { await adapter.delete(prepared.failed.map((f) => f.documentId), ctx); } catch (err) { - return stopped(`removing the page's documents that cannot be indexed failed: ${errorText(err)}`); + return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); } for (const f of prepared.failed) { failed += 1; @@ -740,7 +744,7 @@ export class KnowledgeService implements IKnowledgeService { ok: false, message: `reindex of source '${source.id}' walked every page, but the adapter did not complete the build ` + - `(${errorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, + `(${operatorText(err)}).${done.message === undefined ? '' : ` ${done.message}`}`, }; } } @@ -816,20 +820,18 @@ export class KnowledgeService implements IKnowledgeService { * is not logged and dropped like a failure: the sources that can be searched * answer, and when NONE can, the call is refused whole — this method throws * a coded error naming each refused source with its code. When some answer, - * the hits are theirs and the refused sources are logged at `warn`; the + * the hits are theirs. A source that answers the first round and refuses the + * refill is refused for the whole search, its first-round hits dropped: no + * source is both answered and named as refused. A refused source is named + * with its code and the adapter's one-sentence message; the adapter's + * `remedy`, operator text such as the SQL to run, goes to the `warn` log + * with it and never to the caller. The * return type of `IKnowledgeService.search` has no place to name them, so a * caller that must name them to its own caller (the `search_knowledge` tool) * reads {@link searchWithRefusals}. */ async search(query: string, opts: KnowledgeSearchOptions = {}): Promise { - const report = await this.searchWithRefusals(query, opts); - if (report.refused.length > 0) { - this.options.logger?.warn?.( - `[knowledge] ${report.refused.length} source(s) refused this search and were not searched: ` + - report.refused.map((r) => `'${r.sourceId}' (${r.code}: ${r.message})`).join('; '), - ); - } - return report.hits; + return (await this.searchWithRefusals(query, opts)).hits; } /** @@ -890,6 +892,7 @@ export class KnowledgeService implements IKnowledgeService { return widened(source) && answer !== undefined && answer.answered >= firstAsk(source); }); if (saturated.length > 0) { + const refusedBefore = refused.length; const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter, refused); // A refilled source's second answer is a superset of its first: its // first-round survivors are dropped and the whole answer re-checked. @@ -899,6 +902,14 @@ export class KnowledgeService implements IKnowledgeService { const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); + // A source that refused the refill (its index changed between the two + // rounds) is refused for the whole search: its first-round hits are + // dropped, so no source is both answered and named as refused. + const refusedInRefill = new Set(refused.slice(refusedBefore).map((r) => r.sourceId)); + if (refusedInRefill.size > 0) { + kept = kept.filter((hit) => !refusedInRefill.has(hit.sourceId)); + if ([...first.keys()].every((id) => refusedInRefill.has(id))) throw wholeRefusal(refused); + } } } @@ -1141,13 +1152,16 @@ export class KnowledgeService implements IKnowledgeService { admitted: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, ): Promise { const out: SearchTarget[] = []; + // The settings page's chunk target, read at most once for the whole search. + let target: Promise | undefined; + const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); for (const entry of admitted) { const adapter = this.adapters.get(entry.source.adapter); if (!adapter) { out.push(entry); continue; } - const plan = await this.planIndex(entry.source, adapter); + const plan = await this.planIndex(entry.source, adapter, chunkTarget); out.push({ ...entry, fingerprint: plan.index.fingerprint }); } return out; @@ -1203,7 +1217,12 @@ export class KnowledgeService implements IKnowledgeService { } catch (err) { const coded = codedRefusalOf(err); if (coded !== undefined) { + // The caller reads the code and the adapter's one-sentence message; + // the operator reads its remedy (the SQL to run, say) here. refused.push({ sourceId: source.id, ...coded }); + this.options.logger?.warn?.( + `[knowledge] source '${source.id}' refused this search and was not searched (${coded.code}): ${operatorText(err)}`, + ); continue; } this.options.logger?.error?.( @@ -1933,7 +1952,7 @@ async function listAdapterDocuments( cursor = page.nextCursor; } } catch (err) { - return { ok: false, reason: errorText(err) }; + return { ok: false, reason: operatorText(err) }; } } @@ -2018,7 +2037,7 @@ export async function purgeDocuments(input: PurgeDocumentsInput): Promise; From 065c98ff72750a8bc8f2247bed8f91a1bbb116e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:09:03 +0000 Subject: [PATCH 11/11] fix(knowledge-pgvector): listDocuments resolves the embedder first; the remedy convention stated once - listDocuments asks for the embedder before comparing fingerprints: no embedder is 503, never a 409 with clearing statements - clearSql always includes the width the generation records, so a failed catalogue read never prints the generation row alone - the contract states the coded-refusal remedy convention once, on IKnowledgeAdapter - a service case pins that a remedy reaches the warn log and never refused[].message or the thrown message Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbX5BF433x8ooJNQVRp --- .../src/__tests__/not-ready.test.ts | 9 ++++- .../src/pgvector-adapter.ts | 24 ++++++++---- .../src/__tests__/knowledge-service.test.ts | 38 +++++++++++++++++++ .../spec/src/contracts/knowledge-adapter.ts | 18 ++++++--- 4 files changed, 74 insertions(+), 15 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts index e59e6802339..fb9052b3f73 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts @@ -117,7 +117,7 @@ describe('knowledge-pgvector when the database is not ready', () => { expect(health).toMatchObject({ ok: false, message: expect.stringContaining('ECONNREFUSED') }); }); - it('with no embedder, a search is SERVICE_UNAVAILABLE, never a rebuild refusal of a healthy index', async () => { + it('with no embedder, a search or a listing is SERVICE_UNAVAILABLE, never a rebuild refusal of a healthy index', async () => { // A ready store holding one generation, searched under a fingerprint that // differs only because the embedder (model, width) is not registered yet. const pool: PgPoolLike = { @@ -138,6 +138,13 @@ describe('knowledge-pgvector when the database is not ready', () => { status: 503, message: expect.stringContaining('no embedder'), }); + // The listing a reindex starts with (a capped walk calls no beginBuild) answers the same. + const listing = { source, reason: 'reindex' as const, index: { fingerprint: 'fp-without-model', recipeHash: 'rh' } }; + await expect(adapter.listDocuments(listing, { limit: 5 })).rejects.toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + message: expect.stringContaining('no embedder'), + }); }); it('the plugin registers the adapter and boot goes on, warning with the SQL', async () => { diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 07d17cd0c29..459d904c374 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -352,8 +352,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } const pool = this.requirePool(); await this.ready(); + // The embedder first, as on every other call: without one the service's + // fingerprint carries no model or width, and comparing it would refuse a + // healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE. + const embedder = this.requireEmbedder(); // The generation the writes go to (ADR-0161 K8, item 1). - const generation = await this.writeTarget(ctx, undefined, false); + const generation = await this.writeTarget(ctx, embedder, false); if (!generation || !(await this.tableExists(generation.dim))) return { documents: [] }; // In byte order ("C"), both the order and the cursor's comparison, so a // cursor stays valid whatever the database's collation. @@ -386,9 +390,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (!generation) return []; // Vectors of two fingerprints are never ranked against each other (K7, rule 5). if (opts.index !== undefined && generation.fingerprint !== opts.index.fingerprint) { - throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id)); + throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id, generation.dim)); } - if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id)); + if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id, generation.dim)); if (!(await this.tableExists(generation.dim))) return []; const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; @@ -471,7 +475,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const generation = (await this.activeGeneration(ctx.source.id)) ?? (await this.openFirstGeneration(ctx.source.id, index.fingerprint, embedder)); if (generation.fingerprint === index.fingerprint && generation.dim === embedder.dimensions) return; - const sql = await this.clearSql(ctx.source.id); + const sql = await this.clearSql(ctx.source.id, generation.dim); throw Object.assign( new Error( `Knowledge source '${ctx.source.id}' was indexed under another embedding model, split or content recipe, ` + @@ -697,10 +701,10 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ): Promise { const fingerprint = ctx.index?.fingerprint; if (fingerprint !== undefined && generation.fingerprint !== fingerprint) { - throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id)); + throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id, generation.dim)); } if (embedder !== undefined && embedder.dimensions !== generation.dim) { - throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id)); + throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id, generation.dim)); } return generation; } @@ -711,9 +715,13 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { * generation rows — passages first, so no generation row is ever missing * while its passages remain. */ - private async clearSql(sourceId: string): Promise { + private async clearSql(sourceId: string, knownWidth: number): Promise { const literal = `'${sourceId.replace(/'/g, "''")}'`; - const widths = await this.passageWidths().catch(() => [] as number[]); + // The tables found in the schema, and always the width the source's + // generation records: should the catalogue read fail, the statements still + // clear that table before the generation row, never the row alone. + const found = await this.passageWidths().catch(() => [] as number[]); + const widths = [...new Set([...found, knownWidth])].sort((a, b) => a - b); return [ ...widths.map((width) => `DELETE FROM ${qualified(this.schema, vectorTable(width))} WHERE source_id = ${literal};`), `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = ${literal};`, 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 61b1279a365..bee9333a0c1 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -332,6 +332,44 @@ describe('KnowledgeService — reindex', () => { expect(adapter.upsertSpy).not.toHaveBeenCalled(); }); + it("a refusal's remedy (operator text) reaches the warn log, never refused[].message or the thrown message", async () => { + const http = (id: string, adapter: string): KnowledgeSource => ({ + id, label: id, adapter, source: { kind: 'http', urls: ['https://x.test'] } as KnowledgeSource['source'], + }); + const remedy = 'Run as a database owner:\nDELETE FROM "os_knowledge"."knowledge_generation" WHERE source_id = \'refusing\';'; + const refusing = Object.assign(makeAdapter('refusing'), { + search: vi.fn(async () => { + throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { + code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, remedy, + }); + }), + }); + const answering = makeAdapter('answering', [{ chunkId: 'c1', documentId: 'd1', sourceId: 'answering', score: 0.9, snippet: 'ok' }]); + const warn = vi.fn(); + const svc = new KnowledgeService({ logger: { warn } as never }); + svc.registerAdapter('refusing', refusing); + svc.registerAdapter('answering', answering); + svc.registerSource(http('refusing', 'refusing')); + svc.registerSource(http('answering', 'answering')); + + // Some sources answer: the refused one is named, its message alone. + const report = await svc.searchWithRefusals('q'); + expect(report.hits.map((h) => h.documentId)).toEqual(['d1']); + expect(report.refused).toEqual([ + { sourceId: 'refusing', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, message: "Knowledge source 'refusing' needs a rebuild." }, + ]); + expect(warn.mock.calls.some(([line]) => String(line).includes('DELETE FROM'))).toBe(true); + + // None answers: the thrown refusal carries no remedy either. + const thrown = await svc.searchWithRefusals('q', { sourceIds: ['refusing'] }).then( + () => undefined, + (e: unknown) => e as { code?: string; message: string; refused?: Array<{ message: string }> }, + ); + expect(thrown).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect(thrown?.message).not.toContain('DELETE'); + expect(thrown?.refused?.every((r) => !r.message.includes('DELETE'))).toBe(true); + }); + it('a refused beginBuild stops a complete reindex before any listing or write: ok:false, the remedy carried', async () => { const find = vi.fn(async () => [{ id: 'r1', title: 'T1', notes: 'N1' }]); const listDocuments = vi.fn(async () => ({ documents: [] })); diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index e4a072e3e93..e17ce58f856 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -225,6 +225,16 @@ export interface AdapterEmbeddingDescriptor { * 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`. + * + * ## Coded refusals and their `remedy` + * + * Any member may refuse with an ADR-0112 coded error (`code`, `status`) — + * `KNOWLEDGE_REBUILD_REQUIRED` (409) under another fingerprint, + * `SERVICE_UNAVAILABLE` (503) when the backend is not ready. Its `message` is + * one sentence a search caller may read: no driver text, no SQL, no schema + * name. Operator text — what went wrong in the backend, the SQL to run — goes + * in the error's `remedy` string, which the service shows in a reindex result + * and its log, and never to a search caller. */ export interface IKnowledgeAdapter { /** Stable adapter id used in `KnowledgeSource.adapter`. */ @@ -289,12 +299,8 @@ export interface IKnowledgeAdapter { * under construction for that fingerprint — or, when it cannot, refuses * with a coded refusal and the walk does not run. An adapter that opens * generations keeps one builder per source; one that does not build a - * second generation beside the first refuses a new fingerprint here. - * - * A coded refusal's `message` is one sentence a search caller may read. - * Operator text — what went wrong in the database, the SQL to run — goes in - * the error's `remedy` string, which the service shows in a reindex result - * and its log, never to a search caller. + * second generation beside the first refuses a new fingerprint here, with + * a `remedy` (see "Coded refusals" above). */ beginBuild?(ctx: AdapterContext): Promise;