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
12 changes: 12 additions & 0 deletions .changeset/knowledge-turso-record-scope-exact.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/knowledge-turso': patch
---

perf(knowledge-turso): a narrow record-only scope goes straight to the exact scan

Clause-②: no
Metadata-protocol: none

A vector search whose scope is record ids alone (no parent term) ran the approximate one-bit pass first, then the exact scan whenever the pass kept too few candidates in scope. Since the record index lets that exact scan read only the rows in scope, a narrow scope paid for both. The adapter now estimates how many passages such a scope keeps and goes straight to the exact scan when the first pass's `topK × vectorIndexOverfetch` candidates are not expected to keep 1.25 × the floor of 8 × `topK` in scope. With the default 40 candidates a hit, that is a scope of under 25% of the source's passages. The estimate counts, through the record index, the passages of at most 256 of the scope's ids (all of them when there are no more), so a record split into many passages counts as many. It costs one statement of about 1-2 ms at 200,000 passages.

Measured at 200,000 passages of 1,536 dimensions (clustered, topK 10, 50 record-scoped queries a share), p95 in ms before → after: 5% in scope 219 → 74, 10% 321 → 143, 20% 418 → 289 (the exact scan alone: 81, 154, 291); at 25%, 30%, 35% and 50% the path is unchanged (190 → 206, 187 → 204, 206 → 207, 223 → 228, the one added statement costing 1-2 ms). Recall@10 against the exact scan is equal or higher at every share (0.994 → 1.000 at 20%). A scope with a parent (metadata) term and a search with no scope keep the approximate path, the second pass included. Nothing to configure or migrate.
2 changes: 1 addition & 1 deletion packages/plugins/knowledge-turso/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge
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.

- **Exact scan.** The vector leg reads every row in scope. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms.
- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone goes straight to the exact scan after the first pass, since the record index reads only the rows in scope. So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there".
- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope, and when it keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages, estimated from the passages of at most 256 of its ids), it skips the first pass too and goes straight to the exact scan: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there".
- **Measured** on Linux x64 at 200,000 passages of 1,536 dimensions (clustered synthetic vectors, one organization, `topK` 10, on a shared machine): a search whose keyword leg matches nothing took 66 ms at the median and 81 ms at p95 (the exact scan: 958 ms and 1,054 ms), with a recall@10 against the exact scan of 0.998 over 100 queries; a hybrid search took 550 ms and 666 ms (exact: 1,416 ms and 1,544 ms), recall@10 1.000 — the keyword leg, unchanged, is most of that, and a term under three characters (`LIKE` over every row in scope) alone costs about 600 ms there.
- **When it is built.** At the end of a complete build, never on a search: the side table is made empty in one transaction, then the passage table's rows are copied in, 2,048 to a transaction, before the generation is switched to (or, for a build inside the active generation, while it keeps answering by the exact scan); 200,000 passages took 3 s and 54 MB. Every write after that also writes the passage's one-bit vector. A source that grows past the threshold between builds keeps the exact scan until its next complete build — at the latest the next daily reconcile. A database that refuses the one-bit vectors or the index's DDL (a host whose libSQL lacks them) gets no index: the build completes, the source keeps the exact scan, and the adapter's health check (the plugin's boot line, the knowledge health endpoint) names the source and the reason until a later build makes the index. A copy batch the database refuses ends the copy the same way: the side table, short of its passage table, is never searched, and the next complete build resumes it. The health check's record of a refusal is kept by the process that ran the build, until it restarts.
- **What a search reads to choose.** A process reads the store's catalog (two reads) the first time it searches a generation, and remembers whether that generation's index is complete. The memory is keyed per generation instance: its number and the time its row was made. A build remembers what it found for its own process, so a source under the threshold costs no catalog read there, and two reads once in any other process. With `vectorIndexThreshold: Infinity` a search never reads the catalog for an index, so an index made earlier under a finite threshold stays in place and is not searched. An index another process completes inside the active generation is used here after this process's next complete build of the source, or a restart. A search that takes the index also reads the organization index (three seeks).
Expand Down
70 changes: 62 additions & 8 deletions packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1288,21 +1288,22 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
...Array.from({ length: 6 }, (_, i) => doc(t, `second_${i}`, `${QUERY} w${i + 5}x`)),
...wordsOf(52, 11).map((text, i) => doc(t, `rest_${String(i).padStart(2, '0')}`, `w1x ${text}`)),
];
const over = await built(t, tiers, { vectorIndexOverfetch: 10 });
// Every passage but the two best in scope: 18 or more of the 2 × 10 candidates are left, 8 × topK
const over = await built(t, tiers, { vectorIndexOverfetch: 20 });
// Every passage but the two best in scope: 38 or more of the 2 × 20 candidates are left, 8 × topK
// and more, so the candidates answer, without the exact scan.
from = over.sql.length;
const allButBest = tiers.flatMap((d) => d.sourceRecordId ?? []).filter((id) => !id.startsWith('best_'));
const wide = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: allButBest }] });
expect(wide).toHaveLength(2);
for (const hit of wide) expect(hit.sourceRecordId).toMatch(/^second_/);
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 0 });
// Two passages in scope: at most 2 of the 20 candidates, fewer than 8 × topK, so the exact scan answers.
// Two passages in scope: at most 2 of the 40 candidates, fewer than 8 × topK, so the exact scan
// answers; a scope of records alone that narrow goes to it without the one-bit pass.
from = over.sql.length;
const scoped = ['second_1', 'second_4'];
const narrow = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: scoped }] });
expect(narrow.map((h) => h.sourceRecordId).sort()).toEqual(scoped);
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 1 });
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 0, exact: 1 });
});

it('a leg under 8 × topK in scope tries 10 × the candidates once before the exact scan, unless its pool is too thin or its scope is of records alone', async () => {
Expand Down Expand Up @@ -1353,16 +1354,67 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });

// The 'wide' passages as a scope of records alone: the record index serves the exact scan from the
// rows in scope, so there is no second pass, whatever the first pool.
// rows in scope, so there is no second pass, and at 8 candidates a hit no first one either: no share
// of the passages lets the 16 candidates be expected to keep 1.25 × the floor of 16.
const records = corpus(s)
.filter((d) => (d.metadata?.tags as string[] | undefined)?.includes('wide'))
.flatMap((d) => d.sourceRecordId ?? []);
({ hits, from } = await search([{ kind: 'record', ids: records }]));
expect(ids(hits)).toEqual(['best_1', 'best_2']);
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });
expect(vectorLegs(sql, from)).toEqual({ approximate: 0, exact: 1 });
// Two builds of 400 passages on each store kind: past vitest's 5 s default on a loaded CI box.
}, 30_000);

it('a scope of record terms alone that keeps under 25% of the passages goes straight to the exact scan; a wider one, or one with a parent term, takes the approximate pass', async () => {
const QUERY = 'w1x w2x w3x';
// 400 passages: records 000…039 hold five passages each, 040…239 one each.
const corpus = (s: KnowledgeSource) =>
wordsOf(240, 13).map((text, i) => {
const n = String(i).padStart(3, '0');
const d = doc(s, n, text);
if (i >= 40) return d;
return { ...d, chunks: [0, 1, 2, 3, 4].map((index) => ({ id: `${d.id}#${index}`, documentId: d.id, index, content: `${text} wz${index}x` })) };
});
const s = source('ann_record_cut');
// topK 2 and the default 40 candidates a hit: 80 candidates, a floor of 16. The first pass is taken
// when it is expected to keep 1.25 × that floor, 20 of the 80: 25% of the passages, 100 of 400.
const { adapter, sql, args } = await built(s, corpus(s));
const t = source('ann_record_cut_exact');
const exact = await built(t, corpus(t), { vectorIndexThreshold: Infinity });
const records = (from: number, to: number) => Array.from({ length: to - from }, (_, i) => String(from + i).padStart(3, '0'));
const search = async (scope: NonNullable<Parameters<TursoKnowledgeAdapter['search']>[1]['scope']>) => {
const from = sql.length;
const hits = await adapter.search(QUERY, { source: s, topK: 2, scope });
const want = await exact.adapter.search(QUERY, { source: t, topK: 2, scope });
// The passages the exact scan ranks, by record and passage: the two sources' chunk ids differ by their name.
const passages = (found: typeof hits) => found.map((h) => h.chunkId.slice(h.chunkId.indexOf(':')));
expect(passages(hits)).toEqual(passages(want));
return vectorLegs(sql, from);
};

// 99 passages in scope (records 141…239), under the cut: the exact scan alone, no one-bit pass.
expect(await search([{ kind: 'record', ids: records(141, 240) }])).toEqual({ approximate: 0, exact: 1 });
// 100 (records 140…239): the first pass, which keeps about 20 of its 80 candidates, and answers.
expect(await search([{ kind: 'record', ids: records(140, 240) }])).toEqual({ approximate: 1, exact: 0 });
// The passages in scope are counted, not the ids: 20 records holding 100 passages take the first pass
// (whose pool of near-duplicate passages may then fall short, and the exact scan follow).
expect((await search([{ kind: 'record', ids: records(0, 20) }])).approximate).toBe(1);
// Two terms of 40 records each, one id in both: 80 passages, under the cut.
expect(await search([{ kind: 'record', ids: records(100, 140) }, { kind: 'record', ids: records(139, 180) }])).toEqual({ approximate: 0, exact: 1 });
// 340 ids, of which only the last 40 name a record of this source: estimated from 256 of them,
// spread over the 340, as about 40 passages, so the exact scan alone.
const absent = Array.from({ length: 300 }, (_, i) => `gone_${i}`);
expect(await search([{ kind: 'record', ids: [...absent, ...records(200, 240)] }])).toEqual({ approximate: 0, exact: 1 });
// The narrow records beside a parent (metadata) term: the record index does not serve that scan, so
// the approximate pass runs as before, here answering from its first pool.
expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 1, exact: 0 });
// The count of the passages in scope binds the scope's ids alone, term by term.
const counts = sql.flatMap((q, i) => (!q.includes('vec AS (') && q.includes('source_record_id IN (SELECT value FROM json_each(?1))') ? [args[i]] : []));
expect(counts.map((bound) => bound.length)).toEqual([1, 1, 1, 1, 1]);
expect(JSON.parse(String(counts[3][0]))).toEqual([...records(100, 140), ...records(139, 180)]);
expect(JSON.parse(String(counts[4][0]))).toHaveLength(256);
}, 30_000);

it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => {
const s = source('ann_life');
const { adapter, client, sql } = await built(s, corpus(s, 60));
Expand Down Expand Up @@ -1492,13 +1544,15 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
await adapter.completeBuild(ctx(s));
expect(keywordTerms('?! …')).toEqual([]);
const from = watched.sql.length;
// Answered through the index; then a scope of its two hits, under the floor, runs both statements.
// Answered through the index; then a scope of its two records beside a parent term, under the
// floor, runs both approximate passes and the exact scan, and the two records alone the exact scan.
const hits = await adapter.search('?! …', { source: s, topK: 2 });
expect(hits).toHaveLength(2);
const ids = hits.flatMap((h) => h.sourceRecordId ?? []);
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }, { kind: 'metadata', field: 'status', ids: ['none'] }] })).toHaveLength(2);
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }] })).toHaveLength(2);
const statements = vectorStatements(watched, from);
expect(statements.map((st) => st.approximate)).toEqual([true, true, false]);
expect(statements.map((st) => st.approximate)).toEqual([true, true, true, false, false]);
for (const st of statements) expect(st).toMatchObject({ reads: st.bound });
});

Expand Down
Loading
Loading