From c5500285d7408532960015cf4d6aa2297a7b0d89 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:36:05 +0000 Subject: [PATCH 1/9] feat(knowledge): embed the search question once per search and hand the vector to every round The knowledge service now embeds a question at most once per adapter per search, through the adapter's new optional embedQuery, and hands the vector to both the first round and the refill as AdapterSearchOptions.queryVector. turso and pgvector implement embedQuery and rank with a handed vector instead of embedding again. A keyword search embeds nothing; an adapter without embedQuery embeds on every call, as before. Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../src/pgvector-adapter.ts | 13 ++++-- .../src/__tests__/acceptance.test.ts | 44 +++++++++++++++++++ .../knowledge-turso/src/turso-adapter.ts | 13 ++++-- .../src/knowledge-service-search.ts | 30 ++++++++++++- .../src/knowledge-service-top-level.ts | 15 ++++++- .../spec/src/contracts/knowledge-adapter.ts | 29 ++++++++++++ 6 files changed, 135 insertions(+), 9 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index ef41a406c9d..e4930f62894 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -591,6 +591,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } + /** The question as {@link search} embeds it: the query prefix, then the query, through the embedder. */ + 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++) { @@ -651,10 +657,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ); } // The query is embedded before a connection is taken — never under - // `keyword`, which makes no query vector. - let vector: number[] = []; + // `keyword`, which makes no query vector — unless the service handed the + // vector `embedQuery` answered for this search. + let vector: readonly number[] = []; if (mode !== 'keyword') { - const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + const embedded = opts.queryVector ?? (await this.embedQuery(query)); 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..0f706c15cd5 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1789,3 +1789,47 @@ 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 once a search', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + /** A built source of twelve rows, all one `status`, so a `groupBy: 'status'` search of topK 2 refills. */ + async function built(extra: Record = {}) { + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder, queryPrefix: 'query: ' }); + const s = source(`once_${Math.random().toString(36).slice(2, 8)}`, extra); + 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); + 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 }; + } + + 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. + expect(searches).toHaveLength(2); + expect(embedder.calls - calls).toBe(1); + expect(embedder.texts.slice(texts)).toEqual(['query: granite']); + }); + + 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); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 248f40bf932..d33df69e3dd 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -693,6 +693,12 @@ 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. */ + 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). @@ -735,10 +741,11 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); } // The query is embedded before the database is read — never under - // `keyword`, which makes no query vector. - let vector: number[] = []; + // `keyword`, which makes no query vector — unless the service handed the + // vector `embedQuery` answered for this search. + let vector: readonly number[] = []; if (mode !== 'keyword') { - const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]); + const embedded = opts.queryVector ?? (await this.embedQuery(query)); 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/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index 8a55d42a68b..2bd0bd92ffa 100644 --- a/packages/services/service-knowledge/src/knowledge-service-search.ts +++ b/packages/services/service-knowledge/src/knowledge-service-search.ts @@ -764,6 +764,15 @@ 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()); + // The question is embedded once a search per adapter that can embed it for + // the service (`embedQuery`): one slot per adapter, shared by its sources and + // by both rounds, filled by the first call that needs it ({@link searchRound}). + const questions = new Map }>(); + const questionFor = (adapter: IKnowledgeAdapter): { vector?: Promise } => { + 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 +838,12 @@ export async function planSearches( } out.push({ ...entry, - binding: { adapterId, adapter }, + binding: { + adapterId, + adapter, + // A `keyword` search makes no query vector, so nothing is embedded for it. + ...(typeof adapter.embedQuery === 'function' && retrieval.mode !== 'keyword' ? { question: questionFor(adapter) } : {}), + }, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}), ...(retrieval.mode === undefined ? {} : { retrieval: { mode: retrieval.mode } }), @@ -952,8 +966,19 @@ 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; try { + // The question's vector, embedded by the first call of this search that + // needs it and handed to every later one, the refill included. Not for a + // search that ranks nothing (an empty organization set, a scope with no + // ids), which the adapter answers without embedding. A throw here is + // refused below exactly as a throw from `search` is. + const ranksNothing = + organizationIds?.length === 0 || (scope !== undefined && !scope.some((term) => term.ids.length > 0)); + const embedQuery = adapter.embedQuery; + const queryVector = question === undefined || embedQuery === undefined || ranksNothing + ? undefined + : await (question.vector ??= embedQuery.call(adapter, query)); const hits = await adapter.search(query, { source, topK: ask(source), @@ -962,6 +987,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..e752568265c 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -360,7 +360,20 @@ 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 question's vector for this search, shared by every source the + * search binds to this adapter: filled by the first round that needs it + * (`IKnowledgeAdapter.embedQuery`) and handed to every later call as + * `AdapterSearchOptions.queryVector`. Absent: the adapter has no + * `embedQuery`, or the source's mode embeds nothing (`keyword`). + */ + question?: { vector?: Promise }; + } + | { refusal: Omit | undefined }; organizationIds?: string[]; fingerprint?: string; scope?: AdapterScopeTerm[]; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index b62c7af7d17..5bf081cda49 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -199,6 +199,21 @@ export interface AdapterSearchOptions { * a one-leg mode they reflect rank alone. */ retrieval?: { mode: KnowledgeRetrievalMode }; + /** + * The question's vector, as this adapter's own {@link IKnowledgeAdapter.embedQuery} + * answered it for `query` during this search. The knowledge service embeds + * a question once per search and hands the vector to every call it makes + * for that search, the refill round included; it hands this member only to + * an adapter that has `embedQuery`, and only under a mode that embeds. + * + * - **Present**: rank with this vector, and do not call the embedder for + * the query. Check its width as a vector the embedder answered is + * checked. + * - **Absent**: embed the query as before this member. + * + * Never handed under the `keyword` mode, which makes no query vector. + */ + queryVector?: readonly number[]; /** Trace id for correlation. */ traceId?: string; } @@ -375,6 +390,20 @@ 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 + * (its embedder, and any query-side option such as a query prefix), so the + * vector can be handed back as `AdapterSearchOptions.queryVector`. + * + * The knowledge service calls it at most once per adapter per search, and + * only for a source searched under a mode that embeds (not `keyword`); a + * search that rounds twice (a refill) hands the same vector to both calls. + * A throw refuses each source it was embedded for, as a throw from `search` + * does: a coded refusal keeps its code. An adapter without it keeps working, + * 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; From 9509bed61f0115a02f2b60f5ea4dc62429dc7281 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:38:19 +0000 Subject: [PATCH 2/9] test(knowledge): pin one embed per search on the service, turso and pgvector Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../src/__tests__/retrieval-modes.test.ts | 44 +++++ .../src/__tests__/acceptance.test.ts | 20 ++ .../__tests__/search-question-vector.test.ts | 187 ++++++++++++++++++ 3 files changed, 251 insertions(+) create mode 100644 packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts 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..1daa481572f 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,50 @@ 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 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!); + await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector: handed }); + 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: [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-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 0f706c15cd5..9be08d41c71 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1832,4 +1832,24 @@ describe('knowledge-turso through KnowledgeService: the question is embedded onc expect(searches).toHaveLength(2); expect(embedder.calls).toBe(calls); }); + + 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 = await adapter.embedQuery('basalt'); + const calls = embedder.calls; + const hits = await adapter.search('granite', { source: s, topK: 1, retrieval: { mode: 'vector' }, queryVector: basalt }); + expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:2`]); + expect(embedder.calls).toBe(calls); + // The control: without the vector, 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: basalt.slice(1) }) + .catch((e: unknown) => e as Error); + expect(String((refused as Error).message)).toContain('63-wide query vector'); + }); }); 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..62ddfb4c85a --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts @@ -0,0 +1,187 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The question of one search is embedded once: the service asks an adapter +// that has `embedQuery` for the vector at most once per search, and hands it to +// every `search` call of that search as `queryVector`, the refill round +// included. A keyword search embeds nothing; a search that ranks nothing +// embeds nothing; an adapter without `embedQuery` is searched as before, and +// an embed that throws is refused for its source as a `search` throw is. + +import { describe, it, expect, vi } from 'vitest'; +import { KnowledgeService, SEARCH_FIRST_ROUND_FACTOR } from '../knowledge-service.js'; +import { searchRound } from '../knowledge-service-search.js'; +import type { KnowledgeSearchRefusal, SearchTarget } from '../knowledge-service-top-level.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]; + +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 whose every search fills its ask with passages of one record, so + * a record-level search refills it. `embeds` counts what a search without a + * handed vector would have embedded (the adapter's own embed on each call). + */ +function adapter(id: string, opts: { embedQuery?: IKnowledgeAdapter['embedQuery'] } = {}) { + const seen: AdapterSearchOptions[] = []; + let embeds = 0; + const search = vi.fn(async (_query: string, o: AdapterSearchOptions) => { + seen.push(o); + if (o.queryVector === undefined && o.retrieval?.mode !== 'keyword') embeds += 1; + 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, 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 once a search', () => { + it('a refilled search: embedQuery once, and both rounds handed the same vector', 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(store.embedQuery).toHaveBeenCalledTimes(1); + expect(store.embedQuery).toHaveBeenCalledWith('what is due'); + expect(store.seen.map((o) => o.queryVector)).toEqual([VECTOR, VECTOR]); + expect(store.embeds()).toBe(0); + }); + + it('two sources on one adapter, both refilled: embedQuery once for the whole search', 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(store.embedQuery).toHaveBeenCalledTimes(1); + expect(store.seen.every((o) => o.queryVector === store.seen[0]!.queryVector)).toBe(true); + }); + + it('two adapters: each 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.map((o) => o.queryVector)).toEqual([[1, 0], [1, 0]]); + expect(two.seen.map((o) => o.queryVector)).toEqual([[0, 1], [0, 1]]); + }); + + it('a keyword search embeds nothing and hands no vector, on either round', 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.embedQuery).not.toHaveBeenCalled(); + expect(store.seen.every((o) => !('queryVector' in o))).toBe(true); + }); + + it('an adapter without embedQuery is searched as before: no vector handed, its own embed on each call', 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 throws uncoded refuses its source as a search throw does, and the adapter is not searched', 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).not.toHaveBeenCalled(); + 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('an embed that throws a coded refusal keeps its code and message', async () => { + const store = adapter('vec', { + embedQuery: async () => { + throw Object.assign(new Error('No embedder is registered.'), { code: 'SERVICE_UNAVAILABLE', status: 503 }); + }, + }); + 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(report.refused).toEqual([ + expect.objectContaining({ sourceId: 's1', code: 'SERVICE_UNAVAILABLE', status: 503, message: 'No embedder is registered.' }), + ]); + }); + + it('a round that ranks nothing (an empty organization set, a scope with no ids) embeds nothing', async () => { + const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); + const host = { checkScope: (hits: KnowledgeHit[]) => hits, label: (s: KnowledgeSource) => s.name, options: {} }; + const target = (name: string, extra: Partial): SearchTarget => ({ + source: source(name, 'vec'), + binding: { adapterId: 'vec', adapter: store.adapter, question: {} }, + ...extra, + }); + const refused: KnowledgeSearchRefusal[] = []; + await searchRound.call( + host as never, + 'what is due', + [target('s1', { organizationIds: [] }), target('s2', { scope: [{ kind: 'record', ids: [] }] })], + () => TOP_K, + undefined, + refused, + ); + expect(store.embedQuery).not.toHaveBeenCalled(); + expect(store.seen.every((o) => !('queryVector' in o))).toBe(true); + // The control: the same round with ids to rank embeds once. + await searchRound.call(host as never, 'what is due', [target('s3', { scope: [{ kind: 'record', ids: ['r0'] }] })], () => TOP_K, undefined, refused); + expect(store.embedQuery).toHaveBeenCalledTimes(1); + expect(refused).toEqual([]); + }); +}); From 7340b38573b7651f6df96904ed360c5d713dfb05 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 18:43:33 +0000 Subject: [PATCH 3/9] chore(changeset): the search question is embedded once per search Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .changeset/38676-embed-question-once.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/38676-embed-question-once.md diff --git a/.changeset/38676-embed-question-once.md b/.changeset/38676-embed-question-once.md new file mode 100644 index 00000000000..61510fb18f5 --- /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 once, the refill round included + +Clause-②: yes (widening) +Metadata-protocol: none + +Widened: `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`. An adapter handed a `queryVector` ranks with it and does not call its embedder for the query; it checks the vector's width as it checks one its embedder answered. + +The knowledge service calls `embedQuery` at most once per adapter per search and hands the vector to every `search` call of that search. 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 now share the one embed too. A `keyword` search, and a round that ranks nothing (an empty organization set, a scope with no ids), embed nothing. An embed that fails refuses each source it was needed for, with the same code and wording as a failed `search`. + +`knowledge-turso` and `knowledge-pgvector` implement `embedQuery`. An adapter without it, such as `knowledge-memory`, is searched as before and embeds on every call. From 56feee7fa7c96e7415b9a5a3379175b1ec4600f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:37:39 +0000 Subject: [PATCH 4/9] test(knowledge-pgvector): the bench counts one embed for a refilled search Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../plugins/knowledge-pgvector/bench/instrument.test.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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). From 4561e81d0e6e04381e99c12fae05da9e07555cc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 19:44:35 +0000 Subject: [PATCH 5/9] docs(knowledge): the adapter contract lists embedQuery and the vector it hands back Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 51dad452a8f..f3d5bc75c1c 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 search embeds it delete(documentIds: string[], ctx: AdapterContext): Promise; listDocuments?( ctx: AdapterContext, @@ -564,6 +565,11 @@ 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` does (its +embedder, its query prefix). The service calls it at most once per adapter per +search, never under `keyword`, and hands the vector back as +`AdapterSearchOptions.queryVector` to every call of that search, the refill +included; an adapter without it 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 From a953b5bd4f1bb4197ea5fd3ca4cb6573db88186b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 04:57:15 +0000 Subject: [PATCH 6/9] feat(knowledge): queryVector is a per-search function the adapter calls where it embeds The knowledge service no longer embeds the question ahead of search. It hands every search call to an adapter instance that has embedQuery one memoised function per instance per search; turso and pgvector call it at the line where they embed today, after every refusal they answer first (ADR-0161, the dated note of 2026-12-01 under K8). Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../src/pgvector-adapter.ts | 17 ++++-- .../knowledge-turso/src/turso-adapter.ts | 17 ++++-- .../src/knowledge-service-search.ts | 51 +++++++++++------- .../src/knowledge-service-top-level.ts | 21 +++++--- .../spec/src/contracts/knowledge-adapter.ts | 53 ++++++++++++------- 5 files changed, 106 insertions(+), 53 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index e4930f62894..cad44d84e80 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -591,7 +591,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } - /** The question as {@link search} embeds it: the query prefix, then the query, through the embedder. */ + /** + * 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; @@ -656,12 +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 — unless the service handed the - // vector `embedQuery` answered for this search. + // 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 = opts.queryVector ?? (await this.embedQuery(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/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index d33df69e3dd..375a1674186 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -693,7 +693,12 @@ 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. */ + /** + * 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; @@ -740,12 +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 — unless the service handed the - // vector `embedQuery` answered for this search. + // 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 = opts.queryVector ?? (await this.embedQuery(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/knowledge-service-search.ts b/packages/services/service-knowledge/src/knowledge-service-search.ts index 2bd0bd92ffa..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,11 +765,12 @@ 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()); - // The question is embedded once a search per adapter that can embed it for - // the service (`embedQuery`): one slot per adapter, shared by its sources and - // by both rounds, filled by the first call that needs it ({@link searchRound}). - const questions = new Map }>(); - const questionFor = (adapter: IKnowledgeAdapter): { vector?: Promise } => { + // 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; @@ -841,8 +843,8 @@ export async function planSearches( binding: { adapterId, adapter, - // A `keyword` search makes no query vector, so nothing is embedded for it. - ...(typeof adapter.embedQuery === 'function' && retrieval.mode !== 'keyword' ? { question: questionFor(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 } : {}), @@ -926,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 @@ -967,18 +983,17 @@ export async function searchRound( continue; } const { adapterId, adapter, question } = binding; - try { - // The question's vector, embedded by the first call of this search that - // needs it and handed to every later one, the refill included. Not for a - // search that ranks nothing (an empty organization set, a scope with no - // ids), which the adapter answers without embedding. A throw here is - // refused below exactly as a throw from `search` is. - const ranksNothing = - organizationIds?.length === 0 || (scope !== undefined && !scope.some((term) => term.ids.length > 0)); - const embedQuery = adapter.embedQuery; - const queryVector = question === undefined || embedQuery === undefined || ranksNothing + // 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 - : await (question.vector ??= embedQuery.call(adapter, query)); + : (question.queryVector ??= memoisedQuestion(() => embedQuery.call(adapter, query))); + try { const hits = await adapter.search(query, { source, topK: ask(source), 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 e752568265c..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; /** @@ -365,13 +376,11 @@ export interface SearchTarget { adapterId: string; adapter: IKnowledgeAdapter; /** - * The question's vector for this search, shared by every source the - * search binds to this adapter: filled by the first round that needs it - * (`IKnowledgeAdapter.embedQuery`) and handed to every later call as - * `AdapterSearchOptions.queryVector`. Absent: the adapter has no - * `embedQuery`, or the source's mode embeds nothing (`keyword`). + * 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?: { vector?: Promise }; + question?: SearchQuestion; } | { refusal: Omit | undefined }; organizationIds?: string[]; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 5bf081cda49..eb1bab4ea14 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -200,20 +200,32 @@ export interface AdapterSearchOptions { */ retrieval?: { mode: KnowledgeRetrievalMode }; /** - * The question's vector, as this adapter's own {@link IKnowledgeAdapter.embedQuery} - * answered it for `query` during this search. The knowledge service embeds - * a question once per search and hands the vector to every call it makes - * for that search, the refill round included; it hands this member only to - * an adapter that has `embedQuery`, and only under a mode that embeds. + * 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**: rank with this vector, and do not call the embedder for - * the query. Check its width as a vector the embedder answered is - * checked. + * - **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. * - * Never handed under the `keyword` mode, which makes no query vector. + * 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?: readonly number[]; + queryVector?: () => Promise; /** Trace id for correlation. */ traceId?: string; } @@ -391,16 +403,19 @@ export interface IKnowledgeAdapter { search(query: string, opts: AdapterSearchOptions): Promise; /** - * Embed a search question exactly as this adapter's `search` embeds it - * (its embedder, and any query-side option such as a query prefix), so the - * vector can be handed back as `AdapterSearchOptions.queryVector`. + * 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. * - * The knowledge service calls it at most once per adapter per search, and - * only for a source searched under a mode that embeds (not `keyword`); a - * search that rounds twice (a refill) hands the same vector to both calls. - * A throw refuses each source it was embedded for, as a throw from `search` - * does: a coded refusal keeps its code. An adapter without it keeps working, - * and embeds the question on every `search` call, as before this member. + * 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; From 8a392257a02e0b7ba82cfb0574a0787de6c79bb5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:04:29 +0000 Subject: [PATCH 7/9] test(knowledge): pin the per-search queryVector function in the service, both stores and the contract suite Per store: a rebuild-required source behind a failing embedder answers KNOWLEDGE_REBUILD_REQUIRED 409 with 0 embedder calls; keyword embeds nothing; a refilled search over two sources of one instance embeds once. The contract suite gains one embedQuery case, wired into turso and pgvector (ADR-0161, the dated note of 2026-12-01 under K8). Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../__tests__/contract.live-postgres.test.ts | 1 + .../src/__tests__/question-once.test.ts | 142 +++++++++++++++++ .../src/__tests__/retrieval-modes.test.ts | 12 +- .../src/__tests__/acceptance.test.ts | 69 +++++++-- .../src/__tests__/contract.test.ts | 1 + .../__tests__/search-question-vector.test.ts | 146 ++++++++++++------ .../services/service-knowledge/src/testing.ts | 65 ++++++++ 7 files changed, 371 insertions(+), 65 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/question-once.test.ts 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 1daa481572f..fb61301e7b3 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -135,12 +135,18 @@ describe('knowledge-pgvector: a question vector the service hands', () => { expect(vector).toHaveLength(embedder.dimensions); }); - it('a handed queryVector is the one bound into the ranking, and the embedder is not called', async () => { + 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!); - await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector: handed }); + 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(',')}]`); @@ -152,7 +158,7 @@ describe('knowledge-pgvector: a question vector the service hands', () => { 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: [1, 0] }) + .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'); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 9be08d41c71..14491e09692 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1790,27 +1790,40 @@ describe('knowledge-turso approximate vector index: recall and options', () => { }); }); -describe('knowledge-turso through KnowledgeService: the question is embedded once a search', () => { +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()); - /** A built source of twelve rows, all one `status`, so a `groupBy: 'status'` search of topK 2 refills. */ - async function built(extra: Record = {}) { + /** + * `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 s = source(`once_${Math.random().toString(36).slice(2, 8)}`, extra); 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); - svc.registerSource(s); - expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 12 }); + 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 }; + 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 () => { @@ -1819,12 +1832,22 @@ describe('knowledge-turso through KnowledgeService: the question is embedded onc 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. + // 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; @@ -1833,22 +1856,44 @@ describe('knowledge-turso through KnowledgeService: the question is embedded onc 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 = await adapter.embedQuery('basalt'); + 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: basalt }); + 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 vector, the query itself is embedded and ranked. + // 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: basalt.slice(1) }) + .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/services/service-knowledge/src/__tests__/search-question-vector.test.ts b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts index 62ddfb4c85a..4f84d23b77d 100644 --- a/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts +++ b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts @@ -1,22 +1,23 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// The question of one search is embedded once: the service asks an adapter -// that has `embedQuery` for the vector at most once per search, and hands it to -// every `search` call of that search as `queryVector`, the refill round -// included. A keyword search embeds nothing; a search that ranks nothing -// embeds nothing; an adapter without `embedQuery` is searched as before, and -// an embed that throws is refused for its source as a `search` throw is. +// 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 { searchRound } from '../knowledge-service-search.js'; -import type { KnowledgeSearchRefusal, SearchTarget } from '../knowledge-service-top-level.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 { @@ -38,16 +39,25 @@ function hit(sourceId: string, record: string, n: number): KnowledgeHit { } /** - * An adapter whose every search fills its ask with passages of one record, so - * a record-level search refills it. `embeds` counts what a search without a - * handed vector would have embedded (the adapter's own embed on each call). + * 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'] } = {}) { +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.queryVector === undefined && o.retrieval?.mode !== 'keyword') embeds += 1; + 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); @@ -59,7 +69,7 @@ function adapter(id: string, opts: { embedQuery?: IKnowledgeAdapter['embedQuery' search, ...(embedQuery === undefined ? {} : { embedQuery }), }; - return { adapter: a, search, embedQuery, seen, embeds: () => embeds }; + return { adapter: a, search, embedQuery, seen, answered, embeds: () => embeds }; } function setup(adapters: IKnowledgeAdapter[], sources: KnowledgeSource[]) { @@ -72,50 +82,90 @@ function setup(adapters: IKnowledgeAdapter[], sources: KnowledgeSource[]) { const refilled = { granularity: 'record' as const, topK: TOP_K, executionContext: SYSTEM }; -describe('knowledge search: the question is embedded once a search', () => { - it('a refilled search: embedQuery once, and both rounds handed the same vector', async () => { +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.seen.map((o) => o.queryVector)).toEqual([VECTOR, VECTOR]); + expect(store.answered).toEqual([VECTOR, VECTOR]); expect(store.embeds()).toBe(0); }); - it('two sources on one adapter, both refilled: embedQuery once for the whole search', async () => { + 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); - expect(store.seen.every((o) => o.queryVector === store.seen[0]!.queryVector)).toBe(true); }); - it('two adapters: each embeds the question once, its own way', async () => { + 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.map((o) => o.queryVector)).toEqual([[1, 0], [1, 0]]); - expect(two.seen.map((o) => o.queryVector)).toEqual([[0, 1], [0, 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('a keyword search embeds nothing and hands no vector, on either round', async () => { + 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(); - expect(store.seen.every((o) => !('queryVector' in o))).toBe(true); }); - it('an adapter without embedQuery is searched as before: no vector handed, its own embed on each call', async () => { + 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); @@ -124,7 +174,7 @@ describe('knowledge search: the question is embedded once a search', () => { expect(store.embeds()).toBe(2); }); - it('an embed that throws uncoded refuses its source as a search throw does, and the adapter is not searched', async () => { + 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'); @@ -133,7 +183,7 @@ describe('knowledge search: the question is embedded once a search', () => { 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).not.toHaveBeenCalled(); + expect(store.search).toHaveBeenCalledTimes(1); expect(report.refused).toEqual([ { sourceId: 's1', @@ -146,42 +196,38 @@ describe('knowledge search: the question is embedded once a search', () => { expect(logger.error.mock.calls.some(([line]) => String(line).includes('10.0.0.7'))).toBe(true); }); - it('an embed that throws a coded refusal keeps its code and message', async () => { + 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 Object.assign(new Error('No embedder is registered.'), { code: 'SERVICE_UNAVAILABLE', status: 503 }); + 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 round that ranks nothing (an empty organization set, a scope with no ids) embeds nothing', async () => { - const store = adapter('vec', { embedQuery: async () => [...VECTOR] }); - const host = { checkScope: (hits: KnowledgeHit[]) => hits, label: (s: KnowledgeSource) => s.name, options: {} }; - const target = (name: string, extra: Partial): SearchTarget => ({ - source: source(name, 'vec'), - binding: { adapterId: 'vec', adapter: store.adapter, question: {} }, - ...extra, + 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 refused: KnowledgeSearchRefusal[] = []; - await searchRound.call( - host as never, - 'what is due', - [target('s1', { organizationIds: [] }), target('s2', { scope: [{ kind: 'record', ids: [] }] })], - () => TOP_K, - undefined, - refused, - ); - expect(store.embedQuery).not.toHaveBeenCalled(); - expect(store.seen.every((o) => !('queryVector' in o))).toBe(true); - // The control: the same round with ids to rank embeds once. - await searchRound.call(host as never, 'what is due', [target('s3', { scope: [{ kind: 'record', ids: ['r0'] }] })], () => TOP_K, undefined, refused); + 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); - expect(refused).toEqual([]); }); }); 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. */ From 87a3dbb8ade14081350bc4c23d849755e6136f1f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:04:54 +0000 Subject: [PATCH 8/9] docs(knowledge): section 3.4 and the changeset describe queryVector as the per-search function Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .changeset/38676-embed-question-once.md | 8 +++---- content/docs/protocol/knowledge.mdx | 31 +++++++++++++++++++------ 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/.changeset/38676-embed-question-once.md b/.changeset/38676-embed-question-once.md index 61510fb18f5..edf90a1ab37 100644 --- a/.changeset/38676-embed-question-once.md +++ b/.changeset/38676-embed-question-once.md @@ -5,13 +5,13 @@ '@objectstack/knowledge-pgvector': patch --- -perf(knowledge): a knowledge search embeds its question once, the refill round included +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: `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`. An adapter handed a `queryVector` ranks with it and does not call its embedder for the query; it checks the vector's width as it checks one its embedder answered. +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. -The knowledge service calls `embedQuery` at most once per adapter per search and hands the vector to every `search` call of that search. 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 now share the one embed too. A `keyword` search, and a round that ranks nothing (an empty organization set, a scope with no ids), embed nothing. An embed that fails refuses each source it was needed for, with the same code and wording as a failed `search`. +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 `embedQuery`. An adapter without it, such as `knowledge-memory`, is searched as before and embeds on every call. +`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 f3d5bc75c1c..a086fecf68c 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -526,7 +526,7 @@ interface IKnowledgeAdapter { }; upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise; search(query: string, opts: AdapterSearchOptions): Promise; - embedQuery?(query: string): Promise; // a question, embedded as search embeds it + embedQuery?(query: string): Promise; // a question, embedded as its search embeds it delete(documentIds: string[], ctx: AdapterContext): Promise; listDocuments?( ctx: AdapterContext, @@ -565,11 +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` does (its -embedder, its query prefix). The service calls it at most once per adapter per -search, never under `keyword`, and hands the vector back as -`AdapterSearchOptions.queryVector` to every call of that search, the refill -included; an adapter without it embeds the question on every call, as before. +`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 @@ -621,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` From e434583729f51a1ed49d6bc4c53f227bd23ea4d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:09:34 +0000 Subject: [PATCH 9/9] test(service-knowledge): read the optional spy as optional Claude-Session: https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h Co-authored-by: Claude --- .../src/__tests__/search-question-vector.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 4f84d23b77d..09bc17b75d9 100644 --- a/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts +++ b/packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts @@ -139,7 +139,7 @@ describe('knowledge search: the question is embedded at most once for each adapt 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.embedQuery?.mock.calls).toEqual([['what is due'], ['what is late']]); expect(store.seen[1]!.queryVector).not.toBe(store.seen[0]!.queryVector); });