diff --git a/.changeset/knowledge-turso-scoped-second-pass.md b/.changeset/knowledge-turso-scoped-second-pass.md new file mode 100644 index 00000000000..6d43c056c21 --- /dev/null +++ b/.changeset/knowledge-turso-scoped-second-pass.md @@ -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. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 98dd2c14707..0c602ab1720 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -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). diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index ac7fe52428f..c56b8b70e4c 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -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[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)); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index e0b816b85d3..b83cf886390 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { createHash } from 'node:crypto'; -import type { Client, InArgs, InStatement, Transaction } from '@libsql/client'; +import type { Client, InArgs, InStatement, ResultSet, Transaction } from '@libsql/client'; import type { AdapterContext, AdapterEmbeddingDescriptor, @@ -124,10 +124,30 @@ export const VECTOR_INDEX_OVERFETCH = 40; * of 1,536 dimensions (clustered, topK 10, 40 candidates a hit), a pool of * at least topK gave a recall@10 of 0.95 with 10% of the passages in scope, * 0.91 at 5% and 0.88 at 3%; a pool of at least 4 × topK still left a query - * at 0.7 with 10% in scope. At 8 × topK a scope of 15% or less runs exact. + * at 0.7 with 10% in scope. At 8 × topK alone a scope of 15% or less runs + * exact; {@link VECTOR_RETRY_POOL} is what answers those first. */ const VECTOR_MIN_POOL = 8; +/** + * How many times the first pass's candidates a second approximate pass + * reads, when the first leaves fewer than {@link VECTOR_MIN_POOL} × topK in + * scope: the same `WHERE` over the nearest `topK × vectorIndexOverfetch × 10` + * by their one-bit vector, kept only if it clears the same floor; otherwise + * the leg runs exact. It is tried only when the first pass's pool, scaled by + * this factor, reaches the floor, so a scope too narrow for it goes to the + * exact scan without a pass that could not answer; and never under a scope + * of record terms alone, whose exact scan the record index serves from the + * rows in scope. Measured at 200,000 passages of 1,536 dimensions + * (clustered, topK 10, 40 candidates a hit), 50 queries a share: under a + * parent (metadata) scope keeping 10%, 15% and 20% of the passages, the + * exact scan's p95 was 848, 907 and 908 ms and the search's with this pass + * 351, 328 and 337 ms, at the floor's recall; under a record scope the + * exact scan's was 128, 207 and 265 ms, and the search's with this pass + * 333, 313 and 407 ms. + */ +const VECTOR_RETRY_POOL = 10; + /** How many passages one batch of a vector index's copy writes: each batch is a transaction of its own, so a search waits at most one batch. */ const VECTOR_BACKFILL_BATCH = 2048; @@ -286,7 +306,10 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise ({ - sql: `WITH ${[...(vectorLeg ? vectorCtes(approximate) : []), ...ctes].join(',\n')} + // `candidates`: the approximate statement over that many one-bit candidates; absent, the exact one. + const statement = (candidates?: number): InStatement => ({ + sql: `WITH ${[...(vectorLeg ? vectorCtes(candidates !== undefined) : []), ...ctes].join(',\n')} SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash, - p.heading_path, u.vpos, u.kpos${approximate ? ', (SELECT count(*) FROM pool) AS pool' : ''} + p.heading_path, u.vpos, u.kpos${candidates !== undefined ? ', (SELECT count(*) FROM pool) AS pool' : ''} FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')}) GROUP BY chunk_id) u JOIN ${table} p ON p.chunk_id = u.chunk_id`, - args: (approximate ? [...args, topK * this.vectorIndexOverfetch] : args) as InArgs, + args: (candidates !== undefined ? [...args, candidates] : args) as InArgs, }); const result = await this.queued(client, async () => { // The generation may have been switched while the query was embedded. @@ -784,20 +813,34 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (vectorLeg && (await this.approximateSearchable(tableName, instance))) { // A failed approximate statement (its index gone under this process's // memory of it) forgets that memory and is answered by the exact scan. - const near = await client.execute(statement(true)).catch(() => { - this.vectorIndexKnown.delete(vectorIndexKey(tableName, instance)); - return undefined; - }); - if (near === undefined) return client.execute(statement(false)); + const approximate = (candidates: number) => + client.execute(statement(candidates)).catch(() => { + this.vectorIndexKnown.delete(vectorIndexKey(tableName, instance)); + return undefined; + }); // A vector leg the filter left with fewer than VECTOR_MIN_POOL × topK - // candidates in scope is run again as the exact scan: the float32 - // re-rank of a thin pool misses neighbours the one-bit ranking put - // past the cut, and an answer of fewer than topK says the source - // holds no more, which the candidates cannot say. - const pool = Number(near.rows[0]?.pool ?? 0); - if (pool >= VECTOR_MIN_POOL * topK && near.rows.filter((r) => r.vpos !== null).length >= topK) return near; + // candidates in scope does not stand: the float32 re-rank of a thin + // pool misses neighbours the one-bit ranking put past the cut, and an + // answer of fewer than topK says the source holds no more, which the + // candidates cannot say. + const poolOf = (near: ResultSet) => Number(near.rows[0]?.pool ?? 0); + const stands = (near: ResultSet) => + poolOf(near) >= VECTOR_MIN_POOL * topK && near.rows.filter((r) => r.vpos !== null).length >= topK; + const candidates = topK * this.vectorIndexOverfetch; + const near = await approximate(candidates); + if (near === undefined) return client.execute(statement()); + if (stands(near)) return near; + // Such a leg tries VECTOR_RETRY_POOL times the candidates once, under + // the same floor, when the first pool says the wider one can reach it; + // otherwise, or short again, the exact scan answers. Not under a scope + // of record terms alone: the record index serves that exact scan from + // the rows in scope, which costs less than the wider pass. + if (!recordScope && poolOf(near) * VECTOR_RETRY_POOL >= VECTOR_MIN_POOL * topK) { + const wide = await approximate(candidates * VECTOR_RETRY_POOL); + if (wide !== undefined && stands(wide)) return wide; + } } - return client.execute(statement(false)); + return client.execute(statement()); }); if (result === undefined) { // Switched while the query was embedded: searched again, a bounded number of times.