diff --git a/.changeset/38692-knowledge-turso-retrieval-modes.md b/.changeset/38692-knowledge-turso-retrieval-modes.md new file mode 100644 index 00000000000..65e0c8f627e --- /dev/null +++ b/.changeset/38692-knowledge-turso-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +feat(knowledge-turso): 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-turso` 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 vector leg alone (the exact scan, or the approximate index as before) and `keyword` the keyword match alone; the other leg is not written into any statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question or read the approximate index, 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..edf85e822dc 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -865,7 +865,10 @@ large source of one organization, through an approximate index. the [record scope](#record-scope) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. Without the approximate index the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about - 5 ms; 10,000 take 82 MB and about 50 ms. + 5 ms; 10,000 take 82 MB and about 50 ms. It runs all three retrieval + modes, `hybrid` by default: `vector` or `keyword` leaves the other leg out + of every statement and scores a hit `61 / (60 + rank)`, and `keyword` does + not embed the question or read the approximate index. - **Approximate index.** A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, makes its approximate index: each passage's vector quantized diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 0bf9eb8ed3d..b4ad4260c1b 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -51,8 +51,10 @@ On a file the store sets WAL and a busy timeout: without them a second process w Two legs, 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. +**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 any statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question or read the approximate index, 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` and `v1.2` are one term each (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 term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. 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. There is no dictionary segmentation: the pieces find a code, a name or a phrase as written, and the vector leg answers the question's meaning. -- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. +- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search that has keyword terms (never under `vector`), built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. And the keyword leg is computed once a search: when the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered. diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 903aba6ac35..0862fcbce35 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -28,6 +28,7 @@ for (const kind of ['memory', 'file'] as const) { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..ceddeea0b42 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,180 @@ +// 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) on + * libSQL: the capability report, the legs each mode writes into the ranking + * statement, that `keyword` never calls the embedder nor reads the + * approximate index, and the fusion's scores — `hybrid` bit-identical to the + * fusion before modes existed, one leg `61 / (60 + rank)`. What each mode + * answers is also the contract suite's (`contract.test.ts`). + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { Client } from '@libsql/client'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../turso-adapter.js'; +import { FakeEmbedder, storeOf } from './turso.testkit.js'; + +const source = (id: string): KnowledgeSource => + ({ name: id, label: id, adapter: 'under_test', source: { kind: 'object', object: 'article', content: ['body'] } }) as KnowledgeSource; +const FP = { fingerprint: 'fp-test:modes', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource): AdapterContext => ({ source: s, reason: 'manual', index: FP }); +const doc = (s: KnowledgeSource, n: string, content: string): KnowledgeDocument => { + const id = `${s.name}:${n}`; + return { id, sourceId: s.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] }; +}; + +/** A client whose every executed statement's SQL is recorded. */ +function recording(client: Client): { client: Client; sql: string[] } { + const sql: string[] = []; + const watched = new Proxy(client, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key === 'execute') { + return (statement: unknown, ...rest: unknown[]) => { + sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + return fn(statement, ...rest); + }; + } + return fn; + }, + }); + return { client: watched, sql }; +} + +/** The ranking statements recorded since `from`: those that merge the legs. */ +const rankings = (sql: string[], from: number) => sql.slice(from).filter((s) => s.includes('GROUP BY chunk_id')); + +describe('knowledge-turso retrieval modes', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + async function seeded(opts: { vectorIndexThreshold?: number } = {}) { + const s = source(`modes_${Math.random().toString(36).slice(2, 8)}`); + const watched = recording(store.client()); + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder, ...opts }); + const docs = Array.from({ length: 50 }, (_, i) => doc(s, String(i).padStart(3, '0'), `granite quarry stone ${i} w${i % 7}x`)); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return { s, adapter, embedder, sql: watched.sql }; + } + + it('reports all three modes, hybrid by default', () => { + const adapter = store.adapter(); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid writes both legs, and answers exactly what no mode answers', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hybrid = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'hybrid' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + // The control for the vector case below: hybrid does write the keyword terms. + expect(ranked[0]).toMatch(/\bMATCH\b/); + expect(embedder.calls).toBe(calls + 1); + expect(hybrid).toEqual(await adapter.search('granite w3x', { source: s, topK: 5, index: FP })); + }); + + it('vector writes the vector leg alone; the first hit scores 1', async () => { + const { s, adapter, sql } = await seeded(); + const from = sql.length; + const hits = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).not.toContain('kw AS'); + // No keyword condition is written at all, not just left out of the fusion: on a + // large table the keyword terms (LIKE, or the FTS5 match) are most of a search's cost. + const written = sql.slice(from); + expect(written.length).toBeGreaterThan(0); + for (const q of written) { + expect(q).not.toMatch(/\bLIKE\b/i); + expect(q).not.toMatch(/\bMATCH\b/); + expect(q).not.toContain('-fts'); + } + expect(hits[0]?.score).toBe(1); + }); + + it('keyword writes the keyword leg alone, never calls the embedder, and ranks equal scores by chunk id', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hits = await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).not.toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + expect(embedder.calls).toBe(calls); + // Every passage holds the one term equally: chunk id order, first scoring 1. + expect(hits.map((h) => h.chunkId)).toEqual([...hits.map((h) => h.chunkId)].sort()); + expect(hits[0]?.score).toBe(1); + // No term to match: nothing, and no passage read. + const at = sql.length; + expect(await adapter.search(' ', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP })).toEqual([]); + expect(rankings(sql, at)).toHaveLength(0); + }); + + it('a mode it does not list is refused before anything is read or embedded', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const refused = await adapter + .search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'rerank' as never }, index: FP }) + .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'"); + expect(embedder.calls).toBe(calls); + expect(rankings(sql, from)).toEqual([]); + }); + + it('keyword never reads the approximate index of a generation that has one', async () => { + const { s, adapter, sql } = await seeded({ vectorIndexThreshold: 40 }); + const from = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + expect(sql.slice(from).some((q) => q.includes('vector1bit('))).toBe(false); + const at = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + expect(sql.slice(at).some((q) => q.includes('vector1bit('))).toBe(true); + }); +}); + +describe('knowledge-turso 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: unknown) => (pos === null || pos === undefined ? 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: null, kpos: i + 1 })); + 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.kpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 93aa4111847..248f40bf932 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -197,6 +197,17 @@ const LOCK_CONFLICT = 'LOCK_CONFLICT'; /** 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 whether a + * generation has an approximate index. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** A generation row: one index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -310,8 +321,16 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, ); } - const vectorLeg = !vector.every((x) => x === 0); - const terms = keywordTerms(query); + // The query is embedded before the database is read — 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 !== active.dim) { + throw new Error( + `knowledge-turso: the embedder answered a ${Array.isArray(embedded) ? embedded.length : 'missing'}-wide query ` + + `vector, and this source's index holds ${active.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 []; // One WHERE for both legs: the organization filter, the record scope and // the metadata filter, each bound as values. ?1 is the query vector. - const args: unknown[] = [vectorLiteral(vector)]; + // Under `keyword` there is no query vector and no statement reads ?1; it is bound as NULL. + const args: unknown[] = [mode === 'keyword' ? null : vectorLiteral(vector)]; const where: string[] = []; // Whether the record index can serve the exact scan: a scope of record terms alone. let recordScope = false; @@ -925,7 +963,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } return this.searchAttempt(query, opts, attempt + 1); } - return fuse(result.rows, topK).map(({ row: r, score }) => { + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => { const headingPath = parseJson(r.heading_path); return { chunkId: String(r.chunk_id), @@ -1684,16 +1722,19 @@ async function oneBitVectorsWork(db: Pick): Promise } /** - * 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: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null || row.vpos === undefined ? Infinity : Number(row.vpos)); return rows