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

perf(knowledge-turso): a narrowly scoped vector search tries a wider approximate pass before the exact scan

Clause-②: no
Metadata-protocol: none

The approximate vector leg runs the exact scan when its filter leaves fewer than 8 × `topK` candidates in scope. A search whose scope keeps a fifth of the passages or less hit that floor almost every time and paid the full exact scan. Such a leg now first reads 10 times the candidates once, with the same `WHERE` and the same floor. It keeps that answer only if it clears the floor, and otherwise runs the exact scan as before.

- **Where it runs.** With no scope, or a scope that holds a parent (metadata) term. A scope of record terms alone keeps the old path: its exact scan reads only the rows in scope through the record index, and that costs less than the wider pass.
- **When it is skipped.** When the first pool, times 10, cannot reach the floor, for example a scope of one or two passages. Those go to the exact scan without the extra pass.
- **Measured** at 200,000 passages of 1,536 dimensions (clustered synthetic, `topK` 10, 50 queries per share), under a parent scope keeping 10%, 15% and 20% of the passages: p95 351, 328 and 337 ms, against 848, 907 and 908 ms for the exact scan. recall@10 is the same as the floor's alone.

No option and no export changes, and there is nothing to 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. 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 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".
- **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
58 changes: 58 additions & 0 deletions packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1305,6 +1305,64 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, 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 () => {
const QUERY = 'w1x w2x w3x w4x';
// Two best passages, 30 next to them and 368 further away, each with a list of tags a parent
// (metadata) scope term matches: 'wide' holds the two best and half the far ones, 'short' the two
// best and 3 next ones, 'thin' one far passage.
const corpus = (s: KnowledgeSource) => [
...['best_1', 'best_2'].map((n) => doc(s, n, QUERY, { metadata: { tags: ['wide', 'short'] } })),
...Array.from({ length: 30 }, (_, i) =>
doc(s, `mid_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 20) + 5}x w${(i % 7) + 30}x`, { metadata: { tags: [i < 3 ? 'short' : 'out'] } }),
),
...wordsOf(368, 23).map((text, i) =>
doc(s, `rest_${String(i).padStart(3, '0')}`, `w1x ${text}`, { metadata: { tags: i % 2 === 0 ? ['wide'] : i === 1 ? ['out', 'thin'] : ['out'] } }),
),
];
const s = source('ann_retry');
// topK 2 and 8 candidates a hit: 16 candidates, a floor of 16, and 160 for the second pass.
const { adapter, sql, args } = await built(s, corpus(s), { vectorIndexOverfetch: 8 });
const t = source('ann_retry_exact');
const exact = await built(t, corpus(t), { vectorIndexThreshold: Infinity });
const ids = (hits: Array<{ sourceRecordId?: string }>) => hits.map((h) => h.sourceRecordId);
const tagged = (tag: string) => [{ kind: 'metadata' as const, field: 'tags', ids: [tag] }];
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 });
expect(ids(hits), JSON.stringify(scope).slice(0, 60)).toEqual(ids(await exact.adapter.search(QUERY, { source: t, topK: 2, scope })));
return { hits, from };
};

// 'wide': the first pass keeps the 2 best of its 16 candidates; 10 × a pool of 2 can reach 16, and the
// second pass keeps far more than 16 of its 160, so it answers, as the exact scan would, without it.
let { hits, from } = await search(tagged('wide'));
expect(ids(hits)).toEqual(['best_1', 'best_2']);
expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 0 });
expect(sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : []))).toEqual([16, 160]);
// Each pass binds exactly the values it reads, its candidate count last.
for (const st of vectorStatements({ sql, args }, from)) expect(st).toMatchObject({ reads: st.bound });

// 'short': five passages in scope, so both passes keep at most 5, and the exact scan answers after both.
({ from } = await search(tagged('short')));
expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 1 });

// 'thin': one far passage, no candidate of the first pass; 10 × 0 cannot reach 16, so there is no
// second pass.
({ hits, from } = await search(tagged('thin')));
expect(ids(hits)).toEqual(['rest_001']);
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.
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 });
// Two builds of 400 passages on each store kind: past vitest's 5 s default on a loaded CI box.
}, 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
Loading
Loading