From 26c18ae6486b5c11a2a5fe07c57f9fd41befafa0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:10:52 +0000 Subject: [PATCH 1/4] wip(knowledge-turso): a scoped leg under the floor tries a wider approximate pass before the exact scan Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../src/__tests__/acceptance.test.ts | 38 +++++++++++ .../knowledge-turso/src/turso-adapter.ts | 68 +++++++++++++------ 2 files changed, 87 insertions(+), 19 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index ac7fe52428f..f9ea82f85f3 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1305,6 +1305,44 @@ 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 for that', async () => { + const s = source('ann_retry'); + const docs = corpus(s, 400); + // 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, docs, { vectorIndexOverfetch: 8 }); + const t = source('ann_retry_exact'); + const exact = await built(t, corpus(t, 400), { vectorIndexThreshold: Infinity }); + const QUERY = 'w1x w2x w3x'; + const ids = (hits: Array<{ sourceRecordId?: string }>) => hits.map((h) => h.sourceRecordId); + + // A quarter of the passages in scope: the first pass keeps about 4 of its 16, the second about 40 of + // its 160, which clears the floor, so the second pass answers, as the exact scan would, without it. + const quarter = [{ kind: 'record' as const, ids: docs.flatMap((d) => d.sourceRecordId ?? []).filter((_, i) => i % 4 === 0) }]; + let from = sql.length; + const wide = await adapter.search(QUERY, { source: s, topK: 2, scope: quarter }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 0 }); + // 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 }); + expect( + sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : [])), + ).toEqual([16, 160]); + expect(ids(wide)).toEqual(ids(await exact.adapter.search(QUERY, { source: t, topK: 2, scope: quarter }))); + + // The five nearest passages in scope: both passes keep at most 5, so the exact scan answers after both. + const nearest = ids(await adapter.search(QUERY, { source: s, topK: 5 })).flatMap((id) => id ?? []); + from = sql.length; + const five = await adapter.search(QUERY, { source: s, topK: 2, scope: [{ kind: 'record', ids: nearest }] }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 1 }); + expect(ids(five)).toEqual(nearest.slice(0, 2)); + + // One record in scope (a narrow caller's visible ids): 10 × a pool of 1 cannot reach 16, so there is no + // second pass, and the exact scan answers as it did before the second pass existed. + from = sql.length; + const one = await adapter.search(QUERY, { source: s, topK: 2, scope: [{ kind: 'record', ids: [nearest[3]] }] }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); + expect(ids(one)).toEqual([nearest[3]]); + }); + 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..554eddef5bd 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,25 @@ 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: a scope too narrow for that (the visible + * ids of a narrow caller, a few hundred records) goes to the exact scan as + * before, without a pass that could not answer. Measured at 200,000 + * passages of 1,536 dimensions (clustered, topK 10, 40 candidates a hit) + * under a record scope: see the bench in the changeset that added it. + */ +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 +301,9 @@ 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 +802,32 @@ 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. + if (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. From 6c530b0e0bd13f7b59eb2c7da347e2caa8be0a00 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:35:30 +0000 Subject: [PATCH 2/4] wip(knowledge-turso): the second pass is not tried under a scope of record terms alone Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../src/__tests__/acceptance.test.ts | 70 ++++++++++++------- .../knowledge-turso/src/turso-adapter.ts | 30 +++++--- 2 files changed, 66 insertions(+), 34 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index f9ea82f85f3..49d414eee1a 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1305,43 +1305,63 @@ 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 for that', async () => { + 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'); - const docs = corpus(s, 400); // 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, docs, { vectorIndexOverfetch: 8 }); + const { adapter, sql, args } = await built(s, corpus(s), { vectorIndexOverfetch: 8 }); const t = source('ann_retry_exact'); - const exact = await built(t, corpus(t, 400), { vectorIndexThreshold: Infinity }); - const QUERY = 'w1x w2x w3x'; + 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 }; + }; - // A quarter of the passages in scope: the first pass keeps about 4 of its 16, the second about 40 of - // its 160, which clears the floor, so the second pass answers, as the exact scan would, without it. - const quarter = [{ kind: 'record' as const, ids: docs.flatMap((d) => d.sourceRecordId ?? []).filter((_, i) => i % 4 === 0) }]; - let from = sql.length; - const wide = await adapter.search(QUERY, { source: s, topK: 2, scope: quarter }); + // '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 }); - expect( - sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : [])), - ).toEqual([16, 160]); - expect(ids(wide)).toEqual(ids(await exact.adapter.search(QUERY, { source: t, topK: 2, scope: quarter }))); - // The five nearest passages in scope: both passes keep at most 5, so the exact scan answers after both. - const nearest = ids(await adapter.search(QUERY, { source: s, topK: 5 })).flatMap((id) => id ?? []); - from = sql.length; - const five = await adapter.search(QUERY, { source: s, topK: 2, scope: [{ kind: 'record', ids: nearest }] }); + // '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 }); - expect(ids(five)).toEqual(nearest.slice(0, 2)); - // One record in scope (a narrow caller's visible ids): 10 × a pool of 1 cannot reach 16, so there is no - // second pass, and the exact scan answers as it did before the second pass existed. - from = sql.length; - const one = await adapter.search(QUERY, { source: s, topK: 2, scope: [{ kind: 'record', ids: [nearest[3]] }] }); + // '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 }); - expect(ids(one)).toEqual([nearest[3]]); - }); + + // 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[]).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'); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 554eddef5bd..5573a5c3e2e 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -135,11 +135,15 @@ const VECTOR_MIN_POOL = 8; * 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: a scope too narrow for that (the visible - * ids of a narrow caller, a few hundred records) goes to the exact scan as - * before, without a pass that could not answer. Measured at 200,000 - * passages of 1,536 dimensions (clustered, topK 10, 40 candidates a hit) - * under a record scope: see the bench in the changeset that added it. + * 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 836, 853 and 790 ms and this pass's 326, 325 and + * 299 ms, at the floor's recall; under a record scope the exact scan's was + * 128, 207 and 265 ms, and this pass's 333, 313 and 407 ms. */ const VECTOR_RETRY_POOL = 10; @@ -302,8 +306,9 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise= VECTOR_MIN_POOL * topK) { + // 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; } From 5447b42c769db37391c987ad5c439129fb51cf2b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:46:54 +0000 Subject: [PATCH 3/4] perf(knowledge-turso): a scoped leg under the floor tries a wider approximate pass before the exact scan The second pass runs only when the record index cannot serve the exact scan: no scope, or a scope with a parent term. Bench numbers, README and a patch changeset. Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .changeset/knowledge-turso-scoped-second-pass.md | 16 ++++++++++++++++ packages/plugins/knowledge-turso/README.md | 2 +- .../plugins/knowledge-turso/src/turso-adapter.ts | 7 ++++--- 3 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 .changeset/knowledge-turso-scoped-second-pass.md 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/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 5573a5c3e2e..b83cf886390 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -141,9 +141,10 @@ const VECTOR_MIN_POOL = 8; * 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 836, 853 and 790 ms and this pass's 326, 325 and - * 299 ms, at the floor's recall; under a record scope the exact scan's was - * 128, 207 and 265 ms, and this pass's 333, 313 and 407 ms. + * 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; From 07a84d2e105cdac7bd81453fa57be88e8ed6bd6e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:58:05 +0000 Subject: [PATCH 4/4] test(knowledge-turso): read the fixture's tags through an optional metadata Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP Co-authored-by: Claude --- .../plugins/knowledge-turso/src/__tests__/acceptance.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 49d414eee1a..c56b8b70e4c 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1355,7 +1355,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { // 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[]).includes('wide')) + .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']);