Skip to content

Commit 58695bb

Browse files
perf(knowledge): embed the search question once per search, the refill round included (#38798)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8WwwNJsfXjR7KkaXqjQxjFx)_ Fixes #38676 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 员工在知识库里搜索、且需要补查第二轮时(例如按单位分组或权限复查后命中不足),问题现在只生成一次向量;以前补查轮会再请求一次嵌入服务(DashScope 约 200 毫秒),搜索结果本身不变,运维和管理员无感。 - 这是“知识检索慢”那张卡的第三个原因(补查轮重复生成问题向量);前两个原因已在之前的改动里修好,这次按你选定的“写进约定,一次提问只转一次”收尾。 - 若出错,碰到的是搜索知识库的员工:最坏情况是某个知识源这次搜索被拒答并写明是哪个来源,不会静默答空;“需要重建索引”这类提示照旧排在前面,不会被嵌入服务的报错盖掉;改动可以直接撤回。 - 无。 ## What changes The question of one knowledge search is embedded at most once for each adapter instance, by the adapter, and the knowledge service carries it back to every `search` call of that search, the refill round included. Built to the ADR-0161 dated note of 2026-12-01 under K8 (ruling record 7296268226 on the card, with its condition: an adapter's own refusal stays ahead of the embed). - **Contract (`@objectstack/spec/contracts`)**: `IKnowledgeAdapter` gains an optional `embedQuery(query)`, which embeds a question exactly as that adapter's `search` does (its embedder, its query prefix); it takes no source. `AdapterSearchOptions` gains an optional `queryVector`, typed as a function of no arguments answering a promise of a read-only number array (`() => Promise`, answering `readonly number[]`). It is the function, not the vector. Both docblocks cite the note and no longer say the knowledge service embeds. Both members additive and optional. - **Service (`knowledge-service-search.ts`, `knowledge-service-top-level.ts`)**: `planSearches` gives every target whose adapter instance has `embedQuery` one slot per instance for the whole search (`SearchQuestion`). The first `searchRound` call to that instance puts one memoised function in it (`memoisedQuestion`): its first call asks the instance's `embedQuery` for the query, and every later call in that search answers the same promise, a rejected one too. That one function is handed on every `search` call to that instance in that search. The service no longer embeds ahead of `search`, no longer judges whether a call embeds (the earlier `keyword` and "round ranks nothing" guards are gone) and reads no vector. A rejection is `embedQuery`'s own error, never wrapped. - **`knowledge-turso`, `knowledge-pgvector`**: each calls the handed function at the exact line where its `search` embeds the query today, in place of that call, after every gate it runs first (nothing to rank, store and embedder present, ready, active generation, the fingerprint and width refusal `KNOWLEDGE_REBUILD_REQUIRED`, `topK`, the mode, `keyword`). Absent: it embeds as before, through its own `embedQuery`. The width check is unchanged, and the answered array is never changed. A failed embed therefore fails inside `search`, where it failed on `main`, with `main`'s code and wording (pgvector's `searchRefusalOf` included). - **Contract suite (`@objectstack/service-knowledge/testing`)**: an optional `implements.embedQuery` declaration, checked against the adapter, and one case for it (below). `knowledge-turso` and `knowledge-pgvector` declare it. - **Docs**: §3.4 of `content/docs/protocol/knowledge.mdx` is rewritten to the note: the function type, where the adapter calls it, what costs no embedding call, and the suite case. - An adapter without `embedQuery` (for example `knowledge-memory`) is handed nothing and searched exactly as before. - `main` merged first (`9e729ceaad`). #38817's behaviour is kept: an embedder error reaches the caller unwrapped, and its test file `unconfigured-embedder-code-38775.test.ts` is unchanged and green (6 of 6). Review findings closed by this round: M1 by the note (merged as `13a0d3fedf`); S1 by the suite case; S2 by the new shape and its pins (a refusal ahead of the embed is answered, with 0 embedder calls); N4 by the new shape (the embed is back inside `search`, so pgvector's socket wording is `main`'s again). Nits of contract review 7290045524: N1 by the new shape (the function is handed on every call, so "every call" is literal); N2 by the new shape (an embedder that answers no vector is one embedding call, memoised, and the width check refuses it, where the earlier head made two); N3 by the new shape, wording kept: on the service's path the handed vector is what the adapter's own embedder answered, so "the embedder answered" stays true; a direct caller answers for its function (the note's second diamond). ## Tests All pins count calls; none is wall-clock. - `packages/services/service-knowledge/src/__tests__/search-question-vector.test.ts` (rewritten, 11 cases, over a fake adapter shaped as the two stores): a refilled search hands both rounds one function and calls `embedQuery` once; two sources of one instance, one function for four calls, one call; the function answers the same promise on every call; two instances, two functions, one call each; two searches, two functions; `keyword` is handed the function and embeds nothing; a source the adapter refuses behind a failing embedder answers its 409 with 0 calls; no `embedQuery`, nothing handed; an uncoded embed failure fails the call that asked (503 platform sentence, text to the operator line); a coded one reaches the adapter as the same error object and keeps code and message; a failed embed is shared (one call, both sources refused). - `packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts` (one top-level describe, 6 cases, real adapter behind `KnowledgeService`): refilled search, one embedder call, prefixed; refilled search over two sources of one instance, one call; `keyword`, 0 calls; **a source that needs a rebuild (embedder model changed) behind an embedder that fails answers `KNOWLEDGE_REBUILD_REQUIRED` 409 with 0 embedder calls**; the control, the same failing embedder behind a healthy source, called once and refused 503; a handed function is ranked with, a function of another width is refused. - `packages/plugins/knowledge-pgvector/src/__tests__/question-once.test.ts` (new, 5 cases, real adapter and `KnowledgeService` over a fake pool): the same four pins as turso (the rebuild-required source is an index held under another fingerprint) and the same control. - `packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts` (3 cases, adapter alone): `embedQuery` embeds the prefixed query; a handed function is asked once and its answer is bound into the ranking statement, embedder not called, with a control; another width is refused. - `packages/services/service-knowledge/src/testing.ts#runKnowledgeAdapterContract`, one case, run only for `implements.embedQuery`: handed a function answering its own `embedQuery`, a search answers what it answers without the member and makes no embedding call of its own; handed one answering a vector of another width (wider, then narrower), the search rejects. The count is a **spy on the instance's `embedQuery`** (review 7297709290 N1), with a control (the search without the member is seen by the spy once). It asserts a rejection, not a code (N2); no code is added. - `packages/plugins/knowledge-pgvector/bench/instrument.test.mjs`: unchanged since `56feee7fa7`, still one embed for a refilled search. <details><summary>Ablation (each through scripts/ablation-replace.mjs; landing and restore proven by blob hash, git diff HEAD empty after each)</summary> - The service calls the function ahead of `search` (the earlier head's order): service 6 failed of 11; turso 2 failed of 6 (keyword, rebuild-required); pgvector 2 failed of 5 (keyword, rebuild-required). - The function not memoised: service 5 failed of 11; turso 2 failed of 6 (refilled, two sources); pgvector 2 failed of 5 (refilled, two sources). - `knowledge-turso` ignores the handed function: the contract case fails on both libSQL cells (2 of 2). Every pin goes red under at least one ablation. The `keyword` pins also hold on `main` and on the earlier head: they guard the order, not the count. </details> <details><summary>Runs at e434583</summary> - `pnpm --filter @objectstack/service-knowledge exec vitest run`: Test Files 31 passed (31), Tests 896 passed (896). - `pnpm --filter @objectstack/knowledge-turso exec vitest run`: Test Files 6 passed (6), Tests 335 passed (335). - `pnpm --filter @objectstack/knowledge-pgvector exec vitest run`: Test Files 10 passed, 10 skipped (20); Tests 75 passed, 117 skipped (192). The live-PostgreSQL files skip here (no pgvector server in this container), so the contract case on pgvector is NOT MEASURED locally: CI's live cell runs it. - `pnpm --filter @objectstack/knowledge-memory exec vitest run src/__tests__/contract.test.ts`: 54 passed (the suite change, an adapter without the member). - typecheck of spec, service-knowledge, knowledge-turso, knowledge-pgvector: exit 0, test layers included. - `pnpm --filter @objectstack/spec build` then `check:generated`: all 14 generated artifacts up to date. - eslint over the changed source and test files: exit 0. - Derived gates (`dispatch-gates.mjs --commands`, 117 families): 116 exit 0, 1 NOT MEASURED (`check:dual-build-cjs-loads`, exit 3: needs every package built); `--ran`: 117 derived, 116 run, 1 NOT-MEASURED, 0 UNRUN. </details> ## Acceptance notes - The earlier head's note that a source with no built index cost one embed per search is gone: the adapter now asks only past its own gates. - One embed serves every source of one adapter instance, so a failed embed refuses each source of that instance that asked, with the same error, where on `main` each made its own attempt (the note says so). - The contract case counts by a spy on `embedQuery`, so it reads an adapter whose `search` embeds the query through that method, as both stores do; one that embeds by another path fails the case's control, and the suite's docblock says so. - `knowledge-memory` has no `embedQuery` and still embeds on every call; adding it there is outside this card. ## Verification Read first, by risk: 1. `packages/services/service-knowledge/src/knowledge-service-search.ts`: `memoisedQuestion` and the `queryVector` lines at the top of the loop in `searchRound`. Risk: a call of the function there, ahead of `search`, would undo the condition. 2. `packages/plugins/knowledge-turso/src/turso-adapter.ts` and `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts`: the one changed line where `search` embeds. Risk: it must stay after every refusal above it. 3. `packages/spec/src/contracts/knowledge-adapter.ts`: the two members and their docblocks (the contract text). Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec vitest run src/__tests__/acceptance.test.ts -t 'embedded at most once'` prints `Tests 6 passed`; the fourth case asserts a 409 with 0 embedder calls behind a failing embedder. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbXfgA45f3y5YpDPT5h <!-- signed: repo:objectstack#2 · os-warren · session_01JQwxbXfgA45f3y5YpDPT5h --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 13a0d3f commit 58695bb

15 files changed

Lines changed: 791 additions & 14 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/service-knowledge': patch
4+
'@objectstack/knowledge-turso': patch
5+
'@objectstack/knowledge-pgvector': patch
6+
---
7+
8+
perf(knowledge): a knowledge search embeds its question at most once for each adapter, the refill round included
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
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<readonly number[]>`, 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.
14+
15+
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.
16+
17+
`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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,7 @@ interface IKnowledgeAdapter {
526526
};
527527
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
528528
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
529+
embedQuery?(query: string): Promise<number[]>; // a question, embedded as its search embeds it
529530
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
530531
listDocuments?(
531532
ctx: AdapterContext,
@@ -564,6 +565,25 @@ search to chosen records the same way — see [Record scope](#record-scope).
564565
report, not configuration. `AdapterSearchOptions.retrieval` carries the mode
565566
a search runs, a per-request parameter like `topK`, and only ever a mode the
566567
adapter lists.
568+
`embedQuery` embeds a question exactly as the adapter's `search` embeds it,
569+
through its embedder and with its query prefix; it takes no source, so an
570+
adapter whose query embedding differs from source to source does not
571+
implement it. Its presence is the signal (ADR-0161, the dated note of
572+
2026-12-01 under K8): the service then hands every `search` call it makes to
573+
that adapter instance in one search the same function,
574+
`AdapterSearchOptions.queryVector: () => Promise<readonly number[]>`. Its first
575+
call asks the instance's `embedQuery` for the query; every later call in that
576+
search (another source of the instance, the refill round, the adapter's own
577+
retry) answers the same promise, a rejected one too. The adapter calls it
578+
where its `search` embeds the query, after everything it decides first, so a
579+
search under `keyword`, a search that ranks nothing and a source it refuses
580+
(`KNOWLEDGE_REBUILD_REQUIRED` among them) cost no embedding call, and that
581+
refusal is the one answered. It checks the answer's width as it checks one its
582+
embedder answered, and never changes the array. The service judges nothing
583+
about a call and reads no vector: the question is embedded at most once for
584+
each adapter instance in a search, by the adapter. An adapter without
585+
`embedQuery` is handed nothing and embeds the question on every call, as
586+
before.
567587
`listDocuments` lists the documents the
568588
adapter holds for a source, a page of at most `limit` entries at a time, each
569589
with the `docHash` it was stored with; `nextCursor` is absent once the
@@ -615,7 +635,10 @@ the embedder's budget is removed and reported; and the index fingerprint of
615635
§3.6 — that every call carries one, that a write or a search under another
616636
is refused by code, a complete reindex as one build, and, for an adapter that
617637
keeps generations, the switch at the end of a build; and, for an adapter that declares the optional
618-
`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite
638+
`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words; and,
639+
for an adapter that declares `embedQuery`, that a search handed a function answering its own
640+
`embedQuery` answers as without it and makes no embedding call of its own, and that one answering
641+
a vector of another width is rejected. `implements` declares the optional members, and the suite
619642
checks the declaration against the adapter. `./testing` is a test-only,
620643
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
621644
`knowledge-memory` runs it as the reference implementation; `knowledge-pgvector`

‎packages/plugins/knowledge-pgvector/bench/instrument.test.mjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ function setup({ failEmbed = false } = {}) {
135135
}
136136

137137
describe('bench instrument — segment seams over the real adapter and service', () => {
138-
it('a caller the re-check narrows: two rounds, each one embed, one ranking statement and one re-check', async () => {
138+
it('a caller the re-check narrows: two rounds, one embed serving both, one ranking statement and one re-check', async () => {
139139
const { search } = setup();
140140
const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER);
141141
expect(outcome.error).toBeUndefined();
@@ -145,7 +145,8 @@ describe('bench instrument — segment seams over the real adapter and service',
145145
expect(outcome.record.adapterCalls.map((c) => c.asked)).toEqual([TOP_K * 5, TOP_K * 20]);
146146
expect(s.rounds).toBe(2);
147147
expect(s.refilled).toBe(true);
148-
expect(s.calls.embed).toBe(2);
148+
// The question is embedded once for the search; the refill reuses its vector.
149+
expect(s.calls.embed).toBe(1);
149150
expect(s.calls.ranking).toBe(2);
150151
expect(s.calls.permission_recheck).toBe(2);
151152
// The caller's readable ids, read once before ranking (unscoped search).

‎packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
3131
dropSource: true,
3232
keywordLeg: true,
3333
retrieval: true,
34+
embedQuery: true,
3435
},
3536
});
3637
});
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The question of a search is embedded at most once for this adapter instance
5+
* (ADR-0161, the dated note of 2026-12-01 under K8), through a real
6+
* `KnowledgeService` and without a database: a fake pool answers the store's
7+
* statements. The service hands every `search` call one function as
8+
* `queryVector`; the adapter calls it where it embeds the query, after its own
9+
* refusals, so a source it refuses costs no embedding call and answers its own
10+
* refusal. Call counts only, never a duration.
11+
*/
12+
13+
import { describe, expect, it } from 'vitest';
14+
import type { AdapterSearchOptions, IDataEngine } from '@objectstack/spec/contracts';
15+
import type { KnowledgeSource } from '@objectstack/spec/ai';
16+
import type { ExecutionContext } from '@objectstack/spec/kernel';
17+
import { KnowledgeService } from '@objectstack/service-knowledge';
18+
import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js';
19+
import { FakeEmbedder } from './live-pg.testkit.js';
20+
21+
const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as unknown as ExecutionContext;
22+
const DIMS = 384;
23+
24+
const sourceOf = (name: string, extra: Record<string, unknown> = {}): KnowledgeSource =>
25+
({
26+
name,
27+
label: name,
28+
adapter: 'pgvector',
29+
source: { kind: 'object', object: 'clause', content: ['body'], ...extra },
30+
}) as KnowledgeSource;
31+
32+
/**
33+
* A store with one active generation per source, held under `fingerprint`
34+
* (absent: the one the service searches with), whose ranking statement answers
35+
* 60 passages of one record, so a record-level search refills.
36+
*/
37+
function fakePool(fingerprint?: string): { pool: PgPoolLike; searched: { fingerprint?: string } } {
38+
const searched: { fingerprint?: string } = {};
39+
const answer = async <R>(text: string): Promise<{ rows: R[] }> => {
40+
if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.7' }] as R[] };
41+
if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] };
42+
if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) {
43+
return { rows: [{ generation: 1, fingerprint: fingerprint ?? searched.fingerprint ?? null, recipe_hash: null, dim: DIMS, state: 'active' }] as R[] };
44+
}
45+
if (text.includes('GROUP BY chunk_id')) {
46+
return {
47+
rows: Array.from({ length: 60 }, (_, i) => ({
48+
chunk_id: `ch_${i}`,
49+
document_id: 'doc_0',
50+
source_record_id: 'rec_0',
51+
content: `passage ${i}`,
52+
title: null,
53+
metadata: {},
54+
doc_hash: null,
55+
heading_path: null,
56+
vpos: i + 1,
57+
kpos: null,
58+
})) as R[],
59+
};
60+
}
61+
return { rows: [] as R[] };
62+
};
63+
const client = (): PgClientLike => ({ query: answer, release: () => undefined });
64+
return { pool: { query: answer, connect: async () => client() }, searched };
65+
}
66+
67+
/** The service's reads: every record it asks for by id exists. */
68+
const engine = {
69+
find: async (_object: string, query: { where?: { id?: { $in?: string[] } } }) =>
70+
(query?.where?.id?.$in ?? []).map((id) => ({ id })),
71+
findOne: async () => null,
72+
} as unknown as IDataEngine;
73+
74+
function setup(opts: { fingerprint?: string; sources?: KnowledgeSource[] } = {}) {
75+
const store = fakePool(opts.fingerprint);
76+
const embedder = new FakeEmbedder(DIMS);
77+
const adapter = new PgvectorKnowledgeAdapter({ id: 'pgvector', pool: store.pool, embedder });
78+
const searches: AdapterSearchOptions[] = [];
79+
const search = adapter.search.bind(adapter);
80+
adapter.search = async (query, searchOpts) => {
81+
searches.push(searchOpts);
82+
store.searched.fingerprint = searchOpts.index?.fingerprint;
83+
return search(query, searchOpts);
84+
};
85+
const svc = new KnowledgeService({ dataEngine: engine });
86+
svc.registerAdapter('pgvector', adapter);
87+
for (const s of opts.sources ?? [sourceOf('clauses')]) svc.registerSource(s);
88+
return { svc, embedder, searches };
89+
}
90+
91+
/** From now on every embedding call of `embedder` fails, and is still counted. */
92+
function failing(embedder: FakeEmbedder): void {
93+
embedder.embed = async () => {
94+
embedder.calls += 1;
95+
throw new Error('embedder down at http://10.0.0.7:11434');
96+
};
97+
}
98+
99+
const refilled = { topK: 5, granularity: 'record' as const, executionContext: SYSTEM };
100+
101+
describe('knowledge-pgvector through KnowledgeService: the question is embedded at most once a search', () => {
102+
it('a refilled search calls the adapter twice, both handed one function, and the embedder once', async () => {
103+
const { svc, embedder, searches } = setup();
104+
await svc.search('leave policy', refilled);
105+
expect(searches.map((o) => o.topK)).toEqual([25, 100]);
106+
expect(typeof searches[0]!.queryVector).toBe('function');
107+
expect(searches[1]!.queryVector).toBe(searches[0]!.queryVector);
108+
expect(embedder.calls).toBe(1);
109+
});
110+
111+
it('a refilled search over two sources of one instance: four adapter calls, one embedding call', async () => {
112+
const { svc, embedder, searches } = setup({ sources: [sourceOf('one'), sourceOf('two')] });
113+
await svc.search('leave policy', refilled);
114+
expect(searches.map((o) => o.source.name).sort()).toEqual(['one', 'one', 'two', 'two']);
115+
expect(embedder.calls).toBe(1);
116+
});
117+
118+
it('a keyword search embeds nothing, on either round', async () => {
119+
const { svc, embedder, searches } = setup({ sources: [sourceOf('clauses', { retrieval: { mode: 'keyword' } })] });
120+
await svc.search('leave policy', refilled);
121+
expect(searches).toHaveLength(2);
122+
expect(embedder.calls).toBe(0);
123+
});
124+
125+
it('a source that needs a rebuild, behind an embedder that fails, answers KNOWLEDGE_REBUILD_REQUIRED 409 with 0 embedder calls', async () => {
126+
// The index holds another fingerprint than the one the service searches with.
127+
const { svc, embedder, searches } = setup({ fingerprint: 'fp-built-under-another-model' });
128+
failing(embedder);
129+
const refused = await svc.searchWithRefusals('leave policy', { topK: 5, executionContext: SYSTEM }).catch((e: unknown) => e);
130+
expect(refused).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 });
131+
expect(searches).toHaveLength(1);
132+
expect(embedder.calls).toBe(0);
133+
});
134+
135+
it('the control: the same failing embedder behind a healthy source is called once and refuses it 503', async () => {
136+
const { svc, embedder } = setup();
137+
failing(embedder);
138+
const refused = await svc.searchWithRefusals('leave policy', { topK: 5, executionContext: SYSTEM }).catch((e: unknown) => e);
139+
expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
140+
expect(embedder.calls).toBe(1);
141+
});
142+
});

‎packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,56 @@ describe('knowledge-pgvector retrieval modes', () => {
114114
});
115115
});
116116

117+
describe('knowledge-pgvector: a question vector the service hands', () => {
118+
/** {@link recordingPool}, keeping the parameters of each ranking statement. */
119+
function paramPool(): { pool: PgPoolLike; rankingParams: unknown[][] } {
120+
const rankingParams: unknown[][] = [];
121+
const { pool } = recordingPool();
122+
const answer = async <R>(text: string, params?: unknown[]): Promise<{ rows: R[] }> => {
123+
if (text.includes('GROUP BY chunk_id')) rankingParams.push(params ?? []);
124+
return pool.query<R>(text, params);
125+
};
126+
const client = (): PgClientLike => ({ query: answer, release: () => undefined });
127+
return { pool: { query: answer, connect: async () => client() }, rankingParams };
128+
}
129+
130+
it('embedQuery embeds the query as search does: the query prefix, then the query', async () => {
131+
const embedder = new FakeEmbedder();
132+
const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder, queryPrefix: 'query: ' });
133+
const vector = await adapter.embedQuery('granite quarry');
134+
expect(embedder.texts).toEqual(['query: granite quarry']);
135+
expect(vector).toHaveLength(embedder.dimensions);
136+
});
137+
138+
it('a handed queryVector is asked once, its answer is the one bound into the ranking, and the embedder is not called', async () => {
139+
const store = paramPool();
140+
const embedder = new FakeEmbedder();
141+
const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder });
142+
const handed = await new FakeEmbedder().embed(['basalt column']).then(([v]) => v!);
143+
let asked = 0;
144+
const queryVector = async (): Promise<readonly number[]> => {
145+
asked += 1;
146+
return handed;
147+
};
148+
await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector });
149+
expect(asked).toBe(1);
150+
expect(embedder.calls).toBe(0);
151+
expect(store.rankingParams).toHaveLength(1);
152+
expect(store.rankingParams[0]).toContain(`[${handed.join(',')}]`);
153+
// The control: without one, the query is embedded once.
154+
await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' } });
155+
expect(embedder.calls).toBe(1);
156+
});
157+
158+
it('a handed queryVector of another width is refused, as a vector the embedder answered is', async () => {
159+
const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder: new FakeEmbedder() });
160+
const refused = await adapter
161+
.search('granite', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector: async () => [1, 0] })
162+
.catch((e: unknown) => e);
163+
expect(String((refused as Error).message)).toContain('2-wide query vector');
164+
});
165+
});
166+
117167
describe('knowledge-pgvector fusion under the retrieval modes', () => {
118168
type Row = { chunk_id: string; vpos: number | null; kpos: number | null };
119169

‎packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
591591
}
592592
}
593593

594+
/**
595+
* The question as {@link search} embeds it: the query prefix, then the
596+
* query, through the embedder (ADR-0161, the dated note of 2026-12-01 under
597+
* K8). Neither changes from source to source, so one vector serves every
598+
* source of this instance.
599+
*/
600+
async embedQuery(query: string): Promise<number[]> {
601+
const [embedded] = await this.requireEmbedder().embed([`${this.queryPrefix}${query}`]);
602+
return embedded;
603+
}
604+
594605
/** {@link search}'s attempts: again while a completed build switches the source's index under it. */
595606
private async searchAttempts(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
596607
for (let attempt = 1; ; attempt++) {
@@ -650,11 +661,14 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
650661
{ code: 'VALIDATION_ERROR', status: 400 },
651662
);
652663
}
653-
// The query is embedded before a connection is taken — never under
654-
// `keyword`, which makes no query vector.
655-
let vector: number[] = [];
664+
// The query is embedded before a connection is taken, after every refusal
665+
// above — never under `keyword`, which makes no query vector. A search the
666+
// knowledge service hands `queryVector` asks it here instead, so a refusal
667+
// above costs no embedding call (ADR-0161, the dated note of 2026-12-01
668+
// under K8); its answer serves the search's other calls and is never changed.
669+
let vector: readonly number[] = [];
656670
if (mode !== 'keyword') {
657-
const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]);
671+
const embedded = opts.queryVector === undefined ? await this.embedQuery(query) : await opts.queryVector();
658672
if (!Array.isArray(embedded) || embedded.length !== generation.dim) {
659673
throw new Error(
660674
`knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` +

0 commit comments

Comments
 (0)