Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/38676-embed-question-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/spec': patch
'@objectstack/service-knowledge': patch
'@objectstack/knowledge-turso': patch
'@objectstack/knowledge-pgvector': patch
---

perf(knowledge): a knowledge search embeds its question at most once for each adapter, the refill round included

Clause-②: yes (widening)
Metadata-protocol: none

Widened (ADR-0161, the dated note of 2026-12-01 under K8): `IKnowledgeAdapter` (`@objectstack/spec/contracts`) gains an optional `embedQuery(query)`, which embeds a question exactly as the adapter's `search` does (its embedder and its query prefix), and `AdapterSearchOptions` gains an optional `queryVector: () => Promise<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.

For each search, the knowledge service hands every `search` call to an adapter instance that has `embedQuery` one function: its first call asks that instance's `embedQuery`, and every later call in the search answers the same promise, a failed one too. A search whose first round leaves fewer than `topK` records or groups after the permission re-check (a narrowed caller, `granularity: 'record'` or `groupBy`) asks the adapter again with a larger `topK`; that second round used to embed the question a second time, about one embedding request per refilled search. Several sources on one adapter instance now share the one embedding call too. Because the adapter asks only where it embeds, a `keyword` search, a search that ranks nothing and a source the adapter refuses make no embedding call, and the adapter's own refusal (`KNOWLEDGE_REBUILD_REQUIRED` 409 for an index that needs a rebuild) is the one answered even when the embedder would fail. A failed embedding call fails each `search` call that asked for the vector, with the code and wording it had before.

`knowledge-turso` and `knowledge-pgvector` implement both members. An adapter without `embedQuery`, such as `knowledge-memory`, is handed nothing and is searched as before, embedding on every call. The adapter contract suite (`@objectstack/service-knowledge/testing`) gains an optional `implements.embedQuery` declaration and one case for it.
25 changes: 24 additions & 1 deletion content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,7 @@ interface IKnowledgeAdapter {
};
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
embedQuery?(query: string): Promise<number[]>; // a question, embedded as its search embeds it
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
listDocuments?(
ctx: AdapterContext,
Expand Down Expand Up @@ -564,6 +565,25 @@ search to chosen records the same way — see [Record scope](#record-scope).
report, not configuration. `AdapterSearchOptions.retrieval` carries the mode
a search runs, a per-request parameter like `topK`, and only ever a mode the
adapter lists.
`embedQuery` embeds a question exactly as the adapter's `search` embeds it,
through its embedder and with its query prefix; it takes no source, so an
adapter whose query embedding differs from source to source does not
implement it. Its presence is the signal (ADR-0161, the dated note of
2026-12-01 under K8): the service then hands every `search` call it makes to
that adapter instance in one search the same function,
`AdapterSearchOptions.queryVector: () => Promise<readonly number[]>`. 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
Expand Down Expand Up @@ -615,7 +635,10 @@ the embedder's budget is removed and reported; and the index fingerprint of
§3.6 — that every call carries one, that a write or a search under another
is refused by code, a complete reindex as one build, and, for an adapter that
keeps generations, the switch at the end of a build; and, for an adapter that declares the optional
`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite
`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words; and,
for an adapter that declares `embedQuery`, that a search handed a function answering its own
`embedQuery` answers as without it and makes no embedding call of its own, and that one answering
a vector of another width is rejected. `implements` declares the optional members, and the suite
checks the declaration against the adapter. `./testing` is a test-only,
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
`knowledge-memory` runs it as the reference implementation; `knowledge-pgvector`
Expand Down
5 changes: 3 additions & 2 deletions packages/plugins/knowledge-pgvector/bench/instrument.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
dropSource: true,
keywordLeg: true,
retrieval: true,
embedQuery: true,
},
});
});
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}): 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 <R>(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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,56 @@ describe('knowledge-pgvector retrieval modes', () => {
});
});

describe('knowledge-pgvector: a question vector the service hands', () => {
/** {@link recordingPool}, keeping the parameters of each ranking statement. */
function paramPool(): { pool: PgPoolLike; rankingParams: unknown[][] } {
const rankingParams: unknown[][] = [];
const { pool } = recordingPool();
const answer = async <R>(text: string, params?: unknown[]): Promise<{ rows: R[] }> => {
if (text.includes('GROUP BY chunk_id')) rankingParams.push(params ?? []);
return pool.query<R>(text, params);
};
const client = (): PgClientLike => ({ query: answer, release: () => undefined });
return { pool: { query: answer, connect: async () => client() }, rankingParams };
}

it('embedQuery embeds the query as search does: the query prefix, then the query', async () => {
const embedder = new FakeEmbedder();
const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder, queryPrefix: 'query: ' });
const vector = await adapter.embedQuery('granite quarry');
expect(embedder.texts).toEqual(['query: granite quarry']);
expect(vector).toHaveLength(embedder.dimensions);
});

it('a handed queryVector is asked once, its answer is the one bound into the ranking, and the embedder is not called', async () => {
const store = paramPool();
const embedder = new FakeEmbedder();
const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder });
const handed = await new FakeEmbedder().embed(['basalt column']).then(([v]) => v!);
let asked = 0;
const queryVector = async (): Promise<readonly number[]> => {
asked += 1;
return handed;
};
await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector });
expect(asked).toBe(1);
expect(embedder.calls).toBe(0);
expect(store.rankingParams).toHaveLength(1);
expect(store.rankingParams[0]).toContain(`[${handed.join(',')}]`);
// The control: without one, the query is embedded once.
await adapter.search('granite quarry', { source, topK: 5, index: { fingerprint: 'fp' } });
expect(embedder.calls).toBe(1);
});

it('a handed queryVector of another width is refused, as a vector the embedder answered is', async () => {
const adapter = new PgvectorKnowledgeAdapter({ pool: paramPool().pool, embedder: new FakeEmbedder() });
const refused = await adapter
.search('granite', { source, topK: 5, index: { fingerprint: 'fp' }, queryVector: async () => [1, 0] })
.catch((e: unknown) => e);
expect(String((refused as Error).message)).toContain('2-wide query vector');
});
});

describe('knowledge-pgvector fusion under the retrieval modes', () => {
type Row = { chunk_id: string; vpos: number | null; kpos: number | null };

Expand Down
22 changes: 18 additions & 4 deletions packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
}
}

/**
* The question as {@link search} embeds it: the query prefix, then the
* query, through the embedder (ADR-0161, the dated note of 2026-12-01 under
* K8). Neither changes from source to source, so one vector serves every
* source of this instance.
*/
async embedQuery(query: string): Promise<number[]> {
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<KnowledgeHit[]> {
for (let attempt = 1; ; attempt++) {
Expand Down Expand Up @@ -650,11 +661,14 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
{ code: 'VALIDATION_ERROR', status: 400 },
);
}
// The query is embedded before a connection is taken — never under
// `keyword`, which makes no query vector.
let vector: number[] = [];
// The query is embedded before a connection is taken, after every refusal
// above — never under `keyword`, which makes no query vector. A search the
// knowledge service hands `queryVector` asks it here instead, so a refusal
// above costs no embedding call (ADR-0161, the dated note of 2026-12-01
// under K8); its answer serves the search's other calls and is never changed.
let vector: readonly number[] = [];
if (mode !== 'keyword') {
const [embedded] = await embedder.embed([`${this.queryPrefix}${query}`]);
const embedded = opts.queryVector === undefined ? await this.embedQuery(query) : await opts.queryVector();
if (!Array.isArray(embedded) || embedded.length !== generation.dim) {
throw new Error(
`knowledge-pgvector: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` +
Expand Down
Loading
Loading