From 5caac29461f2073b29aa23750e21cd550f28289d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:55:21 +0000 Subject: [PATCH 1/5] wip(knowledge-turso): a narrow record-only scope goes straight to the exact scan Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso/src/turso-adapter.ts | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index b83cf886390..a9baf038125 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -148,6 +148,19 @@ const VECTOR_MIN_POOL = 8; */ const VECTOR_RETRY_POOL = 10; +/** + * How many times the floor ({@link VECTOR_MIN_POOL} × topK) the first + * approximate pass must be expected to keep in scope for a scope of record + * terms alone to take that pass: the `topK × vectorIndexOverfetch` + * candidates times the share of the passages in scope, which a count of the + * rows in scope, served by the record index and stopped at the cut-over, + * reads. A narrower scope goes straight to the exact scan, which the record + * index serves from the rows in scope: the one-bit pass, which reads every + * row of the table, would mostly leave a pool under the floor and be followed + * by that scan anyway. PLACEHOLDER — placed by the bench. + */ +const VECTOR_RECORD_SCOPE_POOL = 1.5; + /** 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; @@ -811,6 +824,22 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (terms.length > 0) await this.ensureKeywordIndex(tableName); const instance = now.active.createdAt; if (vectorLeg && (await this.approximateSearchable(tableName, instance))) { + const candidates = topK * this.vectorIndexOverfetch; + // A scope of record terms alone too narrow for the first pass to be + // expected to clear the floor (VECTOR_RECORD_SCOPE_POOL) goes straight + // to the exact scan, which the record index serves from the rows in + // scope. The count reads those rows' index entries, at most up to the cut-over. + if (recordScope) { + const cut = (VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL) / this.vectorIndexOverfetch; + const counted = await client.execute({ + sql: `WITH total AS (SELECT count(*) AS n FROM ${table}) + SELECT n, (SELECT count(*) FROM (SELECT 1 FROM ${table} WHERE ${inScope} + LIMIT (SELECT CAST(n * ?${args.length + 1} AS INTEGER) + 1 FROM total))) AS k FROM total`, + args: [...args, cut] as InArgs, + }); + const { n, k } = counted.rows[0]; + if (Number(k) < Number(n) * cut) return client.execute(statement()); + } // 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 approximate = (candidates: number) => @@ -826,7 +855,6 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { 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; From fccb36c599757b4092eef6e6601eb59051fa2ecc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 11:15:55 +0000 Subject: [PATCH 2/5] wip(knowledge-turso): estimate a record scope's passages from a sample of its ids; tests Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/__tests__/acceptance.test.ts | 62 +++++++++++++-- .../knowledge-turso/src/turso-adapter.ts | 79 +++++++++++++------ 2 files changed, 109 insertions(+), 32 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index c56b8b70e4c..25774e93231 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1288,8 +1288,8 @@ 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_')); @@ -1297,12 +1297,13 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { 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 () => { @@ -1353,16 +1354,59 @@ 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[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 }); + expect(hits.map((h) => h.chunkId)).toEqual(want.map((h) => h.chunkId)); + 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. + expect(await search([{ kind: 'record', ids: records(0, 20) }])).toEqual({ approximate: 1, exact: 0 }); + // 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 }); + // The narrow records beside a parent (metadata) term: the record index does not serve that scan, so + // the approximate passes run as before (a thin first pool, then the wider pass, which answers). + expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 2, exact: 0 }); + // The count of the passages in scope binds the scope's ids alone, each once. + 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]); + expect(JSON.parse(String(counts[3][0]))).toEqual(records(100, 180)); + }, 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)); @@ -1492,13 +1536,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 }); }); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index a9baf038125..5246e5b7da6 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -151,15 +151,22 @@ const VECTOR_RETRY_POOL = 10; /** * How many times the floor ({@link VECTOR_MIN_POOL} × topK) the first * approximate pass must be expected to keep in scope for a scope of record - * terms alone to take that pass: the `topK × vectorIndexOverfetch` - * candidates times the share of the passages in scope, which a count of the - * rows in scope, served by the record index and stopped at the cut-over, - * reads. A narrower scope goes straight to the exact scan, which the record - * index serves from the rows in scope: the one-bit pass, which reads every - * row of the table, would mostly leave a pool under the floor and be followed - * by that scan anyway. PLACEHOLDER — placed by the bench. + * terms alone to take it: its `topK × vectorIndexOverfetch` candidates times + * the share of the passages in scope. A narrower scope goes straight to the + * exact scan, which the record index serves from the rows in scope; the + * one-bit pass reads every row of the table, and under such a scope it often + * leaves a pool under the floor, so the exact scan follows it anyway. With + * the default 40 candidates a hit, the cut-over is 25% of the passages in + * scope. Measured at 200,000 passages of 1,536 dimensions (clustered, topK + * 10), 50 queries a share, the p95 of the exact scan and of the search + * through the one-bit pass first: at 20% in scope 228 and 373 ms (48% of the + * queries ran both), at 25% 308 and 200 ms (2% ran both), at 10% 133 and + * 282, at 35% 435 and 188, at 50% 689 and 221. */ -const VECTOR_RECORD_SCOPE_POOL = 1.5; +const VECTOR_RECORD_SCOPE_POOL = 1.25; + +/** At most how many of a record scope's ids the estimate of its passages counts ({@link VECTOR_RECORD_SCOPE_POOL}). */ +const VECTOR_SCOPE_SAMPLE = 256; /** 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; @@ -322,7 +329,9 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(); if (opts.organizationIds !== undefined) { args.push(JSON.stringify(opts.organizationIds)); where.push(`organization_id IN (SELECT value FROM json_each(?${args.length}))`); @@ -727,6 +738,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const ids = `(SELECT value FROM json_each(?${args.length}))`; if (term.kind === 'record') { scopeTerms.push(`source_record_id IN ${ids}`); + for (const id of term.ids) recordIds.add(id); continue; } parentTerm = true; @@ -825,21 +837,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const instance = now.active.createdAt; if (vectorLeg && (await this.approximateSearchable(tableName, instance))) { const candidates = topK * this.vectorIndexOverfetch; - // A scope of record terms alone too narrow for the first pass to be - // expected to clear the floor (VECTOR_RECORD_SCOPE_POOL) goes straight - // to the exact scan, which the record index serves from the rows in - // scope. The count reads those rows' index entries, at most up to the cut-over. - if (recordScope) { - const cut = (VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL) / this.vectorIndexOverfetch; - const counted = await client.execute({ - sql: `WITH total AS (SELECT count(*) AS n FROM ${table}) - SELECT n, (SELECT count(*) FROM (SELECT 1 FROM ${table} WHERE ${inScope} - LIMIT (SELECT CAST(n * ?${args.length + 1} AS INTEGER) + 1 FROM total))) AS k FROM total`, - args: [...args, cut] as InArgs, - }); - const { n, k } = counted.rows[0]; - if (Number(k) < Number(n) * cut) return client.execute(statement()); - } + // A scope of record terms alone that the first pass is not expected + // to answer goes straight to the exact scan, which the record index + // serves from the rows in scope. + if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordIds))) return client.execute(statement()); // 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 approximate = (candidates: number) => @@ -1268,6 +1269,36 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return (await this.organizationsIn(client, table)) <= 1; } + /** + * Whether a scope of record terms alone, of the distinct `recordIds`, keeps + * fewer of the passages of `table` than the first approximate pass needs to + * be expected to keep {@link VECTOR_RECORD_SCOPE_POOL} × the floor in scope: + * a share under that many times {@link VECTOR_MIN_POOL} / + * `vectorIndexOverfetch`. The passages in scope are estimated from those of + * at most {@link VECTOR_SCOPE_SAMPLE} of the ids, spread evenly over them, + * counted through the record index (exactly, for a scope of no more ids), + * so a record of many passages counts as many and an id of no passage as + * none. The organization and metadata filters are not counted: the exact + * scan reads every row the record index finds for the scope. Runs inside + * the client's queue. + */ + private async recordScopeUnderCut(db: Pick, table: string, recordIds: ReadonlySet): Promise { + const ids = [...recordIds]; + const sample = + ids.length <= VECTOR_SCOPE_SAMPLE + ? ids + : Array.from({ length: VECTOR_SCOPE_SAMPLE }, (_, i) => ids[Math.floor((i * ids.length) / VECTOR_SCOPE_SAMPLE)]); + const t = quoted(table); + const counted = await db.execute({ + sql: `SELECT (SELECT count(*) FROM ${t}) AS n, + (SELECT count(*) FROM ${t} WHERE source_record_id IN (SELECT value FROM json_each(?1))) AS k`, + args: [JSON.stringify(sample)], + }); + const n = Number(counted.rows[0].n); + const inScope = (Number(counted.rows[0].k) * ids.length) / Math.max(1, sample.length); + return inScope * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL * n; + } + /** Forgets what this process knew of the approximate vector index of every instance of the passage table `table`. */ private forgetVectorIndex(table: string): void { const prefix = vectorIndexKey(table, ''); From f041fa7a5f457ba2cb09c15efd4f8ecb8a28abe7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 11:34:43 +0000 Subject: [PATCH 3/5] test(knowledge-turso): the cut-over pins compare passages across the two sources Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso/src/__tests__/acceptance.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 25774e93231..c3a4b3de08e 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1386,7 +1386,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { 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 }); - expect(hits.map((h) => h.chunkId)).toEqual(want.map((h) => h.chunkId)); + // 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); }; @@ -1394,8 +1396,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { 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. - expect(await search([{ kind: 'record', ids: records(0, 20) }])).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 }); // The narrow records beside a parent (metadata) term: the record index does not serve that scan, so From eefc6556905114af0fd59cd3323fbf4250d4ec96 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 11:51:26 +0000 Subject: [PATCH 4/5] perf(knowledge-turso): sample a record scope's ids without a set of all of them Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso-record-scope-exact.md | 12 ++++++ .../src/__tests__/acceptance.test.ts | 15 ++++--- .../knowledge-turso/src/turso-adapter.ts | 40 ++++++++++++------- 3 files changed, 47 insertions(+), 20 deletions(-) create mode 100644 .changeset/knowledge-turso-record-scope-exact.md diff --git a/.changeset/knowledge-turso-record-scope-exact.md b/.changeset/knowledge-turso-record-scope-exact.md new file mode 100644 index 00000000000..80d6847cc88 --- /dev/null +++ b/.changeset/knowledge-turso-record-scope-exact.md @@ -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: BENCH_TABLE. Recall@10 against the exact scan is equal or higher at every share. 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. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index c3a4b3de08e..0435cbfa125 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1401,13 +1401,18 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { 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 passes run as before (a thin first pool, then the wider pass, which answers). - expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 2, exact: 0 }); - // The count of the passages in scope binds the scope's ids alone, each once. + // 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]); - expect(JSON.parse(String(counts[3][0]))).toEqual(records(100, 180)); + 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 () => { diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 5246e5b7da6..ff1f06686bd 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -717,8 +717,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const where: string[] = []; // Whether the record index can serve the exact scan: a scope of record terms alone. let recordScope = false; - // The ids of the scope's record terms, each once. - const recordIds = new Set(); + // The ids of the scope's record terms, term by term. + const recordTerms: string[][] = []; if (opts.organizationIds !== undefined) { args.push(JSON.stringify(opts.organizationIds)); where.push(`organization_id IN (SELECT value FROM json_each(?${args.length}))`); @@ -738,7 +738,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const ids = `(SELECT value FROM json_each(?${args.length}))`; if (term.kind === 'record') { scopeTerms.push(`source_record_id IN ${ids}`); - for (const id of term.ids) recordIds.add(id); + recordTerms.push(term.ids); continue; } parentTerm = true; @@ -840,7 +840,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // A scope of record terms alone that the first pass is not expected // to answer goes straight to the exact scan, which the record index // serves from the rows in scope. - if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordIds))) return client.execute(statement()); + if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordTerms))) return client.execute(statement()); // 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 approximate = (candidates: number) => @@ -1270,7 +1270,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } /** - * Whether a scope of record terms alone, of the distinct `recordIds`, keeps + * Whether a scope of record terms alone, of the ids `terms` hold, keeps * fewer of the passages of `table` than the first approximate pass needs to * be expected to keep {@link VECTOR_RECORD_SCOPE_POOL} × the floor in scope: * a share under that many times {@link VECTOR_MIN_POOL} / @@ -1278,16 +1278,26 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { * at most {@link VECTOR_SCOPE_SAMPLE} of the ids, spread evenly over them, * counted through the record index (exactly, for a scope of no more ids), * so a record of many passages counts as many and an id of no passage as - * none. The organization and metadata filters are not counted: the exact - * scan reads every row the record index finds for the scope. Runs inside - * the client's queue. + * none (an id two terms name is one id to the count, and weighs twice in + * the estimate of a sampled scope). The organization and metadata filters + * are not counted: the exact scan reads every row the record index finds + * for the scope. Runs inside the client's queue. */ - private async recordScopeUnderCut(db: Pick, table: string, recordIds: ReadonlySet): Promise { - const ids = [...recordIds]; - const sample = - ids.length <= VECTOR_SCOPE_SAMPLE - ? ids - : Array.from({ length: VECTOR_SCOPE_SAMPLE }, (_, i) => ids[Math.floor((i * ids.length) / VECTOR_SCOPE_SAMPLE)]); + private async recordScopeUnderCut(db: Pick, table: string, terms: readonly (readonly string[])[]): Promise { + const total = terms.reduce((sum, ids) => sum + ids.length, 0); + const sample: string[] = []; + if (total <= VECTOR_SCOPE_SAMPLE) { + for (const ids of terms) sample.push(...ids); + } else { + // The ids at evenly spread positions of the terms taken one after another. + let term = 0; + let before = 0; + for (let i = 0; i < VECTOR_SCOPE_SAMPLE; i++) { + const at = Math.floor((i * total) / VECTOR_SCOPE_SAMPLE); + while (at >= before + terms[term].length) before += terms[term++].length; + sample.push(terms[term][at - before]); + } + } const t = quoted(table); const counted = await db.execute({ sql: `SELECT (SELECT count(*) FROM ${t}) AS n, @@ -1295,7 +1305,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { args: [JSON.stringify(sample)], }); const n = Number(counted.rows[0].n); - const inScope = (Number(counted.rows[0].k) * ids.length) / Math.max(1, sample.length); + const inScope = (Number(counted.rows[0].k) * total) / Math.max(1, sample.length); return inScope * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL * n; } From f041d0a89858bddc6451d41e561b08fa770b35dd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:50:20 +0000 Subject: [PATCH 5/5] docs(knowledge-turso): the README and the changeset state the cut-over and its bench Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/knowledge-turso-record-scope-exact.md | 2 +- packages/plugins/knowledge-turso/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/knowledge-turso-record-scope-exact.md b/.changeset/knowledge-turso-record-scope-exact.md index 80d6847cc88..f6f400a99cd 100644 --- a/.changeset/knowledge-turso-record-scope-exact.md +++ b/.changeset/knowledge-turso-record-scope-exact.md @@ -9,4 +9,4 @@ 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: BENCH_TABLE. Recall@10 against the exact scan is equal or higher at every share. 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. +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. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 0c602ab1720..edb881b94f9 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. 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).