diff --git a/.changeset/38676-embed-question-once.md b/.changeset/38676-embed-question-once.md new file mode 100644 index 00000000000..edf90a1ab37 --- /dev/null +++ b/.changeset/38676-embed-question-once.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +--- + +perf(knowledge): a knowledge search embeds its question at most once for each adapter, the refill round included + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened (ADR-0161, the dated note of 2026-12-01 under K8): `IKnowledgeAdapter` (`@objectstack/spec/contracts`) gains an optional `embedQuery(query)`, which embeds a question exactly as the adapter's `search` does (its embedder and its query prefix), and `AdapterSearchOptions` gains an optional `queryVector: () => Promise`, a function the adapter calls where its `search` embeds the query. An adapter handed it calls it in place of that embedding call, after every refusal it answers first, checks the answer's width as it checks one its embedder answered, and never changes the array. + +For each search, the knowledge service hands every `search` call to an adapter instance that has `embedQuery` one function: its first call asks that instance's `embedQuery`, and every later call in the search answers the same promise, a failed one too. A search whose first round leaves fewer than `topK` records or groups after the permission re-check (a narrowed caller, `granularity: 'record'` or `groupBy`) asks the adapter again with a larger `topK`; that second round used to embed the question a second time, about one embedding request per refilled search. Several sources on one adapter instance now share the one embedding call too. Because the adapter asks only where it embeds, a `keyword` search, a search that ranks nothing and a source the adapter refuses make no embedding call, and the adapter's own refusal (`KNOWLEDGE_REBUILD_REQUIRED` 409 for an index that needs a rebuild) is the one answered even when the embedder would fail. A failed embedding call fails each `search` call that asked for the vector, with the code and wording it had before. + +`knowledge-turso` and `knowledge-pgvector` implement both members. An adapter without `embedQuery`, such as `knowledge-memory`, is handed nothing and is searched as before, embedding on every call. The adapter contract suite (`@objectstack/service-knowledge/testing`) gains an optional `implements.embedQuery` declaration and one case for it. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 51dad452a8f..a086fecf68c 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -526,6 +526,7 @@ interface IKnowledgeAdapter { }; upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; search(query: string, opts: AdapterSearchOptions): Promise; + embedQuery?(query: string): Promise; // a question, embedded as its search embeds it delete(documentIds: string[], ctx: AdapterContext): Promise; listDocuments?( ctx: AdapterContext, @@ -564,6 +565,25 @@ search to chosen records the same way — see [Record scope](#record-scope). report, not configuration. `AdapterSearchOptions.retrieval` carries the mode a search runs, a per-request parameter like `topK`, and only ever a mode the adapter lists. +`embedQuery` embeds a question exactly as the adapter's `search` embeds it, +through its embedder and with its query prefix; it takes no source, so an +adapter whose query embedding differs from source to source does not +implement it. Its presence is the signal (ADR-0161, the dated note of +2026-12-01 under K8): the service then hands every `search` call it makes to +that adapter instance in one search the same function, +`AdapterSearchOptions.queryVector: () => Promise`. Its first +call asks the instance's `embedQuery` for the query; every later call in that +search (another source of the instance, the refill round, the adapter's own +retry) answers the same promise, a rejected one too. The adapter calls it +where its `search` embeds the query, after everything it decides first, so a +search under `keyword`, a search that ranks nothing and a source it refuses +(`KNOWLEDGE_REBUILD_REQUIRED` among them) cost no embedding call, and that +refusal is the one answered. It checks the answer's width as it checks one its +embedder answered, and never changes the array. The service judges nothing +about a call and reads no vector: the question is embedded at most once for +each adapter instance in a search, by the adapter. An adapter without +`embedQuery` is handed nothing and embeds the question on every call, as +before. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the @@ -615,7 +635,10 @@ 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; and, for an adapter that declares the optional -`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite +`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words; and, +for an adapter that declares `embedQuery`, that a search handed a function answering its own +`embedQuery` answers as without it and makes no embedding call of its own, and that one answering +a vector of another width is rejected. `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-pgvector` diff --git a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs index 80abe4b8f85..bc521076c2c 100644 --- a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs +++ b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs @@ -135,7 +135,7 @@ function setup({ failEmbed = false } = {}) { } describe('bench instrument — segment seams over the real adapter and service', () => { - it('a caller the re-check narrows: two rounds, each one embed, one ranking statement and one re-check', async () => { + it('a caller the re-check narrows: two rounds, one embed serving both, one ranking statement and one re-check', async () => { const { search } = setup(); const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER); expect(outcome.error).toBeUndefined(); @@ -145,7 +145,8 @@ describe('bench instrument — segment seams over the real adapter and service', expect(outcome.record.adapterCalls.map((c) => c.asked)).toEqual([TOP_K * 5, TOP_K * 20]); expect(s.rounds).toBe(2); expect(s.refilled).toBe(true); - expect(s.calls.embed).toBe(2); + // The question is embedded once for the search; the refill reuses its vector. + expect(s.calls.embed).toBe(1); expect(s.calls.ranking).toBe(2); expect(s.calls.permission_recheck).toBe(2); // The caller's readable ids, read once before ranking (unscoped search). 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 index c48d725e9cf..fe94f59c438 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -31,6 +31,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { dropSource: true, keywordLeg: true, retrieval: true, + embedQuery: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/question-once.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/question-once.test.ts new file mode 100644 index 00000000000..829fb1864d7 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/question-once.test.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The question of a search is embedded at most once for this adapter instance + * (ADR-0161, the dated note of 2026-12-01 under K8), through a real + * `KnowledgeService` and without a database: a fake pool answers the store's + * statements. The service hands every `search` call one function as + * `queryVector`; the adapter calls it where it embeds the query, after its own + * refusals, so a source it refuses costs no embedding call and answers its own + * refusal. Call counts only, never a duration. + */ + +import { describe, expect, it } from 'vitest'; +import type { AdapterSearchOptions, IDataEngine } from '@objectstack/spec/contracts'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as unknown as ExecutionContext; +const DIMS = 384; + +const sourceOf = (name: string, extra: Record = {}): KnowledgeSource => + ({ + name, + label: name, + adapter: 'pgvector', + source: { kind: 'object', object: 'clause', content: ['body'], ...extra }, + }) as KnowledgeSource; + +/** + * A store with one active generation per source, held under `fingerprint` + * (absent: the one the service searches with), whose ranking statement answers + * 60 passages of one record, so a record-level search refills. + */ +function fakePool(fingerprint?: string): { pool: PgPoolLike; searched: { fingerprint?: string } } { + const searched: { fingerprint?: string } = {}; + const answer = async (text: string): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.7' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: fingerprint ?? searched.fingerprint ?? null, recipe_hash: null, dim: DIMS, state: 'active' }] as R[] }; + } + if (text.includes('GROUP BY chunk_id')) { + return { + rows: Array.from({ length: 60 }, (_, i) => ({ + chunk_id: `ch_${i}`, + document_id: 'doc_0', + source_record_id: 'rec_0', + content: `passage ${i}`, + title: null, + metadata: {}, + doc_hash: null, + heading_path: null, + vpos: i + 1, + kpos: null, + })) as R[], + }; + } + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, searched }; +} + +/** The service's reads: every record it asks for by id exists. */ +const engine = { + find: async (_object: string, query: { where?: { id?: { $in?: string[] } } }) => + (query?.where?.id?.$in ?? []).map((id) => ({ id })), + findOne: async () => null, +} as unknown as IDataEngine; + +function setup(opts: { fingerprint?: string; sources?: KnowledgeSource[] } = {}) { + const store = fakePool(opts.fingerprint); + const embedder = new FakeEmbedder(DIMS); + const adapter = new PgvectorKnowledgeAdapter({ id: 'pgvector', pool: store.pool, embedder }); + const searches: AdapterSearchOptions[] = []; + const search = adapter.search.bind(adapter); + adapter.search = async (query, searchOpts) => { + searches.push(searchOpts); + store.searched.fingerprint = searchOpts.index?.fingerprint; + return search(query, searchOpts); + }; + const svc = new KnowledgeService({ dataEngine: engine }); + svc.registerAdapter('pgvector', adapter); + for (const s of opts.sources ?? [sourceOf('clauses')]) svc.registerSource(s); + return { svc, embedder, searches }; +} + +/** From now on every embedding call of `embedder` fails, and is still counted. */ +function failing(embedder: FakeEmbedder): void { + embedder.embed = async () => { + embedder.calls += 1; + throw new Error('embedder down at http://10.0.0.7:11434'); + }; +} + +const refilled = { topK: 5, granularity: 'record' as const, executionContext: SYSTEM }; + +describe('knowledge-pgvector through KnowledgeService: the question is embedded at most once a search', () => { + it('a refilled search calls the adapter twice, both handed one function, and the embedder once', async () => { + const { svc, embedder, searches } = setup(); + await svc.search('leave policy', refilled); + expect(searches.map((o) => o.topK)).toEqual([25, 100]); + expect(typeof searches[0]!.queryVector).toBe('function'); + expect(searches[1]!.queryVector).toBe(searches[0]!.queryVector); + expect(embedder.calls).toBe(1); + }); + + it('a refilled search over two sources of one instance: four adapter calls, one embedding call', async () => { + const { svc, embedder, searches } = setup({ sources: [sourceOf('one'), sourceOf('two')] }); + await svc.search('leave policy', refilled); + expect(searches.map((o) => o.source.name).sort()).toEqual(['one', 'one', 'two', 'two']); + expect(embedder.calls).toBe(1); + }); + + it('a keyword search embeds nothing, on either round', async () => { + const { svc, embedder, searches } = setup({ sources: [sourceOf('clauses', { retrieval: { mode: 'keyword' } })] }); + await svc.search('leave policy', refilled); + expect(searches).toHaveLength(2); + expect(embedder.calls).toBe(0); + }); + + it('a source that needs a rebuild, behind an embedder that fails, answers KNOWLEDGE_REBUILD_REQUIRED 409 with 0 embedder calls', async () => { + // The index holds another fingerprint than the one the service searches with. + const { svc, embedder, searches } = setup({ fingerprint: 'fp-built-under-another-model' }); + failing(embedder); + const refused = await svc.searchWithRefusals('leave policy', { topK: 5, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect(searches).toHaveLength(1); + expect(embedder.calls).toBe(0); + }); + + it('the control: the same failing embedder behind a healthy source is called once and refuses it 503', async () => { + const { svc, embedder } = setup(); + failing(embedder); + const refused = await svc.searchWithRefusals('leave policy', { topK: 5, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(embedder.calls).toBe(1); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts index e93c41181b2..fb61301e7b3 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -114,6 +114,56 @@ describe('knowledge-pgvector retrieval modes', () => { }); }); +describe('knowledge-pgvector: a question vector the service hands', () => { + /** {@link recordingPool}, keeping the parameters of each ranking statement. */ + function paramPool(): { pool: PgPoolLike; rankingParams: unknown[][] } { + const rankingParams: unknown[][] = []; + const { pool } = recordingPool(); + const answer = async (text: string, params?: unknown[]): Promise<{ rows: R[] }> => { + if (text.includes('GROUP BY chunk_id')) rankingParams.push(params ?? []); + return pool.query(text, params); + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, rankingParams }; + } + + it('embedQuery embeds the query as search does: the query prefix, then the query', async () => { + const embedder = new FakeEmbedder(); + const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder, queryPrefix: 'query: ' }); + const vector = await adapter.embedQuery('granite quarry'); + expect(embedder.texts).toEqual(['query: granite quarry']); + expect(vector).toHaveLength(embedder.dimensions); + }); + + it('a handed queryVector is asked once, its answer is the one bound into the ranking, and the embedder is not called', async () => { + const store = paramPool(); + const embedder = new FakeEmbedder(); + const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder }); + const handed = await new FakeEmbedder().embed(['basalt column']).then(([v]) => v!); + let asked = 0; + const queryVector = async (): Promise => { + asked += 1; + return handed; + }; + await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector }); + expect(asked).toBe(1); + expect(embedder.calls).toBe(0); + expect(store.rankingParams).toHaveLength(1); + expect(store.rankingParams[0]).toContain(`[${handed.join(',')}]`); + // The control: without one, the query is embedded once. + await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' } }); + expect(embedder.calls).toBe(1); + }); + + it('a handed queryVector of another width is refused, as a vector the embedder answered is', async () => { + const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder: new FakeEmbedder() }); + const refused = await adapter + .search('granite', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector: async () => [1, 0] }) + .catch((e: unknown) => e); + expect(String((refused as Error).message)).toContain('2-wide query vector'); + }); +}); + describe('knowledge-pgvector fusion under the retrieval modes', () => { type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index ef41a406c9d..cad44d84e80 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -591,6 +591,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } + /** + * The question as {@link search} embeds it: the query prefix, then the + * query, through the embedder (ADR-0161, the dated note of 2026-12-01 under + * K8). Neither changes from source to source, so one vector serves every + * source of this instance. + */ + async embedQuery(query: string): Promise { + const [embedded] = await this.requireEmbedder().embed([`${this.queryPrefix}${query}`]); + return embedded; + } + /** {@link search}'s attempts: again while a completed build switches the source's index under it. */ private async searchAttempts(query: string, opts: AdapterSearchOptions): Promise { for (let attempt = 1; ; attempt++) { @@ -650,11 +661,14 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { { code: 'VALIDATION_ERROR', status: 400 }, ); } - // The query is embedded before a connection is taken — never under - // `keyword`, which makes no query vector. - let vector: number[] = []; + // The query is embedded before a connection is taken, after every refusal + // above — never under `keyword`, which makes no query vector. A search the + // knowledge service hands `queryVector` asks it here instead, so a refusal + // above costs no embedding call (ADR-0161, the dated note of 2026-12-01 + // under K8); its answer serves the search's other calls and is never changed. + let vector: readonly number[] = []; if (mode !== 'keyword') { - const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + const embedded = opts.queryVector === undefined ? await this.embedQuery(query) : await opts.queryVector(); if (!Array.isArray(embedded) || embedded.length !== generation.dim) { throw new Error( `knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 3354b1920e7..14491e09692 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1789,3 +1789,112 @@ describe('knowledge-turso approximate vector index: recall and options', () => { expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 8 })).not.toThrow(); }); }); + +describe('knowledge-turso through KnowledgeService: the question is embedded at most once a search (ADR-0161, the dated note of 2026-12-01 under K8)', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + /** + * `count` built sources of twelve rows each on one adapter instance, all one + * `status`, so a `groupBy: 'status'` search of topK 2 refills each of them. + */ + async function built(extra: Record = {}, count = 1) { + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder, queryPrefix: 'query: ' }); + const rows: Row[] = Array.from({ length: 12 }, (_, i) => ({ id: `r${String(i).padStart(2, '0')}`, body: `granite quarry ${i}`, status: 'published' })); + const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + svc.registerAdapter('under_test', adapter); + const sources = Array.from({ length: count }, () => source(`once_${Math.random().toString(36).slice(2, 8)}`, extra)); + for (const s of sources) { + svc.registerSource(s); + expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 12 }); + } + const searches: Array[1]> = []; + const search = adapter.search.bind(adapter); + adapter.search = async (query, opts) => { + searches.push(opts); + return search(query, opts); + }; + return { svc, embedder, searches, sources }; + } + + /** From now on every embedding call of `embedder` fails, and is still counted. */ + function failing(embedder: FakeEmbedder): void { + embedder.embed = async () => { + embedder.calls += 1; + throw new Error('embedder down at http://10.0.0.7:11434'); + }; + } + + it('a refilled search calls the adapter twice and the embedder once, with the query prefix', async () => { + const { svc, embedder, searches } = await built(); + const calls = embedder.calls; + const texts = embedder.texts.length; + const hits = await svc.search('granite', { topK: 2, groupBy: 'status', executionContext: SYSTEM }); + expect(hits).toHaveLength(1); + // The refill ran: two rounds reached the adapter, each handed the one function. + expect(searches).toHaveLength(2); + expect(typeof searches[0]!.queryVector).toBe('function'); + expect(searches[1]!.queryVector).toBe(searches[0]!.queryVector); + expect(embedder.calls - calls).toBe(1); + expect(embedder.texts.slice(texts)).toEqual(['query: granite']); + }); + + it('a refilled search over two sources of one instance: four adapter calls, one embedding call', async () => { + const { svc, embedder, searches, sources } = await built({}, 2); + const calls = embedder.calls; + await svc.search('granite', { topK: 2, groupBy: 'status', executionContext: SYSTEM }); + expect(searches.map((o) => o.source.name).sort()).toEqual([...sources, ...sources].map((s) => s.name).sort()); + expect(embedder.calls - calls).toBe(1); + }); + + it('a keyword search embeds nothing, on either round', async () => { + const { svc, embedder, searches } = await built({ retrieval: { mode: 'keyword' } }); + const calls = embedder.calls; + await svc.search('granite', { topK: 2, groupBy: 'status', executionContext: SYSTEM }); + expect(searches).toHaveLength(2); + expect(embedder.calls).toBe(calls); + }); + + it('a source that needs a rebuild, behind an embedder that fails, answers KNOWLEDGE_REBUILD_REQUIRED 409 with 0 embedder calls', async () => { + const { svc, embedder, searches } = await built(); + // An embedder setting saved with another model and a key that fails: the + // fingerprint moves and every embedding call fails, together. + embedder.model = 'another-model'; + failing(embedder); + const calls = embedder.calls; + const refused = await svc.searchWithRefusals('granite', { topK: 2, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + expect(searches).toHaveLength(1); + expect(embedder.calls - calls).toBe(0); + }); + + it('the control: the same failing embedder behind a healthy source is called once and refuses it 503', async () => { + const { svc, embedder } = await built(); + failing(embedder); + const calls = embedder.calls; + const refused = await svc.searchWithRefusals('granite', { topK: 2, executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(embedder.calls - calls).toBe(1); + }); + + it('a handed queryVector is ranked with, and the embedder is not called; a vector of another width is refused', async () => { + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder }); + const s = source('handed'); + await adapter.upsert([doc(s, '1', 'granite quarry'), doc(s, '2', 'basalt column')], ctx(s)); + const basalt: readonly number[] = await adapter.embedQuery('basalt'); + const calls = embedder.calls; + const hits = await adapter.search('granite', { source: s, topK: 1, retrieval: { mode: 'vector' }, queryVector: async () => basalt }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:2`]); + expect(embedder.calls).toBe(calls); + // The control: without the member, the query itself is embedded and ranked. + const own = await adapter.search('granite', { source: s, topK: 1, retrieval: { mode: 'vector' } }); + expect(own.map((h) => h.documentId)).toEqual([`${s.name}:1`]); + expect(embedder.calls).toBe(calls + 1); + const refused = await adapter + .search('granite', { source: s, topK: 1, queryVector: async () => basalt.slice(1) }) + .catch((e: unknown) => e as Error); + expect(String((refused as Error).message)).toContain('63-wide query vector'); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 0862fcbce35..81e73a20bf7 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -29,6 +29,7 @@ for (const kind of ['memory', 'file'] as const) { dropSource: true, keywordLeg: true, retrieval: true, + embedQuery: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 248f40bf932..375a1674186 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -693,6 +693,17 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return this.searchAttempt(query, opts, 1); } + /** + * The question as {@link search} embeds it: the query prefix, then the + * query, through the embedder (ADR-0161, the dated note of 2026-12-01 under + * K8). Neither changes from source to source, so one vector serves every + * source of this instance. + */ + async embedQuery(query: string): Promise { + const [embedded] = await this.requireEmbedder().embed([`${this.queryPrefix}${query}`]); + return embedded; + } + /** One attempt of {@link search}; `attempt` counts the generation switches met so far. */ private async searchAttempt(query: string, opts: AdapterSearchOptions, attempt: number): Promise { // An empty organization set ranks nothing (ADR-0161 K8, item 9). @@ -734,11 +745,14 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { { code: 'VALIDATION_ERROR', status: 400 }, ); } - // The query is embedded before the database is read — never under - // `keyword`, which makes no query vector. - let vector: number[] = []; + // The query is embedded before the database is read, after every refusal + // above — never under `keyword`, which makes no query vector. A search the + // knowledge service hands `queryVector` asks it here instead, so a refusal + // above costs no embedding call (ADR-0161, the dated note of 2026-12-01 + // under K8); its answer serves the search's other calls and is never changed. + let vector: readonly number[] = []; if (mode !== 'keyword') { - const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + const embedded = opts.queryVector === undefined ? await this.embedQuery(query) : await opts.queryVector(); if (!Array.isArray(embedded) || embedded.length !== active.dim) { throw new Error( `knowledge-turso: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + diff --git a/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts new file mode 100644 index 00000000000..09bc17b75d9 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts @@ -0,0 +1,233 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The question of one search is embedded at most once for each adapter +// instance (ADR-0161, the dated note of 2026-12-01 under K8). The service +// hands every `search` call to an instance that has `embedQuery` one function +// for the whole search, `queryVector`; its first call asks `embedQuery`, every +// later call answers the same promise, a rejected one too. The service judges +// nothing about a call and reads no vector: the adapter asks where it embeds, +// after its own refusals, so a refused source and a `keyword` search cost no +// embedding call. An adapter without `embedQuery` is handed nothing. + +import { describe, it, expect, vi } from 'vitest'; +import { KnowledgeService, SEARCH_FIRST_ROUND_FACTOR } from '../knowledge-service.js'; +import type { AdapterSearchOptions, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeHit, KnowledgeRetrievalMode, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; + +const SYSTEM = { positions: [], permissions: [], isSystem: true }; +const TOP_K = 3; +const VECTOR = [0.6, 0.8]; +const REBUILD = Object.assign(new Error("Knowledge source 'stale' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + +function source(name: string, adapter: string, mode?: KnowledgeRetrievalMode): KnowledgeSource { + return { + name, + label: name, + adapter, + source: { + kind: 'object', + object: 'task', + content: ['title'], + metadataFields: ['status'], + ...(mode === undefined ? {} : { retrieval: { mode } }), + } as ObjectKnowledgeSource, + }; +} + +function hit(sourceId: string, record: string, n: number): KnowledgeHit { + return { chunkId: `${sourceId}:${record}#${n}`, documentId: `${sourceId}:${record}`, sourceId, sourceRecordId: record, score: 1 - n / 1000, snippet: 'ok' }; +} + +/** + * An adapter shaped as the two stores are: its `search` first answers what it + * decides without a vector (nothing to rank, a source it refuses, `keyword`), + * then takes the question's vector where it embeds, from `queryVector` when + * handed one, else from its own embed (counted by `embeds`). Every search + * fills its ask with passages of one record, so a record-level search refills. + */ +function adapter(id: string, opts: { embedQuery?: IKnowledgeAdapter['embedQuery']; refuses?: string[] } = {}) { + const seen: AdapterSearchOptions[] = []; + const answered: Array = []; + let embeds = 0; + const search = vi.fn(async (_query: string, o: AdapterSearchOptions) => { + seen.push(o); + if (o.organizationIds?.length === 0) return []; + if (o.scope !== undefined && !o.scope.some((term) => term.ids.length > 0)) return []; + if (opts.refuses?.includes(o.source.name)) throw REBUILD; + if (o.retrieval?.mode !== 'keyword') { + if (o.queryVector === undefined) embeds += 1; + else answered.push(await o.queryVector()); + } + return Array.from({ length: o.topK }, (_, n) => hit(o.source.name, 'r0', n)); + }); + const embedQuery = opts.embedQuery === undefined ? undefined : vi.fn(opts.embedQuery); + const a: IKnowledgeAdapter = { + id, + capabilities: { retrieval: { modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' } }, + upsert: vi.fn(async () => undefined), + delete: vi.fn(async () => undefined), + search, + ...(embedQuery === undefined ? {} : { embedQuery }), + }; + return { adapter: a, search, embedQuery, seen, answered, embeds: () => embeds }; +} + +function setup(adapters: IKnowledgeAdapter[], sources: KnowledgeSource[]) { + const logger = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() }; + const svc = new KnowledgeService({ logger: logger as never }); + for (const a of adapters) svc.registerAdapter(a.id, a); + for (const s of sources) svc.registerSource(s); + return { svc, logger }; +} + +const refilled = { granularity: 'record' as const, topK: TOP_K, executionContext: SYSTEM }; + +describe('knowledge search: the question is embedded at most once for each adapter instance', () => { + it('a refilled search: both rounds are handed one function, and embedQuery is called once', async () => { + const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); + const { svc } = setup([store.adapter], [source('s1', 'vec')]); + await svc.searchWithRefusals('what is due', refilled); + // The refill ran: the second round asked for more than the first. + expect(store.seen.map((o) => o.topK)).toEqual([TOP_K * SEARCH_FIRST_ROUND_FACTOR, expect.any(Number)]); + expect(store.seen[1]!.topK).toBeGreaterThan(store.seen[0]!.topK); + expect(typeof store.seen[0]!.queryVector).toBe('function'); + expect(store.seen[1]!.queryVector).toBe(store.seen[0]!.queryVector); + expect(store.embedQuery).toHaveBeenCalledTimes(1); + expect(store.embedQuery).toHaveBeenCalledWith('what is due'); + expect(store.answered).toEqual([VECTOR, VECTOR]); + expect(store.embeds()).toBe(0); + }); + + it('two sources of one instance, both refilled: one function for all four calls, embedQuery once', async () => { + const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); + const { svc } = setup([store.adapter], [source('s1', 'vec'), source('s2', 'vec')]); + await svc.searchWithRefusals('what is due', refilled); + expect(store.seen).toHaveLength(4); + expect(new Set(store.seen.map((o) => o.queryVector)).size).toBe(1); + expect(store.embedQuery).toHaveBeenCalledTimes(1); + }); + + it('the function answers the same promise on every call of the search', async () => { + let resolve!: (v: number[]) => void; + const store = adapter('vec', { embedQuery: () => new Promise((r) => (resolve = r)) }); + const { svc } = setup([store.adapter], [source('s1', 'vec')]); + store.search.mockImplementationOnce(async (_q, o) => { + const first = o.queryVector!(); + expect(o.queryVector!()).toBe(first); + resolve([...VECTOR]); + expect(await first).toEqual(VECTOR); + return []; + }); + await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }); + expect(store.embedQuery).toHaveBeenCalledTimes(1); + }); + + it('two instances: each is handed its own function and embeds the question once, its own way', async () => { + const one = adapter('one', { embedQuery: async () => [1, 0] }); + const two = adapter('two', { embedQuery: async () => [0, 1] }); + const { svc } = setup([one.adapter, two.adapter], [source('s1', 'one'), source('s2', 'two')]); + await svc.searchWithRefusals('what is due', refilled); + expect(one.embedQuery).toHaveBeenCalledTimes(1); + expect(two.embedQuery).toHaveBeenCalledTimes(1); + expect(one.seen[0]!.queryVector).not.toBe(two.seen[0]!.queryVector); + expect(one.answered).toEqual([[1, 0], [1, 0]]); + expect(two.answered).toEqual([[0, 1], [0, 1]]); + }); + + it('two searches: each makes its own function and its own embedding call', async () => { + const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); + const { svc } = setup([store.adapter], [source('s1', 'vec')]); + await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }); + await svc.searchWithRefusals('what is late', { executionContext: SYSTEM }); + expect(store.embedQuery?.mock.calls).toEqual([['what is due'], ['what is late']]); + expect(store.seen[1]!.queryVector).not.toBe(store.seen[0]!.queryVector); + }); + + it('a keyword search is handed the function on both rounds, and embeds nothing: the adapter never asks', async () => { + const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); + const { svc } = setup([store.adapter], [source('s1', 'vec', 'keyword')]); + await svc.searchWithRefusals('what is due', refilled); + expect(store.seen).toHaveLength(2); + expect(store.seen.every((o) => typeof o.queryVector === 'function')).toBe(true); + expect(store.embedQuery).not.toHaveBeenCalled(); + }); + + it('a source its adapter refuses ahead of its embed answers that refusal, with no embedding call, behind an embedder that fails', async () => { + const store = adapter('vec', { + refuses: ['stale'], + embedQuery: async () => { + throw new Error('embedder down at http://10.0.0.7:11434'); + }, + }); + const { svc } = setup([store.adapter], [source('stale', 'vec')]); + const refused = await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect(store.embedQuery).not.toHaveBeenCalled(); + }); + + it('an adapter without embedQuery is handed nothing and embeds on each call, as before', async () => { + const store = adapter('plain'); + const { svc } = setup([store.adapter], [source('s1', 'plain')]); + await svc.searchWithRefusals('what is due', refilled); + expect(store.seen).toHaveLength(2); + expect(store.seen.every((o) => !('queryVector' in o))).toBe(true); + expect(store.embeds()).toBe(2); + }); + + it('an embed that fails uncoded fails the search call that asked, refused as any search throw is', async () => { + const store = adapter('vec', { + embedQuery: async () => { + throw new Error('embedder down at http://10.0.0.7:11434'); + }, + }); + const other = adapter('plain'); + const { svc, logger } = setup([store.adapter, other.adapter], [source('s1', 'vec'), source('s2', 'plain')]); + const report = await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }); + expect(store.search).toHaveBeenCalledTimes(1); + expect(report.refused).toEqual([ + { + sourceId: 's1', + code: 'SERVICE_UNAVAILABLE', + status: 503, + message: "[knowledge] source 's1' could not be searched: its adapter 'vec' failed.", + }, + ]); + expect(new Set(report.hits.map((h) => h.sourceId))).toEqual(new Set(['s2'])); + expect(logger.error.mock.calls.some(([line]) => String(line).includes('10.0.0.7'))).toBe(true); + }); + + it("a coded embed failure reaches the adapter as embedQuery threw it, and keeps its code and message", async () => { + const thrown = Object.assign(new Error('No embedder is registered.'), { code: 'SERVICE_UNAVAILABLE', status: 503 }); + const store = adapter('vec', { + embedQuery: async () => { + throw thrown; + }, + }); + const reached: unknown[] = []; + store.search.mockImplementationOnce(async (_q, o) => { + reached.push(await o.queryVector!().catch((e: unknown) => e)); + throw reached[0]; + }); + const other = adapter('plain'); + const { svc } = setup([store.adapter, other.adapter], [source('s1', 'vec'), source('s2', 'plain')]); + const report = await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }); + expect(reached).toEqual([thrown]); + expect(reached[0]).toBe(thrown); + expect(report.refused).toEqual([ + expect.objectContaining({ sourceId: 's1', code: 'SERVICE_UNAVAILABLE', status: 503, message: 'No embedder is registered.' }), + ]); + }); + + it('a failed embed is shared: one call, and each source of the instance that asked is refused', async () => { + const store = adapter('vec', { + embedQuery: async () => { + throw new Error('embedder down'); + }, + }); + const { svc } = setup([store.adapter], [source('s1', 'vec'), source('s2', 'vec')]); + const refused = await svc.searchWithRefusals('what is due', { executionContext: SYSTEM }).catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(store.search).toHaveBeenCalledTimes(2); + expect(store.embedQuery).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index 8a55d42a68b..69507354c0c 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -62,6 +62,7 @@ import { SEARCH_FIRST_ROUND_FACTOR, SEARCH_FRESHNESS_ROUNDS, SEARCH_REFILL_FACTOR, + type SearchQuestion, type SearchTarget, UNMOUNTED_ADAPTER_CODE, UNPROVEN_CALLER_TEXT, @@ -764,6 +765,16 @@ export async function planSearches( // The settings page's chunk target, read at most once for the whole search. let target: Promise | undefined; const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); + // One slot per adapter instance that has `embedQuery`, shared by every + // source the search binds to it and by both rounds: it holds the one + // function the search hands that instance as `queryVector` + // ({@link searchRound}; ADR-0161, the dated note of 2026-12-01 under K8). + const questions = new Map(); + const questionFor = (adapter: IKnowledgeAdapter): SearchQuestion => { + let slot = questions.get(adapter); + if (slot === undefined) questions.set(adapter, (slot = {})); + return slot; + }; for (const { proveIndex, ...entry } of admitted) { // The adapter is resolved here, once per search: the proof below is read // from this instance and both rounds search this instance, so a source @@ -829,7 +840,12 @@ export async function planSearches( } out.push({ ...entry, - binding: { adapterId, adapter }, + binding: { + adapterId, + adapter, + // Whether a call embeds is the adapter's to decide, never judged here. + ...(typeof adapter.embedQuery === 'function' ? { question: questionFor(adapter) } : {}), + }, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}), ...(retrieval.mode === undefined ? {} : { retrieval: { mode: retrieval.mode } }), @@ -912,6 +928,20 @@ export async function unprovenIndex(plan: IndexPlan): Promise<{ why: string; end return undefined; } +/** + * The function one search hands one adapter instance as + * `AdapterSearchOptions.queryVector` (ADR-0161, the dated note of 2026-12-01 + * under K8): its first call runs `embed`, the instance's `embedQuery` for the + * search's query; every later call answers the same promise, a rejected one + * too. A rejection is `embedQuery`'s own error, never wrapped, and reaches the + * adapter that asked; nothing here reads the vector. + */ +function memoisedQuestion(embed: () => Promise): () => Promise { + let vector: Promise | undefined; + // `async` turns a synchronous throw of `embed` into the same rejected promise. + return () => (vector ??= (async () => embed())()); +} + /** * One round of {@link search}: ask each source's adapter for `ask(source)` * hits. Answers, per source that answered, the hits it serves and how many @@ -952,7 +982,17 @@ export async function searchRound( if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); continue; } - const { adapterId, adapter } = binding; + const { adapterId, adapter, question } = binding; + // The one function this search hands this instance, made by its first + // call: the adapter calls it where it embeds the query, after its own + // refusals, so a failed embed is the adapter's throw and is refused below + // as any throw from `search` is (ADR-0161, the dated note of 2026-12-01 + // under K8). + const embedQuery = adapter.embedQuery; + const queryVector = + question === undefined || embedQuery === undefined + ? undefined + : (question.queryVector ??= memoisedQuestion(() => embedQuery.call(adapter, query))); try { const hits = await adapter.search(query, { source, @@ -962,6 +1002,7 @@ export async function searchRound( ...(fingerprint === undefined ? {} : { index: { fingerprint } }), ...(scope === undefined ? {} : { scope: scope.map((term) => ({ ...term, ids: [...term.ids] })) }), ...(retrieval === undefined ? {} : { retrieval: { mode: retrieval.mode } }), + ...(queryVector === undefined ? {} : { queryVector }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index dc0dc0034e5..a50e0ef8038 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -353,6 +353,17 @@ export const UNPROVEN_OPERATOR_TEXT: Readonly> = { */ export const INDEX_NOT_PROVEN_CODE = 'KNOWLEDGE_REBUILD_REQUIRED'; +/** + * What one search hands one adapter instance that has `embedQuery` + * (ADR-0161, the dated note of 2026-12-01 under K8): `queryVector` is the + * function handed as `AdapterSearchOptions.queryVector` on every `search` + * call to that instance in the search, made by the round's first call to it + * ({@link KnowledgeService.searchRound}). + */ +export interface SearchQuestion { + queryVector?: () => Promise; +} + export interface SearchTarget { source: KnowledgeSource; /** @@ -360,7 +371,18 @@ export interface SearchTarget { * ({@link KnowledgeService.planSearches}), or the coded refusal its * resolution answered (`undefined`: an uncoded failure, skipped unsearched). */ - binding: { adapterId: string; adapter: IKnowledgeAdapter } | { refusal: Omit | undefined }; + binding: + | { + adapterId: string; + adapter: IKnowledgeAdapter; + /** + * The slot of this adapter instance for this search, shared by every + * source the search binds to the instance and by both rounds. + * Absent: the adapter has no `embedQuery`. + */ + question?: SearchQuestion; + } + | { refusal: Omit | undefined }; organizationIds?: string[]; fingerprint?: string; scope?: AdapterScopeTerm[]; diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 55202a5f3ca..1ecea54fbe5 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -83,6 +83,13 @@ * source declares, or its own default, or nothing when it reports no modes; * a declared mode it does not list is refused at registration and at every * search, and the source still indexes. + * + * An adapter that declares `embedQuery` (ADR-0161, the dated note of + * 2026-12-01 under K8), handed as `queryVector` a function that answers its + * own `embedQuery` for the query, answers what it answers without the member + * and makes no embedding call of its own, counted by a spy on the instance's + * `embedQuery`; handed one that answers a vector of another width, its + * search rejects. */ import { describe, expect, it, vi } from 'vitest'; @@ -171,6 +178,20 @@ export interface KnowledgeAdapterContractOptions { * Absent: `false`. */ retrieval?: boolean; + /** + * `embedQuery` (ADR-0161, the dated note of 2026-12-01 under K8): the + * adapter embeds a question as its `search` does, and its `search` takes + * the question's vector from `AdapterSearchOptions.queryVector` when handed + * one. Asserted by behaviour, on the adapter alone: handed a function that + * answers its own `embedQuery` for the query, a search answers what it + * answers without the member and makes no embedding call of its own; + * handed one that answers a vector of another width, it rejects. The + * suite counts embedding calls by a spy on the instance's `embedQuery`, so + * it reads an adapter whose `search` embeds the query through that method, + * as `knowledge-turso` and `knowledge-pgvector` do; the case's control + * fails for one that embeds by another path. Absent: `false`. + */ + embedQuery?: boolean; }; } @@ -534,6 +555,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); expect(adapter.capabilities?.retrieval !== undefined).toBe(opts.implements.retrieval === true); + expect(typeof adapter.embedQuery === 'function').toBe(opts.implements.embedQuery === true); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -667,6 +689,49 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + if (opts.implements.embedQuery === true) { + describe('embedQuery and queryVector (ADR-0161, the dated note of 2026-12-01 under K8)', () => { + it('handed a function answering its own embedQuery, a search answers as without it and makes no embedding call; another width rejects', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('query_vector'); + await adapter.upsert( + [doc(a, '1', 'alpine meadow flowers'), doc(a, '2', 'harbour cranes at night'), doc(a, '3', 'alpine glacier ice')], + ctxOf(a), + ); + const QUERY = 'alpine meadow'; + // The count: a spy on this instance's `embedQuery`. + const embedQuery = vi.spyOn(adapter as Required>, 'embedQuery'); + const without = await adapter.search(QUERY, { source: a, topK: 3 }); + // The control: without the member the search embeds the question + // itself, and the spy sees that call. + expect(embedQuery).toHaveBeenCalledTimes(1); + expect(without.length).toBeGreaterThan(0); + const vector: readonly number[] = await adapter.embedQuery!(QUERY); + embedQuery.mockClear(); + + let asked = 0; + const handed = await adapter.search(QUERY, { + source: a, + topK: 3, + queryVector: async () => { + asked += 1; + return vector; + }, + }); + expect(handed).toEqual(without); + expect(asked).toBeGreaterThan(0); + expect(embedQuery).not.toHaveBeenCalled(); + + const wider = [...vector, 0]; + await expect(adapter.search(QUERY, { source: a, topK: 3, queryVector: async () => wider })).rejects.toBeDefined(); + const narrower = vector.slice(1); + await expect(adapter.search(QUERY, { source: a, topK: 3, queryVector: async () => narrower })).rejects.toBeDefined(); + expect(embedQuery).not.toHaveBeenCalled(); + embedQuery.mockRestore(); + }); + }); + } + if (opts.implements.organizationIds) { describe('organizationIds (ADR-0161 K8, item 9)', () => { /** B's document outranks A's; a third document carries no organization. */ diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index b62c7af7d17..eb1bab4ea14 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -199,6 +199,33 @@ export interface AdapterSearchOptions { * a one-leg mode they reflect rank alone. */ retrieval?: { mode: KnowledgeRetrievalMode }; + /** + * The question's vector, as a function the adapter calls at the point where + * its `search` embeds the query (ADR-0161, the dated note of 2026-12-01 + * under K8). The knowledge service hands it on every `search` call it makes + * to an adapter instance that has {@link IKnowledgeAdapter.embedQuery}, and + * judges nothing about the call: one function per instance per search, whose + * first call asks that instance's `embedQuery` for `query`, and whose every + * later call in the search (another source of the instance, the refill + * round, the adapter's own retry) answers the same promise, a rejected one + * too. The service reads no vector. + * + * - **Present**: call it in place of the query's embedding call, after + * everything the search decides first (whether anything is ranked, the + * store and embedder being present and ready, the active generation, the + * fingerprint and width refusal `KNOWLEDGE_REBUILD_REQUIRED`, the mode), so + * a refusal there is the one answered and costs no embedding call. Under + * `keyword`, which makes no query vector, never call it. Check the answer's + * width as a vector the embedder answered is checked, and never change the + * array: it serves the search's other calls. A rejection fails the + * `search` call that asked, as a failed embedding call does. + * - **Absent**: embed the query as before this member. + * + * A caller that hands it directly answers for the function: that it answers + * this instance's own `embedQuery` for this query. The adapter does not + * verify it. + */ + queryVector?: () => Promise; /** Trace id for correlation. */ traceId?: string; } @@ -375,6 +402,23 @@ export interface IKnowledgeAdapter { /** Run a search query. Returns hits sorted by descending score. */ search(query: string, opts: AdapterSearchOptions): Promise; + /** + * Embed a search question exactly as this adapter's `search` embeds it: + * through its embedder, with its query-side options such as a query prefix + * (ADR-0161, the dated note of 2026-12-01 under K8; K8, item 15). It takes + * no source and no context, so one vector serves every source of the + * instance: an adapter whose query embedding differs from source to source + * does not implement it. + * + * Its presence is the signal. The knowledge service then hands every + * `search` call of a search {@link AdapterSearchOptions.queryVector}, a + * function that calls this method at most once for this instance in that + * search, and only when the adapter's `search` asks for the vector. An + * adapter without it is handed nothing and embeds the question on every + * `search` call, as before this member. + */ + embedQuery?(query: string): Promise; + /** Remove documents by id. */ delete(documentIds: string[], ctx: AdapterContext): Promise;