diff --git a/.changeset/38692-knowledge-pgvector-retrieval-modes.md b/.changeset/38692-knowledge-pgvector-retrieval-modes.md new file mode 100644 index 00000000000..927460236e5 --- /dev/null +++ b/.changeset/38692-knowledge-pgvector-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +feat(knowledge-pgvector): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says + +Clause-②: yes (widening) +Metadata-protocol: none + +`knowledge-pgvector` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the cosine scan alone and `keyword` the keyword match alone; the other leg is not written into the statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. A mode it does not list is refused (`400 VALIDATION_ERROR`), never run. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 80c896266a8..12d9358c2fe 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -788,7 +788,10 @@ an exact scan. [record scope](#record-scope) and the metadata `filter` (equality per key) are one `WHERE`, run in both legs before either ranks. `queryPrefix` is put before every query before it is embedded, for a model - that embeds questions and passages differently. + that embeds questions and passages differently. It runs all three + retrieval modes, `hybrid` by default: `vector` or `keyword` leaves the + other leg out of the statement and scores a hit `61 / (60 + rank)`, and + `keyword` does not embed the question. The ranking statement runs in a transaction of its own under `SET LOCAL statement_timeout` (`statementTimeoutMs`, else `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000 ms), so the limit holds no diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index f84798730c2..d7fb0af98d1 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -59,8 +59,10 @@ The next call retries; no restart is needed. A database the plugin cannot reach Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. The organization filter, the record scope and the metadata `filter` are one `WHERE`, run in both legs before either ranks. +**Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into the statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. + - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched as a substring over the rows in scope: by `content LIKE '%…%'` when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by `content ILIKE '%…%'` otherwise. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. -- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). +- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write of that width, or the first search of that width with keyword terms (never under `vector`) (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds). - **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it. ## Pool size and time limit 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 4a8be8ed477..c48d725e9cf 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 @@ -30,6 +30,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..e93c41181b2 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8), without + * a database: the capability report, the legs each mode writes into the + * ranking statement, that `keyword` never calls the embedder, and the + * fusion's scores — `hybrid` bit-identical to the fusion before modes + * existed, one leg `61 / (60 + rank)`. The behaviour against a real + * PostgreSQL is the contract suite's (`contract.live-postgres.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../pgvector-adapter.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'modes', label: 'modes', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +/** A store with one active generation whose ranking statement is recorded and answers nothing. */ +function recordingPool(): { pool: PgPoolLike; rankings: string[]; statements: string[] } { + const rankings: string[] = []; + const statements: string[] = []; + const answer = async (text: string): Promise<{ rows: R[] }> => { + statements.push(text); + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] 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: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('GROUP BY chunk_id')) rankings.push(text); + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, rankings, statements }; +} + +async function searched(mode: 'vector' | 'keyword' | 'hybrid' | undefined, query = 'granite quarry') { + return searchedRaw(mode, query); +} + +async function searchedRaw(mode: string | undefined, query = 'granite quarry') { + const store = recordingPool(); + const embedder = new FakeEmbedder(); + const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder }); + const hits = await adapter.search(query, { + source, + topK: 5, + index: { fingerprint: 'fp' }, + ...(mode === undefined ? {} : { retrieval: { mode: mode as 'hybrid' } }), + }); + return { hits, embedder, rankings: store.rankings, statements: store.statements }; +} + +describe('knowledge-pgvector retrieval modes', () => { + it('reports all three modes, hybrid by default', () => { + const adapter = new PgvectorKnowledgeAdapter({ pool: recordingPool().pool, embedder: new FakeEmbedder() }); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid, and no mode, write both legs into the statement', async () => { + for (const mode of ['hybrid', undefined] as const) { + const { rankings, embedder } = await searched(mode); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + expect(embedder.calls).toBe(1); + } + }); + + it('vector writes the vector leg alone', async () => { + const { rankings, embedder } = await searched('vector'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).toContain('vec AS ('); + expect(rankings[0]).not.toContain('kw AS ('); + expect(embedder.calls).toBe(1); + }); + + it('vector writes no keyword condition into any statement, not just none into the fusion', async () => { + // Measured on PG17 + pgvector 0.8.7 over 59,949 clauses: the keyword terms (sixteen + // LIKEs over every row in scope) were most of a hybrid statement's cost. + const hybrid = await searched('hybrid', 'granite quarry w3x 出差'); + expect(hybrid.rankings[0]).toMatch(/\bI?LIKE\b/); + const { statements } = await searched('vector', 'granite quarry w3x 出差'); + expect(statements.length).toBeGreaterThan(0); + for (const text of statements) { + expect(text).not.toMatch(/\bI?LIKE\b/); + expect(text).not.toMatch(/tsquery|@@/); + } + }); + + it('keyword writes the keyword leg alone and never calls the embedder', async () => { + const { rankings, embedder } = await searched('keyword'); + expect(rankings).toHaveLength(1); + expect(rankings[0]).not.toContain('vec AS ('); + expect(rankings[0]).toContain('kw AS ('); + // Equal keyword scores fall to the chunk id: the candidates carry no distance. + expect(rankings[0]).toContain('0 AS distance'); + expect(embedder.calls).toBe(0); + }); + + it('a mode it does not list is refused before anything is embedded or ranked', async () => { + const refused = await searchedRaw('rerank').catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("does not run the retrieval mode 'rerank'"); + }); + + it('keyword with no term to match answers nothing and reads no passage', async () => { + const { hits, rankings, embedder } = await searched('keyword', ' '); + expect(hits).toEqual([]); + expect(rankings).toHaveLength(0); + expect(embedder.calls).toBe(0); + }); +}); + +describe('knowledge-pgvector fusion under the retrieval modes', () => { + type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; + + /** The fusion's score as it stood before retrieval modes existed: the hybrid pin's reference. */ + const before = (row: Row): number => { + const best = 2 / (RRF_K + 1); + const leg = (pos: number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); + return (leg(row.vpos) + leg(row.kpos)) / best; + }; + + it('hybrid is bit-identical to the fusion before modes, for every pair of ranks up to 200', () => { + const ranks: Array = [null, ...Array.from({ length: 200 }, (_, i) => i + 1)]; + const rows: Row[] = []; + for (const vpos of ranks) for (const kpos of ranks) if (vpos !== null || kpos !== null) rows.push({ chunk_id: `${vpos}:${kpos}`, vpos, kpos }); + const fused = fuse(rows, rows.length, 2); + expect(fused).toHaveLength(rows.length); + let differing = 0; + for (const { row, score } of fused) if (!Object.is(score, before(row))) differing += 1; + expect(differing).toBe(0); + }); + + it('one leg scores 61 / (60 + rank): the first is 1, and scores fall with rank', () => { + const rows: Row[] = Array.from({ length: 50 }, (_, i) => ({ chunk_id: `c${String(i + 1).padStart(3, '0')}`, vpos: i + 1, kpos: null })); + const fused = fuse(rows, 50, 1); + expect(fused[0]?.score).toBe(1); + for (const { row, score } of fused) expect(score).toBeCloseTo(61 / (60 + Number(row.vpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 6fe750f9cf7..ef41a406c9d 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -136,6 +136,17 @@ const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** + * The retrieval modes this adapter runs, and its default (ADR-0161, the dated + * note of 2026-11-30 under K8): all three, `hybrid` when a source declares none. + * A report, not configuration; the default does not move with what the + * database offers. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** The default of {@link PgvectorKnowledgeAdapterOptions.statementTimeoutMs}, in milliseconds. */ export const DEFAULT_STATEMENT_TIMEOUT_MS = 10_000; @@ -192,8 +203,17 @@ interface Readiness { * Two legs, merged by reciprocal rank fusion (`k` = {@link RRF_K}) before the * knowledge service re-checks each hit as the caller. Each leg ranks at most * `topK` passages; a passage's score is the sum of `1 / (k + rank)` over the - * legs that rank it, divided by the score of a passage first in both, so it - * lies in `(0, 1]`. Both legs run in one statement, so in one snapshot. + * legs that rank it, divided by the score of a passage first in every leg + * that runs, so it lies in `(0, 1]`. Both legs run in one statement, so in one + * snapshot. + * + * The search's retrieval mode (`AdapterSearchOptions.retrieval`, {@link + * RETRIEVAL}) names the legs that run: `hybrid` (the default) both, `vector` + * the vector leg alone, `keyword` the keyword leg alone — the leg left out is + * not written into the statement. Under one leg a passage's score is + * `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the query: + * the keyword leg's passages of equal score are ranked by chunk id, and a + * query with no terms answers nothing. * * - The vector leg: an exact scan by cosine distance — no approximate index, * so a 3072-wide model works (pgvector's HNSW index stops at 2000 @@ -292,7 +312,7 @@ interface Readiness { */ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { readonly id: string; - readonly capabilities = { chunks: true } as const; + readonly capabilities = { chunks: true, retrieval: RETRIEVAL } as const; private readonly pool?: PgPoolLike; private readonly unavailable?: string; private readonly resolveEmbedder: () => IEmbedder | undefined; @@ -617,16 +637,34 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; - // The query is embedded before a connection is taken. - const [vector] = await embedder.embed([`${this.queryPrefix}${query}`]); - if (!Array.isArray(vector) || vector.length !== generation.dim) { - throw new Error( - `knowledge-pgvector: the embedder answered a ${Array.isArray(vector) ? vector.length : 'missing'}-wide query ` + - `vector, and this source's index holds ${generation.dim}-wide vectors.`, + // The legs the search's mode runs (ADR-0161, the dated note of 2026-11-30 + // under K8); the service hands only a mode this adapter lists, and any + // other is refused, never run on a scale it was not built for. + const mode = opts.retrieval?.mode ?? RETRIEVAL.default; + if (!(RETRIEVAL.modes as readonly string[]).includes(mode)) { + throw Object.assign( + new Error( + `knowledge-pgvector does not run the retrieval mode '${String(mode)}': it runs ` + + `${RETRIEVAL.modes.map((m) => `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, ); } - const vectorLeg = !vector.every((x) => x === 0); - const terms = keywordTerms(query); + // The query is embedded before a connection is taken — never under + // `keyword`, which makes no query vector. + let vector: number[] = []; + if (mode !== 'keyword') { + const [embedded] = await embedder.embed([`${this.queryPrefix}${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 ` + + `vector, and this source's index holds ${generation.dim}-wide vectors.`, + ); + } + vector = embedded; + } + const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); + const terms = mode === 'vector' ? [] : keywordTerms(query); if (!vectorLeg && terms.length === 0) return []; if (terms.length > 0) await this.ensureKeywordIndex(generation.dim); @@ -768,7 +806,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const now = await this.generations(opts.source.name); if (now.active?.generation !== generation.generation) return undefined; } - return fuse(result.rows, topK).map(({ row: r, score }) => ({ + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => ({ chunkId: r.chunk_id, documentId: r.document_id, sourceId: opts.source.name, @@ -1474,16 +1512,19 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } /** - * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank - * in each leg, or null): best first, at most `topK`; a tie goes to the better + * Reciprocal rank fusion of the legs' rows (`vpos`, `kpos`: a row's rank in + * each leg, or null): best first, at most `topK`; a tie goes to the better * vector rank, then to the chunk id. The score is the fused sum divided by - * that of a row first in both legs. + * that of a row first in each of the `legs` the search's mode runs: under + * `hybrid` (two) exactly as before modes existed, under one leg + * `61 / (60 + rank)`. Exported for its pin test, not from the package entry. */ -function fuse( +export function fuse( rows: readonly R[], topK: number, + legs: 1 | 2, ): Array<{ row: R; score: number }> { - const best = 2 / (RRF_K + 1); + const best = legs / (RRF_K + 1); const leg = (pos: string | number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null ? Infinity : Number(row.vpos)); return rows