Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
3034d99
fix(knowledge-turso): a scoped search reads its passage table once a …
claude Nov 30, 2026
d3c750a
chore(changeset): say that writes past the request bound answer TIMEO…
claude Nov 30, 2026
4059689
perf(knowledge-turso): compute the keyword leg once a search; send a …
claude Nov 30, 2026
1ff5857
feat(spec): source.retrieval.mode, AdapterCapabilities.retrieval and …
claude Nov 30, 2026
8dc9af7
chore(spec): regenerate the generated artifacts for source.retrieval
claude Nov 30, 2026
e582d5e
chore(changeset): source.retrieval.mode and the adapter's retrieval r…
claude Nov 30, 2026
9e57639
test(service-knowledge): the vector-mode contract case reads the vect…
claude Nov 30, 2026
26f78ac
Merge remote-tracking branch 'origin/claude/project-thread-vj79kz' in…
claude Nov 30, 2026
adc756c
feat(knowledge-turso): run one leg or both by the search's retrieval …
claude Nov 30, 2026
0415254
docs(knowledge-turso): the retrieval modes in the README, the protoco…
claude Nov 30, 2026
e805371
test(spec): pin KnowledgeRetrievalModeSchema as isomorphic (ADR-0122)
claude Nov 30, 2026
ae20d2c
Merge branch 'claude/project-thread-vj79kz' of https://github.com/obj…
claude Nov 30, 2026
14b8b7a
docs(knowledge): the adapter contract carries the retrieval mode; nam…
claude Nov 30, 2026
3d9bbb8
Merge branch 'claude/project-thread-vj79kz' of https://github.com/obj…
claude Nov 30, 2026
dd4cf3e
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 30, 2026
08788c6
fix(platform-objects): name the retrieval-mode choices in every local…
claude Nov 30, 2026
dba27db
Merge remote-tracking branch 'origin/claude/project-thread-vj79kz' in…
claude Nov 30, 2026
7436d4f
test(platform-objects): count the retrieval-mode rows in the translat…
claude Nov 30, 2026
5250d16
Merge remote-tracking branch 'origin/claude/project-thread-vj79kz' in…
claude Nov 30, 2026
53a6f99
test(knowledge-turso): a vector-mode search writes no keyword conditi…
claude Nov 30, 2026
43497e0
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 30, 2026
b15ac8d
docs(spec): cite the ADR-0161 note of 2026-11-30 under K8 by its plac…
claude Nov 30, 2026
a76dc2e
chore(changeset): the platform-objects translations of the retrieval-…
claude Nov 30, 2026
75d7437
fix(spec): the retrieval key warns until the service reads it; the co…
claude Nov 30, 2026
fdba258
Merge remote-tracking branch 'origin/main' into claude/project-thread…
claude Nov 30, 2026
4c3bf79
Merge branch 'claude/project-thread-vj79kz' of https://github.com/obj…
claude Nov 30, 2026
a99c90a
Cite the retrieval-mode note by its date in the turso test
claude Nov 30, 2026
9e356c8
Merge branch 'main' of https://github.com/objectstack-ai/objectstack …
claude Nov 30, 2026
2496e51
Refuse a retrieval mode the store does not list; declare the widening
claude Nov 30, 2026
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
10 changes: 10 additions & 0 deletions .changeset/38692-knowledge-turso-retrieval-modes.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion packages/plugins/knowledge-turso/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<source>_g<n>` 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_<source>_g<n>` 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ for (const kind of ['memory', 'file'] as const) {
scope: true,
dropSource: true,
keywordLeg: true,
retrieval: true,
},
});
});
Expand Down
180 changes: 180 additions & 0 deletions packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts
Original file line number Diff line number Diff line change
@@ -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<number | null> = [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);
});
});
Loading
Loading