From 1e3bd96c04d6ead1add9019a5dbd48c240adbb88 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 20:16:56 +0000 Subject: [PATCH 01/15] wip(knowledge-turso): approximate vector index for large single-organization sources Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/plugins/knowledge-turso/src/sql.ts | 144 ++++++++++ .../knowledge-turso/src/turso-adapter.ts | 251 +++++++++++++++++- 2 files changed, 382 insertions(+), 13 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index fd3f5c345fb..f8c6a7a0f2c 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -252,6 +252,150 @@ export function keywordIndexShape( return found.length === 2 + triggers.length ? 'complete' : 'partial'; } +/** + * The names of a passage table's approximate vector index: a side table + * (`-vec`: an integer key, the chunk id, and the passage's vector in + * float8), libSQL's DiskANN index on it (`
$vec`, which libSQL keeps in + * a shadow table `
$vec_shadow`), an index of the passage table's + * organization column (`
-org`), and the three triggers that keep the + * side table in step with every write to the passage table. A DiskANN index + * name cannot hold a hyphen, so it holds a `$`, which no source id, generation + * table or object name can hold either; the other names hold a hyphen. + */ +export function vectorIndexNames(table: string): { + side: string; + index: string; + shadow: string; + org: string; + triggers: [string, string, string]; +} { + return { + side: `${table}-vec`, + index: `${table}$vec`, + shadow: `${table}$vec_shadow`, + org: `${table}-org`, + triggers: [`${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`], + }; +} + +/** + * The settings of the DiskANN index, measured at 1,536 dimensions on 5,000 + * clustered vectors: neighbours compressed to one bit and at most 32 of them + * cost about 3 ms a vector to insert and about 11 KB a vector on disk, with a + * recall@10 of 0.998 against the exact scan; float8 neighbours cost three times + * the time and size for no measured recall gain. Libsql's defaults (float32 + * neighbours) took 329 MB and 21.8 s for 1,000 vectors. + */ +export const VECTOR_INDEX_SETTINGS = `'metric=cosine', 'compress_neighbors=float1bit', 'max_neighbors=32'`; + +/** + * The statements that make a passage table's approximate vector index ({@link + * vectorIndexNames}), empty: the side table and its DiskANN index, the + * organization index of the passage table, and the triggers. The rows the + * passage table already holds are copied in afterwards, a batch at a time + * ({@link vectorBackfillSql}); the triggers, made first, keep every row + * written meanwhile in step, so the side table holds a subset of the passage + * table's chunks at every moment, and all of them once the copy ends. + */ +export function vectorIndexDdl(table: string, dimensions: number): string[] { + if (!Number.isInteger(dimensions) || dimensions < 1) { + throw new RangeError(`knowledge-turso: vector dimensions must be a positive integer, got ${String(dimensions)}`); + } + const { side, index, org, triggers } = vectorIndexNames(table); + const t = quoted(table); + const s = quoted(side); + return [ + // The organization index is kept: it may be there alone (made for a + // table found to hold more than one organization), and serves as it is. + ...dropVectorIndexDdl(table).filter((statement) => !statement.includes(quoted(org))), + `CREATE TABLE ${s} (id INTEGER PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE, embedding F8_BLOB(${dimensions}) NOT NULL)`, + `CREATE INDEX ${quoted(index)} ON ${s} (libsql_vector_idx(embedding, ${VECTOR_INDEX_SETTINGS}))`, + organizationIndexDdl(table), + `CREATE TRIGGER ${quoted(triggers[0])} AFTER INSERT ON ${t} BEGIN + INSERT INTO ${s} (chunk_id, embedding) VALUES (new.chunk_id, vector8(new.embedding)) + ON CONFLICT (chunk_id) DO UPDATE SET embedding = excluded.embedding; +END`, + `CREATE TRIGGER ${quoted(triggers[1])} AFTER DELETE ON ${t} BEGIN + DELETE FROM ${s} WHERE chunk_id = old.chunk_id; +END`, + `CREATE TRIGGER ${quoted(triggers[2])} AFTER UPDATE OF chunk_id, embedding ON ${t} + WHEN old.chunk_id IS NOT new.chunk_id OR old.embedding IS NOT new.embedding BEGIN + UPDATE ${s} SET chunk_id = new.chunk_id, embedding = vector8(new.embedding) WHERE chunk_id = old.chunk_id; +END`, + ]; +} + +/** The statement that makes the organization index of a passage table, the first part of its vector index to be made. */ +export function organizationIndexDdl(table: string): string { + return `CREATE INDEX IF NOT EXISTS ${quoted(vectorIndexNames(table).org)} ON ${quoted(table)} (organization_id)`; +} + +/** + * One batch of the copy of a passage table's rows into its vector side table: + * `last` reads the greatest chunk id of the next `?2` rows after the cursor + * `?1` (null when none is left), and `copy` copies the rows after `?1` up to + * and including `?2` that the side table does not hold yet. + */ +export function vectorBackfillSql(table: string): { last: string; copy: string } { + const t = quoted(table); + return { + last: `SELECT max(chunk_id) AS last FROM (SELECT chunk_id FROM ${t} WHERE chunk_id > ?1 ORDER BY chunk_id LIMIT ?2)`, + copy: + `INSERT INTO ${quoted(vectorIndexNames(table).side)} (chunk_id, embedding) ` + + `SELECT chunk_id, vector8(embedding) FROM ${t} WHERE chunk_id > ?1 AND chunk_id <= ?2 ORDER BY chunk_id ` + + 'ON CONFLICT (chunk_id) DO NOTHING', + }; +} + +/** The statements that drop a passage table's vector index; libSQL drops the DiskANN index and its shadow with the side table. */ +export function dropVectorIndexDdl(table: string): string[] { + const { side, index, org, triggers } = vectorIndexNames(table); + return [ + ...triggers.map((name) => `DROP TRIGGER IF EXISTS ${quoted(name)}`), + `DROP INDEX IF EXISTS ${quoted(org)}`, + `DROP INDEX IF EXISTS ${quoted(index)}`, + `DROP TABLE IF EXISTS ${quoted(side)}`, + ]; +} + +/** What is found under a passage table's vector-index names, read from `sqlite_master` rows (`type`, `name`, `tbl_name`, `sql`). */ +export type VectorIndexShape = 'none' | 'complete' | 'partial' | 'other'; + +/** + * Reads the shape of a passage table's vector index, as {@link + * keywordIndexShape} reads its keyword index: `complete` when the side table + * (exactly its three columns), its DiskANN index, the organization index and + * the three triggers are all there and are this module's; `none` when nothing + * is; `partial` when only some are; `other` when an object under one of those + * names (or the DiskANN shadow's) is not this module's — never dropped or used. + * `complete` says the structure is there, not that every row was copied in. + */ +export function vectorIndexShape( + table: string, + rows: ReadonlyArray>, + sideColumns: ReadonlyArray>, +): VectorIndexShape { + const { side, index, shadow, org, triggers } = vectorIndexNames(table); + const byName = new Map( + rows.map((r) => [String(r.name), { type: String(r.type), on: String(r.tbl_name), sql: String(r.sql ?? '') }]), + ); + const own = [side, index, org, ...triggers]; + const found = own.filter((n) => byName.has(n)); + if (found.length === 0 && !byName.has(shadow)) return 'none'; + const is = (name: string, type: string, on: string) => + !byName.has(name) || (byName.get(name)!.type === type && byName.get(name)!.on === on); + const sideOk = + is(side, 'table', side) && + (!byName.has(side) || sideColumns.map((c) => String(c.name)).sort().join(',') === 'chunk_id,embedding,id'); + const indexOk = is(index, 'index', side) && (!byName.has(index) || /libsql_vector_idx\s*\(/i.test(byName.get(index)!.sql)); + // The shadow is libSQL's, made with the DiskANN index and dropped with it. + const shadowOk = !byName.has(shadow) || (byName.has(index) && byName.get(shadow)!.type === 'table'); + const orgOk = is(org, 'index', table); + const triggersOk = triggers.every((n) => is(n, 'trigger', table)); + if (!sideOk || !indexOk || !shadowOk || !orgOk || !triggersOk) return 'other'; + return found.length === own.length ? 'complete' : 'partial'; +} + /** The most terms of one query the keyword leg matches; the rest are left to the vector leg. */ export const MAX_KEYWORD_TERMS = 16; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index b99f2149b65..44cf2f16c41 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -20,6 +20,7 @@ import { TRIGRAM_MIN_CHARS, type KeywordIndexShape, type TableShape, + type VectorIndexShape, tableShape, assertSourceId, containsPattern, @@ -34,6 +35,12 @@ import { legacyTable, passageTableDdl, quoted, + dropVectorIndexDdl, + organizationIndexDdl, + vectorBackfillSql, + vectorIndexDdl, + vectorIndexNames, + vectorIndexShape, vectorLiteral, } from './sql.js'; @@ -74,8 +81,42 @@ export interface TursoKnowledgeAdapterOptions { * bound (a `file:` store waits only for the busy timeout). */ requestTimeoutMs?: number; + /** + * The passage count at or above which a complete build of a source makes + * its approximate vector index (libSQL's DiskANN, `vector_top_k`), so its + * vector leg reads `topK × vectorIndexOverfetch` candidates instead of + * every vector. Counted when the build completes, on the generation it + * completes; `Infinity` never makes one. A source whose passage table holds + * more than one organization never gets one, and is never searched through + * one. @default 20000 + */ + vectorIndexThreshold?: number; + /** + * How many candidates per hit the vector leg reads from the approximate + * index before the organization, record-scope and metadata filter run: the + * index ranks before the filter, so a filter that removes candidates is + * answered from what is left, and a leg left with fewer than `topK` is run + * again as the exact scan. A whole number, 1 or more. @default 4 + */ + vectorIndexOverfetch?: number; } +/** The passage count at or above which a complete build makes a source's approximate vector index. */ +export const VECTOR_INDEX_THRESHOLD = 20_000; + +/** How many approximate-index candidates the vector leg reads per hit it ranks. */ +export const VECTOR_INDEX_OVERFETCH = 4; + +/** + * The most candidates libSQL's `vector_top_k` answers on one call, measured + * (a larger `k` answers this many); a vector leg that needs more takes the + * exact scan. + */ +export const VECTOR_TOP_K_MAX = 200; + +/** 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 = 128; + /** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; @@ -276,6 +317,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { private readonly noLegacy = new Set(); /** Passage tables whose keyword index is known to be complete. */ private readonly keyed = new Set(); + /** Passage tables whose vector side table is known to hold every passage (triggers keep it so). */ + private readonly vectorIndexed = new Set(); + private readonly vectorIndexThreshold: number; + private readonly vectorIndexOverfetch: number; constructor(opts: TursoKnowledgeAdapterOptions) { this.id = opts.id ?? 'turso'; @@ -287,6 +332,16 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (opts.requestTimeoutMs !== undefined && (!Number.isFinite(opts.requestTimeoutMs) || opts.requestTimeoutMs <= 0)) { throw new RangeError(`knowledge-turso: requestTimeoutMs must be a positive number, got ${String(opts.requestTimeoutMs)}`); } + const threshold = opts.vectorIndexThreshold ?? VECTOR_INDEX_THRESHOLD; + if (Number.isNaN(threshold) || threshold < 1) { + throw new RangeError(`knowledge-turso: vectorIndexThreshold must be a number of passages, 1 or more, got ${String(threshold)}`); + } + this.vectorIndexThreshold = threshold; + const overfetch = opts.vectorIndexOverfetch ?? VECTOR_INDEX_OVERFETCH; + if (!Number.isInteger(overfetch) || overfetch < 1) { + throw new RangeError(`knowledge-turso: vectorIndexOverfetch must be a whole number, 1 or more, got ${String(overfetch)}`); + } + this.vectorIndexOverfetch = overfetch; this.client = opts.client === undefined || opts.requestTimeoutMs === undefined ? opts.client @@ -586,16 +641,32 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const inScope = where.length === 0 ? 'TRUE' : where.join(' AND '); args.push(topK); const limit = `?${args.length}`; + args.push(Math.min(VECTOR_TOP_K_MAX, topK * this.vectorIndexOverfetch)); + const candidates = `?${args.length}`; const tableName = generationTable(opts.source.name, active.generation); const table = quoted(tableName); + const vectorIndex = vectorIndexNames(tableName); const legs: string[] = []; const ctes: string[] = []; - if (vectorLeg) { - ctes.push(`vec AS ( + // The vector leg, exact or approximate: the same in-scope WHERE and the + // same order by the stored vector's cosine distance, over every row in + // scope, or over those of the approximate index's `candidates` nearest + // that are in scope — that index ranks before the filter, so its + // candidates are filtered after. Either way the leg's ranks 1…topK feed + // the fusion below as they are. + const vectorCte = (approximate: boolean): string => { + const near = approximate + ? ` AND chunk_id IN (SELECT s.chunk_id FROM vector_top_k('${vectorIndex.index}', vector8(?1), ${candidates}) AS a + JOIN ${quoted(vectorIndex.side)} s ON s.id = a.id)` + : ''; + return `vec AS ( SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM ( - SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope} - ) WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`); + SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope}${near} + ) WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`; + }; + if (vectorLeg) { + ctes.push(vectorCte(false)); legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec'); } if (terms.length > 0) { @@ -629,20 +700,28 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); legs.push('SELECT chunk_id, NULL AS vpos, pos AS kpos FROM kw'); } - const result = await this.queued(client, async () => { - // The generation may have been switched while the query was embedded. - const now = await this.generations(opts.source.name); - if (now.active?.generation !== active.generation) return undefined; - if (terms.length > 0) await this.ensureKeywordIndex(tableName); - return client.execute({ - sql: `WITH ${ctes.join(',\n')} + const statement = (approximate: boolean): InStatement => ({ + sql: `WITH ${(approximate ? [vectorCte(true), ...ctes.slice(1)] : 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 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: args as InArgs, - }); + args: args as InArgs, + }); + const result = await this.queued(client, async () => { + // The generation may have been switched while the query was embedded. + const now = await this.generations(opts.source.name); + if (now.active?.generation !== active.generation) return undefined; + if (terms.length > 0) await this.ensureKeywordIndex(tableName); + if (vectorLeg && topK <= VECTOR_TOP_K_MAX && (await this.approximateSearchable(tableName))) { + const near = await client.execute(statement(true)); + // A vector leg the filter left with fewer than topK candidates is + // run again as the exact scan: an answer of fewer than topK says the + // source holds no more, which the candidates cannot say. + if (near.rows.filter((r) => r.vpos !== null).length >= topK) return near; + } + return client.execute(statement(false)); }); if (result === undefined) { // Switched while the query was embedded: searched again, a bounded number of times. @@ -722,6 +801,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const client = this.requireClient(); assertSourceId(ctx.source.name); await this.ready(); + // The approximate vector index of the generation this build completes, + // made before that generation is switched to, a batch at a time. + await this.buildVectorIndex(ctx.source.name, index.fingerprint); await this.queued(client, async () => { const legacy = await this.hasLegacy(ctx.source.name); await this.transaction(async (tx) => { @@ -936,9 +1018,136 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); } await this.assertKeywordIndexOurs(tx, table, sourceId, generation); + await this.assertVectorIndexOurs(tx, table, sourceId, generation); await tx.execute(`DROP TABLE IF EXISTS ${quoted(table)}`); for (const statement of dropKeywordIndexDdl(table)) await tx.execute(statement); + for (const statement of dropVectorIndexDdl(table)) await tx.execute(statement); this.keyed.delete(table); + this.vectorIndexed.delete(table); + } + + /** The shape of the vector index of the passage table `table` (`vectorIndexShape`). */ + private async vectorShapeOf(db: Pick, table: string): Promise { + const { side, index, shadow, org, triggers } = vectorIndexNames(table); + const names = [side, index, shadow, org, ...triggers]; + const rows = await db.execute({ + sql: `SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')})`, + args: names, + }); + const columns = await db.execute({ sql: 'SELECT name FROM pragma_table_info(?)', args: [side] }); + return vectorIndexShape(table, rows.rows, columns.rows); + } + + /** + * Refuses, naming it, an object under one of the vector-index names of + * `table` that this store did not make; the transaction is rolled back with + * the refusal, so nothing of the call is removed. + */ + private async assertVectorIndexOurs(db: Pick, table: string, sourceId: string, generation: number): Promise { + if ((await this.vectorShapeOf(db, table)) !== 'other') return; + throw vectorIndexNotOurs(table, sourceId, generation); + } + + /** + * Whether a search of the passage table `table` may rank its vector leg + * through the approximate index: its side table and DiskANN index are + * there and hold every passage of the table (once true, kept so by the + * triggers, and remembered), and the table holds passages of one + * organization at most — read at each search, from the organization index, + * so a second organization written after the index was made turns the + * table back to the exact scan at once. The index ranks before the + * organization filter: over two organizations' passages, one + * organization's candidates would crowd out the other's. Runs inside the + * client's queue. + */ + private async approximateSearchable(table: string): Promise { + const client = this.requireClient(); + if (!this.vectorIndexed.has(table)) { + if ((await this.vectorShapeOf(client, table)) !== 'complete') return false; + const counts = await client.execute( + `SELECT (SELECT count(*) FROM ${quoted(table)}) AS n, (SELECT count(*) FROM ${quoted(vectorIndexNames(table).side)}) AS v`, + ); + if (Number(counts.rows[0].n) !== Number(counts.rows[0].v)) return false; + this.vectorIndexed.add(table); + } + return (await this.organizationsIn(client, table)) <= 1; + } + + /** + * How many organizations the passages of `table` belong to, counting + * passages of no organization as one more, up to 2: three seeks of the + * organization index when the table has one. + */ + private async organizationsIn(db: Pick, table: string): Promise { + const t = quoted(table); + const found = await db.execute( + `SELECT (SELECT min(organization_id) FROM ${t}) AS lo, (SELECT max(organization_id) FROM ${t}) AS hi, + EXISTS (SELECT 1 FROM ${t} WHERE organization_id IS NULL) AS anonymous`, + ); + const { lo, hi, anonymous } = found.rows[0]; + const named = lo === null ? 0 : lo === hi ? 1 : 2; + return Math.min(2, named + (Number(anonymous) === 1 ? 1 : 0)); + } + + /** + * Makes the approximate vector index of the generation of `sourceId` a + * build under `fingerprint` completes (ADR-0161 K7: the generation under + * construction, or the active one rebuilt inside), when its passage table + * holds {@link TursoKnowledgeAdapterOptions.vectorIndexThreshold} passages + * or more, of one organization at most. The structure is made empty in one + * transaction, then the table's rows are copied in, {@link + * VECTOR_BACKFILL_BATCH} at a time, each batch a write transaction of its + * own on the client's queue: a search waits at most one batch, and is + * answered by the exact scan until the copy ends. A copy cut short (the + * process ended) resumes at the next complete build; the triggers keep + * every write in step meanwhile. A generation switched away or dropped + * during the copy ends it. + */ + private async buildVectorIndex(sourceId: string, fingerprint: string): Promise { + const client = this.requireClient(); + const planned = await this.queued(client, async () => { + const { active, building } = await this.generations(sourceId); + const target = + building?.fingerprint === fingerprint ? building : active?.fingerprint === fingerprint ? active : undefined; + // No generation of this fingerprint: completeBuild refuses the call. + if (target === undefined) return undefined; + const table = generationTable(sourceId, target.generation); + const shape = await this.vectorShapeOf(client, table); + if (shape === 'other') throw vectorIndexNotOurs(table, sourceId, target.generation); + if (shape !== 'complete') { + const count = await client.execute(`SELECT count(*) AS n FROM ${quoted(table)}`); + if (Number(count.rows[0].n) < this.vectorIndexThreshold) return undefined; + await this.transaction(async (tx) => { + await tx.execute(organizationIndexDdl(table)); + // One organization at most, or no index: it ranks before the organization filter. + if ((await this.organizationsIn(tx, table)) > 1) return { commit: true, value: undefined }; + for (const statement of vectorIndexDdl(table, target.dim)) await tx.execute(statement); + return { commit: true, value: undefined }; + }); + if ((await this.vectorShapeOf(client, table)) !== 'complete') return undefined; + } + return { target, table }; + }); + if (planned === undefined) return; + const { target, table } = planned; + const { last, copy } = vectorBackfillSql(table); + for (let cursor = ''; ; ) { + const step = await this.queued(client, () => + this.transaction(async (tx) => { + const still = await tx.execute({ + sql: `SELECT 1 FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ? AND fingerprint IS ?`, + args: [sourceId, target.generation, target.fingerprint], + }); + if (still.rows.length === 0) return { commit: false, value: undefined }; + const upTo = (await tx.execute({ sql: last, args: [cursor, VECTOR_BACKFILL_BATCH] })).rows[0]?.last; + if (upTo === null || upTo === undefined) return { commit: false, value: undefined }; + await tx.execute({ sql: copy, args: [cursor, String(upTo)] }); + return { commit: true, value: String(upTo) }; + }), + ); + if (step === undefined) return; + cursor = step; + } } /** The shape of the keyword index of the passage table `table` (`keywordIndexShape`). */ @@ -1027,8 +1236,13 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); } await this.assertKeywordIndexOurs(tx, table, sourceId, generation); + await this.assertVectorIndexOurs(tx, table, sourceId, generation); + // A vector index left behind under this name (its side table outlives the + // passage table's DROP) is dropped with it: the new table starts without one. + for (const statement of dropVectorIndexDdl(table)) await tx.execute(statement); for (const statement of passageTableDdl(table, embedder.dimensions)) await tx.execute(statement); this.keyed.add(table); + this.vectorIndexed.delete(table); await tx.execute({ sql: `INSERT INTO ${quoted(GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) VALUES (?, ?, ?, ?, ?, ?)`, args: [sourceId, generation, fingerprint ?? null, embedder.dimensions, embedder.model ?? null, state], @@ -1173,6 +1387,17 @@ function switchedDuringSearch(diagnosis: string, detail: string): Error { }); } +/** The refusal of an object under a vector-index name of `table` that the store did not make. */ +function vectorIndexNotOurs(table: string, sourceId: string, generation: number): Error { + const { side, index, org } = vectorIndexNames(table); + return notReady( + `an object it did not make holds a name of the vector index of generation ${generation} of source '${sourceId}'`, + `The database holds a table, index or trigger under '${side}', '${index}', '${org}' or a '${table}-vec-*' trigger ` + + `that is not this store's vector index, so it is not dropped, and generation ${generation} of source ` + + `'${sourceId}' cannot be built, replaced or removed. Rename or remove it, or keep the store in a database of its own.`, + ); +} + /** * The store is not ready. The message is one sentence with no database * detail, as a search caller may read it; what went wrong and what to do are From 931665ef5852731b7f5071f18ec4cbbbc8d887b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 20:22:19 +0000 Subject: [PATCH 02/15] test(knowledge-turso): pins for the approximate vector index path Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../src/__tests__/acceptance.test.ts | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 75c2178714d..24b2056b46e 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -875,3 +875,279 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { }); }); } + +/** + * A client whose every statement's SQL is recorded, the transaction's too, so + * a test reads which path a search took: the approximate vector leg names + * `vector_top_k`, the exact one does not. + */ +function recording(client: Client): { client: Client; sql: string[] } { + const sql: string[] = []; + const note = (statement: unknown) => sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + const watch = (target: T, onTransaction: boolean): T => + new Proxy(target, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key === 'execute') return (statement: unknown, ...rest: unknown[]) => (note(statement), fn(statement, ...rest)); + if (key === 'batch') return (statements: unknown[], ...rest: unknown[]) => (statements.forEach(note), fn(statements, ...rest)); + if (key === 'transaction' && onTransaction) { + return async (...a: unknown[]) => watch((await fn(...a)) as object, false); + } + return fn; + }, + }); + return { client: watch(client, true), sql }; +} + +/** The vector legs of the searches recorded since `from`: how many were approximate, how many exact. */ +function vectorLegs(sql: string[], from = 0): { approximate: number; exact: number } { + const legs = sql.slice(from).filter((s) => s.includes('vec AS (')); + const approximate = legs.filter((s) => s.includes('vector_top_k(')).length; + return { approximate, exact: legs.length - approximate }; +} + +/** The vector-index objects (side table, DiskANN index and its shadow, organization index, triggers) of a passage table. */ +async function vectorObjects(client: Client, table: string): Promise { + const names = [`${table}-vec`, `${table}$vec`, `${table}$vec_shadow`, `${table}-org`, `${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`]; + const found = await client.execute({ + sql: `SELECT name FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')}) ORDER BY name`, + args: names, + }); + return found.rows.map((r) => String(r.name)); +} + +/** Deterministic passages of four words from a vocabulary of 60, so their fake vectors overlap. */ +function wordsOf(n: number, seed: number): string[] { + const vocabulary = Array.from({ length: 60 }, (_, i) => `w${i.toString(36)}x`); + let x = seed; + const next = () => ((x = (x * 1103515245 + 12345) % 2147483648) / 2147483648); + return Array.from({ length: n }, () => Array.from({ length: 4 }, () => vocabulary[Math.floor(next() * vocabulary.length)]).join(' ')); +} + +for (const kind of ['memory', 'file'] as StoreKind[]) { + describe(`knowledge-turso approximate vector index on ${kind === 'memory' ? ':memory:' : 'a file: URL'}`, () => { + const store = storeOf(kind); + afterAll(() => store.closeAll()); + const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' }; + const THRESHOLD = 40; + + /** An adapter on a recorded client, and a complete build of `docs` under `fp`. */ + async function built( + s: KnowledgeSource, + docs: KnowledgeDocument[], + opts: { vectorIndexThreshold?: number; vectorIndexOverfetch?: number } = {}, + ) { + const watched = recording(store.client()); + const adapter = new TursoKnowledgeAdapter({ + id: 'under_test', + client: watched.client, + embedder: new FakeEmbedder(), + vectorIndexThreshold: THRESHOLD, + ...opts, + }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return { adapter, ...watched }; + } + + const corpus = (s: KnowledgeSource, n: number, extra: (i: number) => Partial = () => ({})) => + wordsOf(n, 7).map((text, i) => doc(s, String(i).padStart(3, '0'), text, extra(i))); + + it('a source at or above the threshold is searched through vector_top_k; below it, or at Infinity, by the exact scan', async () => { + const s = source('ann_switch'); + const above = await built(s, corpus(s, 60)); + expect(await vectorObjects(above.client, `knowledge_${s.name}_g1`)).toHaveLength(7); + const from = above.sql.length; + const hits = await above.adapter.search('w1x w2x w3x', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); + expect(hits).toHaveLength(5); + expect(vectorLegs(above.sql, from)).toEqual({ approximate: 1, exact: 0 }); + + for (const vectorIndexThreshold of [61, Infinity]) { + const t = source(`ann_off_${vectorIndexThreshold === Infinity ? 'inf' : 'n'}`); + const below = await built(t, corpus(t, 60), { vectorIndexThreshold }); + expect(await vectorObjects(below.client, `knowledge_${t.name}_g1`)).toEqual([]); + const at = below.sql.length; + await below.adapter.search('w1x w2x w3x', { source: t, topK: 5 }); + expect(vectorLegs(below.sql, at)).toEqual({ approximate: 0, exact: 1 }); + } + }); + + it('a store holding passages of two organizations never takes the approximate path, built or not', async () => { + const s = source('ann_two_orgs'); + const two = await built(s, corpus(s, 60, (i) => ({ organizationId: i % 2 === 0 ? 'org_a' : 'org_b' }))); + // No index for a table of two organizations: only its organization index is made. + expect(await vectorObjects(two.client, `knowledge_${s.name}_g1`)).toEqual([`knowledge_${s.name}_g1-org`]); + let from = two.sql.length; + await two.adapter.search('w1x w2x', { source: s, topK: 5, organizationIds: ['org_a'] }); + expect(vectorLegs(two.sql, from)).toEqual({ approximate: 0, exact: 1 }); + + // Built for one organization; a second one written after turns it back to the exact scan at once. + const t = source('ann_second_org'); + const one = await built(t, corpus(t, 60, () => ({ organizationId: 'org_a' }))); + from = one.sql.length; + await one.adapter.search('w1x w2x', { source: t, topK: 5, organizationIds: ['org_a'] }); + expect(vectorLegs(one.sql, from)).toEqual({ approximate: 1, exact: 0 }); + await one.adapter.upsert([doc(t, 'other', 'w1x w2x', { organizationId: 'org_b' })], ctx(t)); + from = one.sql.length; + const asB = await one.adapter.search('w1x w2x', { source: t, topK: 5, organizationIds: ['org_b'] }); + expect(asB.map((h) => h.documentId)).toEqual([`${t.name}:other`]); + expect(vectorLegs(one.sql, from)).toEqual({ approximate: 0, exact: 1 }); + // A passage of no organization beside one organization's is a second one too. + const u = source('ann_anonymous'); + const mixed = await built(u, corpus(u, 60, (i) => (i === 0 ? {} : { organizationId: 'org_a' }))); + from = mixed.sql.length; + await mixed.adapter.search('w1x w2x', { source: u, topK: 5 }); + expect(vectorLegs(mixed.sql, from)).toEqual({ approximate: 0, exact: 1 }); + }); + + it('the filter runs on the over-fetched candidates; a leg it leaves short of topK is run again exactly', async () => { + const s = source('ann_scope'); + const QUERY = 'w1x w2x w3x w4x'; + // 56 passages near the query, published; 4 far from it, drafts. + const docs = [ + ...Array.from({ length: 56 }, (_, i) => doc(s, `near_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 9) + 5}x`)), + ...['a', 'b', 'c', 'd'].map((n) => doc(s, `far_${n}`, `w1x wqx wrx ws${n}x`, { metadata: { status: 'draft' } })), + ]; + const { adapter, sql } = await built(s, docs); + // A filter only the far passages pass: none is among the candidates, so the exact scan answers. + let from = sql.length; + const drafts = await adapter.search(QUERY, { source: s, topK: 3, filter: { status: 'draft' } }); + expect(drafts).toHaveLength(3); + for (const hit of drafts) expect(hit.metadata).toMatchObject({ status: 'draft' }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); + // A record scope of passages ranked 3rd to 8th: the first two candidates are out of scope, and the + // over-fetch (2 × 4 candidates) still fills topK in scope, without the exact scan. + const t = source('ann_overfetch'); + const tiers = [ + ...['best_1', 'best_2'].map((n) => doc(t, n, QUERY)), + ...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); + from = over.sql.length; + const scoped = ['second_1', 'second_4']; + const inScope = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: scoped }] }); + expect(inScope.map((h) => h.sourceRecordId).sort()).toEqual(scoped); + expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 0 }); + }); + + 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)); + const g1 = `knowledge_${s.name}_g1`; + const counts = async (table: string) => + (await client.execute(`SELECT (SELECT count(*) FROM "${table}") AS n, (SELECT count(*) FROM "${table}-vec") AS v`)).rows[0]; + expect(await counts(g1)).toMatchObject({ n: 60, v: 60 }); + // A new passage is found through the index; a removed one is not. + await adapter.upsert([doc(s, 'fresh', 'wzzx wyyx wxxx')], ctx(s)); + let from = sql.length; + expect((await adapter.search('wzzx wyyx wxxx', { source: s, topK: 1 })).map((h) => h.sourceRecordId)).toEqual(['fresh']); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 0 }); + await adapter.upsert([doc(s, 'fresh', 'wqqx wppx wnnx')], ctx(s)); + expect((await adapter.search('wqqx wppx wnnx', { source: s, topK: 1 })).map((h) => h.sourceRecordId)).toEqual(['fresh']); + await adapter.delete([`${s.name}:fresh`, `${s.name}:000`], ctx(s)); + expect(await counts(g1)).toMatchObject({ n: 59, v: 59 }); + + // A rebuild under another fingerprint: the new generation gets its own index, the old one's goes with it. + await adapter.beginBuild(ctx(s, FP_B)); + await adapter.upsert(corpus(s, 60), ctx(s, FP_B)); + await adapter.completeBuild(ctx(s, FP_B)); + const g2 = `knowledge_${s.name}_g2`; + expect(await vectorObjects(client, g1)).toEqual([]); + expect(await vectorObjects(client, g2)).toHaveLength(7); + expect(await counts(g2)).toMatchObject({ n: 60, v: 60 }); + from = sql.length; + await adapter.search('w1x w2x', { source: s, topK: 5, index: { fingerprint: FP_B.fingerprint } }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 0 }); + + await adapter.dropSource(ctx(s, FP_B)); + expect(await vectorObjects(client, g2)).toEqual([]); + const left = await client.execute("SELECT name FROM sqlite_master WHERE name LIKE '%$vec%' OR name LIKE '%-vec%'"); + expect(left.rows).toEqual([]); + }); + + it('a source that grew past the threshold gets its index at its next complete build, inside its generation', async () => { + const s = source('ann_grew'); + const watched = recording(store.client()); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold: THRESHOLD }); + await adapter.upsert(corpus(s, 60), ctx(s)); + expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toEqual([]); + // A complete build under the same fingerprint rebuilds inside generation 1, and makes its index. + await adapter.beginBuild(ctx(s)); + await adapter.upsert(corpus(s, 60), ctx(s)); + await adapter.completeBuild(ctx(s)); + expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toHaveLength(7); + const from = watched.sql.length; + await adapter.search('w1x w2x', { source: s, topK: 5 }); + expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 1, exact: 0 }); + }); + + it('an object it did not make under a vector-index name is never dropped; the build and dropSource are refused', async () => { + const s = source('ann_taken'); + const watched = recording(store.client()); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold: THRESHOLD }); + await adapter.upsert(corpus(s, 60), ctx(s)); + const side = `knowledge_${s.name}_g1-vec`; + await watched.client.execute(`CREATE TABLE "${side}" (id TEXT PRIMARY KEY, note TEXT)`); + await watched.client.execute(`INSERT INTO "${side}" VALUES ('r1', 'kept')`); + for (const call of [ + async () => { + await adapter.beginBuild(ctx(s)); + await adapter.completeBuild(ctx(s)); + }, + () => adapter.dropSource(ctx(s)), + ]) { + const refused = await refusal(call()); + expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(String(refused.remedy)).toContain(side); + } + expect((await watched.client.execute(`SELECT note FROM "${side}"`)).rows.map((r) => r.note)).toEqual(['kept']); + expect(await tables(watched.client, `knowledge_${s.name}_g%`)).toEqual([`knowledge_${s.name}_g1`]); + // The exact scan still answers it. + const from = watched.sql.length; + expect(await adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 0, exact: 1 }); + }); + }); +} + +describe('knowledge-turso approximate vector index: recall and options', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + it('recall@10 of the approximate search against the exact-scan search is 0.95 or more on a sample of 40 queries', async () => { + const s = source('ann_recall'); + const docs = wordsOf(600, 3).map((text, i) => doc(s, String(i).padStart(3, '0'), text)); + const make = async (vectorIndexThreshold: number) => { + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder: new FakeEmbedder(), vectorIndexThreshold }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return adapter; + }; + const approximate = await make(100); + const exact = await make(Infinity); + let found = 0; + let wanted = 0; + for (const query of wordsOf(40, 99)) { + const want = (await exact.search(query, { source: s, topK: 10 })).map((h) => h.chunkId); + const got = new Set((await approximate.search(query, { source: s, topK: 10 })).map((h) => h.chunkId)); + wanted += want.length; + found += want.filter((id) => got.has(id)).length; + } + expect(wanted).toBe(400); + expect(found / wanted).toBeGreaterThanOrEqual(0.95); + }); + + it('refuses a threshold below 1 and an over-fetch that is not a whole number of 1 or more', () => { + const client = store.client(); + const embedder = new FakeEmbedder(); + for (const bad of [{ vectorIndexThreshold: 0 }, { vectorIndexThreshold: Number.NaN }, { vectorIndexOverfetch: 0 }, { vectorIndexOverfetch: 1.5 }]) { + expect(() => new TursoKnowledgeAdapter({ client, embedder, ...bad })).toThrow(RangeError); + } + expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 1 })).not.toThrow(); + }); +}); From 84f82932d4cf9f8dab27afa147dc71afeda33097 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 20:27:49 +0000 Subject: [PATCH 03/15] docs(knowledge-turso): the approximate index in the README and the knowledge docs; plugin options Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- content/docs/ai/knowledge-rag.mdx | 2 +- content/docs/protocol/knowledge.mdx | 23 ++++++++++++++----- packages/plugins/knowledge-turso/README.md | 16 ++++++++++--- .../src/__tests__/plugin.test.ts | 18 +++++++++++++++ packages/plugins/knowledge-turso/src/index.ts | 2 ++ .../plugins/knowledge-turso/src/plugin.ts | 10 ++++++++ .../knowledge-turso/src/turso-adapter.ts | 16 +++++++++---- 7 files changed, 72 insertions(+), 15 deletions(-) diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index c8af698620a..cf7ced39556 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -370,7 +370,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds — new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL ``` -- It searches with two legs merged by reciprocal rank fusion: an exact cosine scan, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs, before ranking. 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms; larger sources belong on pgvector. +- It searches with two legs merged by reciprocal rank fusion: a cosine ranking, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs. The cosine ranking is an exact scan — 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms — until a complete build finds a source of 20,000 passages or more (`vectorIndexThreshold`), all of one organization: that source gets libSQL's approximate (DiskANN) index, whose candidates are filtered after it ranks, never over two organizations. TBD_RAG Larger sources shared by many organizations belong on pgvector. - A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes. - Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 70901fc3ea7..8613f59a825 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -688,7 +688,8 @@ an exact scan. libSQL's native vectors (`F32_BLOB`, `vector32`, `vector_distance_cos`): the store for local development and for a deployment not on PostgreSQL. It takes the service's passages, embeds them with the kernel's `embedder` service (or -the `embedder` it is given), and answers a search by an exact scan. +the `embedder` it is given), and answers a search by an exact scan, or, for a +large source of one organization, through an approximate index. - **Which database.** The `url` option (`file:`, `:memory:` or a `libsql://` Turso URL), else `knowledge.db` under the project's @@ -712,11 +713,21 @@ the `embedder` it is given), and answers a search by an exact scan. passage table (kept in step by triggers), a term of three characters or more as a quoted phrase, a shorter one by `LIKE`. The organization filter, the [record scope](#record-scope) and the metadata `filter` (JSON equality - per key) are one `WHERE`, run in both legs before either ranks. The store creates no DiskANN index: `vector_top_k` ranks - before it filters, and with one, 1,000 vectors of 1,536 dimensions grew a - file from 8.2 MB to 329 MB and took 21.8 s to index. Without it the same - 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and - about 50 ms. A larger source belongs on `knowledge-pgvector`. + per key) are one `WHERE`, run in both legs. The exact scan reads every row + in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about + 5 ms; 10,000 take 82 MB and about 50 ms. +- **Approximate index.** A complete build that completes on a generation of + `vectorIndexThreshold` passages or more (default 20,000), all of one + organization, makes its DiskANN index (`vector_top_k`), copied in 128 rows to + a transaction before the switch, never on a search. The vector leg then + reads `topK × vectorIndexOverfetch` candidates (default 4, at most 200), + runs the same `WHERE` over them, ranks those in scope by their stored + vector, and feeds the fusion as the exact leg does; a leg the filter leaves + short of `topK` runs again as the exact scan, so a search never answers + fewer hits than the exact scan. The index ranks before it filters, so it is + never made, or used, over the passages of two organizations (passages of + none count as one): each search reads the organization index and takes the + exact scan once a second organization's passage is written. TBD_DOCS - **Rebuilds.** A changed fingerprint is refused (§3.6). A complete reindex under a new fingerprint builds a new generation table beside the active one, which keeps answering its own fingerprint, and switches at the end of diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 86f64d6280d..b6b2eded0f2 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -1,6 +1,6 @@ # @objectstack/knowledge-turso -`IKnowledgeAdapter` on [libSQL](https://github.com/tursodatabase/libsql)'s native vectors — the open vector store for local development (`os dev`) and for deployments not on PostgreSQL. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in a libSQL database of its own, and answers `search()` with two legs — an exact cosine scan and a keyword match — merged by reciprocal rank fusion. +`IKnowledgeAdapter` on [libSQL](https://github.com/tursodatabase/libsql)'s native vectors — the open vector store for local development (`os dev`) and for deployments not on PostgreSQL. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in a libSQL database of its own, and answers `search()` with two legs — a cosine ranking (an exact scan, or an approximate index for a large source of one organization) and a keyword match — merged by reciprocal rank fusion. ```ts import { ObjectKernel } from '@objectstack/core'; @@ -30,6 +30,8 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts | `projectRoot` | `process.cwd()` | The directory the default file is under. | | `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | +| `vectorIndexThreshold` | `20000` | The passage count at or above which a complete build makes a source's approximate vector index ([Search](#search)). `Infinity` never makes one. | +| `vectorIndexOverfetch` | `4` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 1 or more. | ## Its own file, never the platform's @@ -41,6 +43,7 @@ On a file the store sets WAL and a busy timeout: without them a second process w - `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints. - `knowledge__g` — the passages of one generation of one source, with an `F32_BLOB()` vector column sized for that generation. +- `knowledge__g-vec`, `…$vec`, `…-org` — a large source's approximate vector index ([Search](#search)), when it has one: a side table of the passages' vectors in float8, libSQL's DiskANN index on it (libSQL keeps it in `…$vec_shadow`), an index of the passage table's organization column, and three triggers that keep the side table in step. Dropped with the passage table, by a generation switch and by `dropSource`; an object under one of those names that the store did not make is never dropped or used, and the call is refused `SERVICE_UNAVAILABLE`, naming it. `` is the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two tables). When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: the source's generation tables and rows are dropped in one transaction. A table the store did not make under one of those names (an object's table, in a database shared with object tables) is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming the table, and nothing of the source is removed. @@ -50,9 +53,16 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` and `v1.2` are one term each (at most 16 terms). A term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. There is no word segmentation: a Chinese question is one term unless it holds spaces or punctuation, so the keyword leg finds a code, a name or a phrase as written, and the vector leg answers the question's meaning. - **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. -- **Vector leg.** An exact scan by cosine distance (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. +- **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. -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 before either ranks — libSQL's DiskANN index (`vector_top_k`) ranks first and filters after, so the store creates none. 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. (With a DiskANN index the same 1,000 vectors grew a file to 329 MB, and the index build took 21.8 s.) For larger sources, use `@objectstack/knowledge-pgvector`. +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 DiskANN index (`vector_top_k`; one-bit neighbours, at most 32 each). Its vector leg then reads `topK × vectorIndexOverfetch` candidates from the index (at most 200, the most `vector_top_k` answers), runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The index ranks before it filters, so a leg the filter leaves with fewer than `topK` candidates is run again as the exact scan: a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there". TBD_MEASURED +- **When it is built.** At the end of a complete build, never on a search or a record write: the index is made empty in one transaction, then the passage table's rows are copied in, 128 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). A search waits at most one batch. Every write after that pays the index's insert, about TBD_INSERT ms a passage. 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. +- **Never over two organizations.** Over two organizations' passages, the index's candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the index ranks, not on the whole database; on a hosted database, which holds one organization (cloud ADR-0114), it always holds. + +For a source of hundreds of thousands of passages shared by many organizations, use `@objectstack/knowledge-pgvector`. ## Rebuilds diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index ac599acb64a..37c2b4d0092 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -207,6 +207,24 @@ describe('KnowledgeTursoPlugin', () => { services[EMBEDDER_SERVICE] = new FakeEmbedder(32, 'late-model'); expect(adapter.embedding).toEqual({ dimensions: 32, model: 'late-model' }); }); + + it('hands vectorIndexThreshold to its adapter: a complete build at the threshold makes the approximate index', async () => { + const root = tempDir(); + const { ctx, adapters } = contextOf(); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, vectorIndexThreshold: 3, vectorIndexOverfetch: 2 }); + await plugin.start(ctx); + const adapter = adapters.get('turso')!; + const source = { name: 'notes', label: 'n', adapter: 'turso', source: { kind: 'object', object: 'o', content: ['b'] } } as never; + const build = { source, reason: 'manual', index: { fingerprint: 'fp:1', recipeHash: 'rh:1' } } as never; + await adapter.beginBuild!(build); + await adapter.upsert(['oak table', 'pine chair', 'elm desk'].map((content, i) => ({ id: `d${i}`, sourceId: 'notes', content })), build); + await adapter.completeBuild!(build); + const { createClient } = await import('@libsql/client'); + const probe = createClient({ url: `file:${join(root, '.objectstack', 'data', 'knowledge.db')}` }); + expect((await probe.execute("SELECT name FROM sqlite_master WHERE name = 'knowledge_notes_g1$vec'")).rows).toHaveLength(1); + probe.close(); + await plugin.destroy(); + }); }); /** diff --git a/packages/plugins/knowledge-turso/src/index.ts b/packages/plugins/knowledge-turso/src/index.ts index 8bc16c8610a..9b1b1a58dc6 100644 --- a/packages/plugins/knowledge-turso/src/index.ts +++ b/packages/plugins/knowledge-turso/src/index.ts @@ -3,6 +3,8 @@ export { KNOWLEDGE_REBUILD_REQUIRED, TursoKnowledgeAdapter, + VECTOR_INDEX_OVERFETCH, + VECTOR_INDEX_THRESHOLD, type TursoKnowledgeAdapterOptions, } from './turso-adapter.js'; export { diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index c6fefe25ea4..de197ba0958 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -58,6 +58,14 @@ export interface KnowledgeTursoPluginOptions { requestTimeoutMs?: number; /** Text put before every query before it is embedded (see the adapter's option). */ queryPrefix?: string; + /** + * The passage count at or above which a complete build makes a source's + * approximate vector index (see the adapter's option); `Infinity` never + * makes one. @default 20000 + */ + vectorIndexThreshold?: number; + /** How many approximate-index candidates the vector leg reads per hit (see the adapter's option). @default 4 */ + vectorIndexOverfetch?: number; /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ embedder?: IEmbedder; /** @@ -531,6 +539,8 @@ export class KnowledgeTursoPlugin implements Plugin { ...(store.client ? { client: store.client } : { unavailable: store.unavailable }), embedder, queryPrefix: this.opts.queryPrefix, + ...(this.opts.vectorIndexThreshold === undefined ? {} : { vectorIndexThreshold: this.opts.vectorIndexThreshold }), + ...(this.opts.vectorIndexOverfetch === undefined ? {} : { vectorIndexOverfetch: this.opts.vectorIndexOverfetch }), ...(store.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: store.requestTimeoutMs }), }); } diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 44cf2f16c41..526ea29639b 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -243,8 +243,13 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise Date: Fri, 27 Nov 2026 20:45:42 +0000 Subject: [PATCH 04/15] chore(knowledge-turso): changeset for the approximate vector index Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/knowledge-turso-approximate-index.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .changeset/knowledge-turso-approximate-index.md diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md new file mode 100644 index 00000000000..3e22e4422ab --- /dev/null +++ b/.changeset/knowledge-turso-approximate-index.md @@ -0,0 +1,15 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +feat(knowledge-turso): an approximate vector index for a large source of one organization + +Clause-②: yes (widening) +Metadata-protocol: none + +Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's DiskANN index (`vector_top_k`, one-bit neighbours, at most 32 each). The vector leg then reads `topK × vectorIndexOverfetch` candidates (default 4, at most 200), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. + +- **Never over two organizations.** The index ranks before it filters, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. +- **Built at the end of a complete build, never on a search or a write.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The index is made empty, then filled 128 passages to a transaction before the generation is switched to; a search waits at most one batch. A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes the index. +- **Names.** `knowledge__g-vec` (the side table of float8 vectors), `…$vec` (the DiskANN index, kept by libSQL in `…$vec_shadow`), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. +- **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch`. Nothing to migrate: a store keeps the exact scan until its next complete build. From 09b0571582e2147854d9b1cfcac4f49a76a61db9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:08:02 +0000 Subject: [PATCH 05/15] docs(knowledge-turso): name the recall of the index settings on unstructured vectors Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/plugins/knowledge-turso/src/sql.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index f8c6a7a0f2c..9e47eea1847 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -281,10 +281,12 @@ export function vectorIndexNames(table: string): { /** * The settings of the DiskANN index, measured at 1,536 dimensions on 5,000 * clustered vectors: neighbours compressed to one bit and at most 32 of them - * cost about 3 ms a vector to insert and about 11 KB a vector on disk, with a - * recall@10 of 0.998 against the exact scan; float8 neighbours cost three times - * the time and size for no measured recall gain. Libsql's defaults (float32 - * neighbours) took 329 MB and 21.8 s for 1,000 vectors. + * cost about 3 ms a vector to insert and about 11 KB a vector on disk (with + * the float8 side table), with a recall@10 of 0.998 against the exact scan; + * float8 neighbours cost three times the time and size for no recall gain on + * clustered vectors (on unstructured random vectors both fall short: 0.94 and + * 0.75). libSQL's defaults (float32 neighbours) took 329 MB and 21.8 s for + * 1,000 vectors. */ export const VECTOR_INDEX_SETTINGS = `'metric=cosine', 'compress_neighbors=float1bit', 'max_neighbors=32'`; From ceb6c4c4778ad0413de93259c859b2125c7c48fb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:34:05 +0000 Subject: [PATCH 06/15] feat(knowledge-turso): rank the candidates by one-bit vectors instead of libSQL's DiskANN index DiskANN measured a recall@10 of 0.39 at 200,000 clustered passages and took 24 minutes and 2.2 GB to build; a one-bit side table scanned whole and re-ranked by the float32 vectors measured 0.99, 3 s and 54 MB. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso-approximate-index.md | 8 +- content/docs/ai/knowledge-rag.mdx | 2 +- content/docs/protocol/knowledge.mdx | 21 +++-- packages/plugins/knowledge-turso/README.md | 12 +-- .../src/__tests__/acceptance.test.ts | 27 +++--- .../src/__tests__/plugin.test.ts | 2 +- .../plugins/knowledge-turso/src/plugin.ts | 2 +- packages/plugins/knowledge-turso/src/sql.ts | 90 +++++++------------ .../knowledge-turso/src/turso-adapter.ts | 59 ++++++------ 9 files changed, 105 insertions(+), 118 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index 3e22e4422ab..6a79e6632ed 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -7,9 +7,9 @@ feat(knowledge-turso): an approximate vector index for a large source of one org Clause-②: yes (widening) Metadata-protocol: none -Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's DiskANN index (`vector_top_k`, one-bit neighbours, at most 32 each). The vector leg then reads `topK × vectorIndexOverfetch` candidates (default 4, at most 200), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. +Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. TBD_CHANGESET -- **Never over two organizations.** The index ranks before it filters, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. -- **Built at the end of a complete build, never on a search or a write.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The index is made empty, then filled 128 passages to a transaction before the generation is switched to; a search waits at most one batch. A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes the index. -- **Names.** `knowledge__g-vec` (the side table of float8 vectors), `…$vec` (the DiskANN index, kept by libSQL in `…$vec_shadow`), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. +- **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. +- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. +- **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. - **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch`. Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 10371cd536c..10f71a3ed0a 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -371,7 +371,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds — new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL ``` -- It searches with two legs merged by reciprocal rank fusion: a cosine ranking, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs. The cosine ranking is an exact scan — 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms — until a complete build finds a source of 20,000 passages or more (`vectorIndexThreshold`), all of one organization: that source gets libSQL's approximate (DiskANN) index, whose candidates are filtered after it ranks, never over two organizations. TBD_RAG Larger sources shared by many organizations belong on pgvector. +- It searches with two legs merged by reciprocal rank fusion: a cosine ranking, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs. The cosine ranking is an exact scan — 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms — until a complete build finds a source of 20,000 passages or more (`vectorIndexThreshold`), all of one organization: that source gets an approximate index of one-bit vectors, whose nearest candidates are filtered and re-ranked by the stored vector, never over two organizations. TBD_RAG Larger sources shared by many organizations belong on pgvector. - A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes. - Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index d1adf865d68..dfaa700e6c3 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -739,16 +739,21 @@ large source of one organization, through an approximate index. 5 ms; 10,000 take 82 MB and about 50 ms. - **Approximate index.** A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one - organization, makes its DiskANN index (`vector_top_k`), copied in 128 rows to - a transaction before the switch, never on a search. The vector leg then - reads `topK × vectorIndexOverfetch` candidates (default 4, at most 200), - runs the same `WHERE` over them, ranks those in scope by their stored + organization, makes its approximate index: each passage's vector quantized + to one bit a dimension, in a side table kept in step by triggers, copied in + 2,048 rows to a transaction before the switch, never on a search (200,000 + passages: 3 s, 54 MB). The vector leg then takes the + `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a + hit), runs the same `WHERE` over them, ranks those in scope by their stored vector, and feeds the fusion as the exact leg does; a leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers - fewer hits than the exact scan. The index ranks before it filters, so it is - never made, or used, over the passages of two organizations (passages of - none count as one): each search reads the organization index and takes the - exact scan once a second organization's passage is written. TBD_DOCS + fewer hits than the exact scan. The candidates are ranked before the + filter, so the index is never made, or used, over the passages of two + organizations (passages of none count as one): each search reads the + organization index and takes the exact scan once a second organization's + passage is written. TBD_DOCS libSQL's own DiskANN index (`vector_top_k`) + is not used: on the same 200,000 passages it took 24 minutes and 2.2 GB to + build and answered a recall@10 of 0.39. - **Rebuilds.** A changed fingerprint is refused (§3.6). A complete reindex under a new fingerprint builds a new generation table beside the active one, which keeps answering its own fingerprint, and switches at the end of diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index b6b2eded0f2..7fb5147666c 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -31,7 +31,7 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts | `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | | `vectorIndexThreshold` | `20000` | The passage count at or above which a complete build makes a source's approximate vector index ([Search](#search)). `Infinity` never makes one. | -| `vectorIndexOverfetch` | `4` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 1 or more. | +| `vectorIndexOverfetch` | `40` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 1 or more. | ## Its own file, never the platform's @@ -43,7 +43,7 @@ On a file the store sets WAL and a busy timeout: without them a second process w - `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints. - `knowledge__g` — the passages of one generation of one source, with an `F32_BLOB()` vector column sized for that generation. -- `knowledge__g-vec`, `…$vec`, `…-org` — a large source's approximate vector index ([Search](#search)), when it has one: a side table of the passages' vectors in float8, libSQL's DiskANN index on it (libSQL keeps it in `…$vec_shadow`), an index of the passage table's organization column, and three triggers that keep the side table in step. Dropped with the passage table, by a generation switch and by `dropSource`; an object under one of those names that the store did not make is never dropped or used, and the call is refused `SERVICE_UNAVAILABLE`, naming it. +- `knowledge__g-vec`, `…-org` — a large source's approximate vector index ([Search](#search)), when it has one: a side table of the passages' vectors quantized to one bit a dimension (`F1BIT_BLOB`, 192 bytes at 1,536 dimensions), an index of the passage table's organization column, and three triggers that keep the side table in step with every write. Dropped with the passage table, by a generation switch and by `dropSource`; an object under one of those names that the store did not make is never dropped or used, and the call is refused `SERVICE_UNAVAILABLE`, naming it. `` is the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two tables). When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: the source's generation tables and rows are dropped in one transaction. A table the store did not make under one of those names (an object's table, in a database shared with object tables) is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming the table, and nothing of the source is removed. @@ -58,9 +58,11 @@ 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 DiskANN index (`vector_top_k`; one-bit neighbours, at most 32 each). Its vector leg then reads `topK × vectorIndexOverfetch` candidates from the index (at most 200, the most `vector_top_k` answers), runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The index ranks before it filters, so a leg the filter leaves with fewer than `topK` candidates is run again as the exact scan: a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there". TBD_MEASURED -- **When it is built.** At the end of a complete build, never on a search or a record write: the index is made empty in one transaction, then the passage table's rows are copied in, 128 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). A search waits at most one batch. Every write after that pays the index's insert, about TBD_INSERT ms a passage. 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. -- **Never over two organizations.** Over two organizations' passages, the index's candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the index ranks, not on the whole database; on a hosted database, which holds one organization (cloud ADR-0114), it always holds. +- **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 `topK` is run again as the exact scan: 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): TBD_MEASURED +- **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. +- **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). +- **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. For a source of hundreds of thousands of passages shared by many organizations, use `@objectstack/knowledge-pgvector`. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 24b2056b46e..6c6e32de0c7 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -878,8 +878,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { /** * A client whose every statement's SQL is recorded, the transaction's too, so - * a test reads which path a search took: the approximate vector leg names - * `vector_top_k`, the exact one does not. + * a test reads which path a search took: the approximate vector leg ranks + * the one-bit side table (`vector1bit`), the exact one does not. */ function recording(client: Client): { client: Client; sql: string[] } { const sql: string[] = []; @@ -904,13 +904,13 @@ function recording(client: Client): { client: Client; sql: string[] } { /** The vector legs of the searches recorded since `from`: how many were approximate, how many exact. */ function vectorLegs(sql: string[], from = 0): { approximate: number; exact: number } { const legs = sql.slice(from).filter((s) => s.includes('vec AS (')); - const approximate = legs.filter((s) => s.includes('vector_top_k(')).length; + const approximate = legs.filter((s) => s.includes('vector1bit(')).length; return { approximate, exact: legs.length - approximate }; } -/** The vector-index objects (side table, DiskANN index and its shadow, organization index, triggers) of a passage table. */ +/** The vector-index objects (side table, organization index, triggers) of a passage table. */ async function vectorObjects(client: Client, table: string): Promise { - const names = [`${table}-vec`, `${table}$vec`, `${table}$vec_shadow`, `${table}-org`, `${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`]; + const names = [`${table}-vec`, `${table}-org`, `${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`]; const found = await client.execute({ sql: `SELECT name FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')}) ORDER BY name`, args: names, @@ -956,10 +956,10 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const corpus = (s: KnowledgeSource, n: number, extra: (i: number) => Partial = () => ({})) => wordsOf(n, 7).map((text, i) => doc(s, String(i).padStart(3, '0'), text, extra(i))); - it('a source at or above the threshold is searched through vector_top_k; below it, or at Infinity, by the exact scan', async () => { + it('a source at or above the threshold is searched through its approximate index; below it, or at Infinity, by the exact scan', async () => { const s = source('ann_switch'); const above = await built(s, corpus(s, 60)); - expect(await vectorObjects(above.client, `knowledge_${s.name}_g1`)).toHaveLength(7); + expect(await vectorObjects(above.client, `knowledge_${s.name}_g1`)).toHaveLength(5); const from = above.sql.length; const hits = await above.adapter.search('w1x w2x w3x', { source: s, topK: 5, index: { fingerprint: FP_A.fingerprint } }); expect(hits).toHaveLength(5); @@ -1011,7 +1011,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ...Array.from({ length: 56 }, (_, i) => doc(s, `near_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 9) + 5}x`)), ...['a', 'b', 'c', 'd'].map((n) => doc(s, `far_${n}`, `w1x wqx wrx ws${n}x`, { metadata: { status: 'draft' } })), ]; - const { adapter, sql } = await built(s, docs); + // Four candidates a hit, so the candidates are not every row of this small table. + const { adapter, sql } = await built(s, docs, { vectorIndexOverfetch: 4 }); // A filter only the far passages pass: none is among the candidates, so the exact scan answers. let from = sql.length; const drafts = await adapter.search(QUERY, { source: s, topK: 3, filter: { status: 'draft' } }); @@ -1026,7 +1027,7 @@ 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); + const over = await built(t, tiers, { vectorIndexOverfetch: 4 }); from = over.sql.length; const scoped = ['second_1', 'second_4']; const inScope = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: scoped }] }); @@ -1057,7 +1058,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.completeBuild(ctx(s, FP_B)); const g2 = `knowledge_${s.name}_g2`; expect(await vectorObjects(client, g1)).toEqual([]); - expect(await vectorObjects(client, g2)).toHaveLength(7); + expect(await vectorObjects(client, g2)).toHaveLength(5); expect(await counts(g2)).toMatchObject({ n: 60, v: 60 }); from = sql.length; await adapter.search('w1x w2x', { source: s, topK: 5, index: { fingerprint: FP_B.fingerprint } }); @@ -1065,7 +1066,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.dropSource(ctx(s, FP_B)); expect(await vectorObjects(client, g2)).toEqual([]); - const left = await client.execute("SELECT name FROM sqlite_master WHERE name LIKE '%$vec%' OR name LIKE '%-vec%'"); + const left = await client.execute("SELECT name FROM sqlite_master WHERE name LIKE '%-vec%' OR name LIKE '%-org'"); expect(left.rows).toEqual([]); }); @@ -1079,7 +1080,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.beginBuild(ctx(s)); await adapter.upsert(corpus(s, 60), ctx(s)); await adapter.completeBuild(ctx(s)); - expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toHaveLength(7); + expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toHaveLength(5); const from = watched.sql.length; await adapter.search('w1x w2x', { source: s, topK: 5 }); expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 1, exact: 0 }); @@ -1120,7 +1121,7 @@ describe('knowledge-turso approximate vector index: recall and options', () => { it('recall@10 of the approximate search against the exact-scan search is 0.95 or more on a sample of 40 queries', async () => { const s = source('ann_recall'); - const docs = wordsOf(600, 3).map((text, i) => doc(s, String(i).padStart(3, '0'), text)); + const docs = wordsOf(2000, 3).map((text, i) => doc(s, String(i).padStart(3, '0'), text)); const make = async (vectorIndexThreshold: number) => { const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder: new FakeEmbedder(), vectorIndexThreshold }); await adapter.beginBuild(ctx(s)); diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 37c2b4d0092..032967d0225 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -221,7 +221,7 @@ describe('KnowledgeTursoPlugin', () => { await adapter.completeBuild!(build); const { createClient } = await import('@libsql/client'); const probe = createClient({ url: `file:${join(root, '.objectstack', 'data', 'knowledge.db')}` }); - expect((await probe.execute("SELECT name FROM sqlite_master WHERE name = 'knowledge_notes_g1$vec'")).rows).toHaveLength(1); + expect((await probe.execute("SELECT name FROM sqlite_master WHERE name = 'knowledge_notes_g1-vec'")).rows).toHaveLength(1); probe.close(); await plugin.destroy(); }); diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index de197ba0958..c33e8cc2c58 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -64,7 +64,7 @@ export interface KnowledgeTursoPluginOptions { * makes one. @default 20000 */ vectorIndexThreshold?: number; - /** How many approximate-index candidates the vector leg reads per hit (see the adapter's option). @default 4 */ + /** How many approximate-index candidates the vector leg reads per hit (see the adapter's option). @default 40 */ vectorIndexOverfetch?: number; /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ embedder?: IEmbedder; diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index 9e47eea1847..de8dc32ea81 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -254,67 +254,49 @@ export function keywordIndexShape( /** * The names of a passage table's approximate vector index: a side table - * (`
-vec`: an integer key, the chunk id, and the passage's vector in - * float8), libSQL's DiskANN index on it (`
$vec`, which libSQL keeps in - * a shadow table `
$vec_shadow`), an index of the passage table's - * organization column (`
-org`), and the three triggers that keep the - * side table in step with every write to the passage table. A DiskANN index - * name cannot hold a hyphen, so it holds a `$`, which no source id, generation - * table or object name can hold either; the other names hold a hyphen. + * (`
-vec`: the chunk id and the passage's vector quantized to one bit + * a dimension), an index of the passage table's organization column + * (`
-org`), and the three triggers that keep the side table in step + * with every write to the passage table. Each name holds a hyphen, which no + * source id, generation table or object name can hold. */ export function vectorIndexNames(table: string): { side: string; - index: string; - shadow: string; org: string; triggers: [string, string, string]; } { return { side: `${table}-vec`, - index: `${table}$vec`, - shadow: `${table}$vec_shadow`, org: `${table}-org`, triggers: [`${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`], }; } /** - * The settings of the DiskANN index, measured at 1,536 dimensions on 5,000 - * clustered vectors: neighbours compressed to one bit and at most 32 of them - * cost about 3 ms a vector to insert and about 11 KB a vector on disk (with - * the float8 side table), with a recall@10 of 0.998 against the exact scan; - * float8 neighbours cost three times the time and size for no recall gain on - * clustered vectors (on unstructured random vectors both fall short: 0.94 and - * 0.75). libSQL's defaults (float32 neighbours) took 329 MB and 21.8 s for - * 1,000 vectors. - */ -export const VECTOR_INDEX_SETTINGS = `'metric=cosine', 'compress_neighbors=float1bit', 'max_neighbors=32'`; - -/** - * The statements that make a passage table's approximate vector index ({@link - * vectorIndexNames}), empty: the side table and its DiskANN index, the - * organization index of the passage table, and the triggers. The rows the - * passage table already holds are copied in afterwards, a batch at a time - * ({@link vectorBackfillSql}); the triggers, made first, keep every row - * written meanwhile in step, so the side table holds a subset of the passage - * table's chunks at every moment, and all of them once the copy ends. + * The statements that make a passage table's approximate vector index + * ({@link vectorIndexNames}), empty: the side table of one-bit vectors + * (`F1BIT_BLOB`, `vector1bit`: 192 bytes at 1,536 dimensions, a 32nd of the + * float32 vector), the organization index of the passage table, and the + * triggers. The rows the passage table already holds are copied in + * afterwards, a batch at a time ({@link vectorBackfillSql}); the triggers, + * made first, keep every row written meanwhile in step, so the side table + * holds a subset of the passage table's chunks at every moment, and all of + * them once the copy ends. The organization index, when it is there alone + * (made for a table found to hold more than one organization), is kept. */ export function vectorIndexDdl(table: string, dimensions: number): string[] { if (!Number.isInteger(dimensions) || dimensions < 1) { throw new RangeError(`knowledge-turso: vector dimensions must be a positive integer, got ${String(dimensions)}`); } - const { side, index, org, triggers } = vectorIndexNames(table); + const { side, org, triggers } = vectorIndexNames(table); const t = quoted(table); const s = quoted(side); return [ - // The organization index is kept: it may be there alone (made for a - // table found to hold more than one organization), and serves as it is. ...dropVectorIndexDdl(table).filter((statement) => !statement.includes(quoted(org))), - `CREATE TABLE ${s} (id INTEGER PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE, embedding F8_BLOB(${dimensions}) NOT NULL)`, - `CREATE INDEX ${quoted(index)} ON ${s} (libsql_vector_idx(embedding, ${VECTOR_INDEX_SETTINGS}))`, + `CREATE TABLE ${s} (chunk_id TEXT NOT NULL PRIMARY KEY, embedding F1BIT_BLOB(${dimensions}) NOT NULL)`, organizationIndexDdl(table), `CREATE TRIGGER ${quoted(triggers[0])} AFTER INSERT ON ${t} BEGIN - INSERT INTO ${s} (chunk_id, embedding) VALUES (new.chunk_id, vector8(new.embedding)) + INSERT INTO ${s} (chunk_id, embedding) VALUES (new.chunk_id, vector1bit(new.embedding)) ON CONFLICT (chunk_id) DO UPDATE SET embedding = excluded.embedding; END`, `CREATE TRIGGER ${quoted(triggers[1])} AFTER DELETE ON ${t} BEGIN @@ -322,7 +304,7 @@ END`, END`, `CREATE TRIGGER ${quoted(triggers[2])} AFTER UPDATE OF chunk_id, embedding ON ${t} WHEN old.chunk_id IS NOT new.chunk_id OR old.embedding IS NOT new.embedding BEGIN - UPDATE ${s} SET chunk_id = new.chunk_id, embedding = vector8(new.embedding) WHERE chunk_id = old.chunk_id; + UPDATE ${s} SET chunk_id = new.chunk_id, embedding = vector1bit(new.embedding) WHERE chunk_id = old.chunk_id; END`, ]; } @@ -344,18 +326,17 @@ export function vectorBackfillSql(table: string): { last: string; copy: string } last: `SELECT max(chunk_id) AS last FROM (SELECT chunk_id FROM ${t} WHERE chunk_id > ?1 ORDER BY chunk_id LIMIT ?2)`, copy: `INSERT INTO ${quoted(vectorIndexNames(table).side)} (chunk_id, embedding) ` + - `SELECT chunk_id, vector8(embedding) FROM ${t} WHERE chunk_id > ?1 AND chunk_id <= ?2 ORDER BY chunk_id ` + + `SELECT chunk_id, vector1bit(embedding) FROM ${t} WHERE chunk_id > ?1 AND chunk_id <= ?2 ORDER BY chunk_id ` + 'ON CONFLICT (chunk_id) DO NOTHING', }; } -/** The statements that drop a passage table's vector index; libSQL drops the DiskANN index and its shadow with the side table. */ +/** The statements that drop a passage table's vector index. */ export function dropVectorIndexDdl(table: string): string[] { - const { side, index, org, triggers } = vectorIndexNames(table); + const { side, org, triggers } = vectorIndexNames(table); return [ ...triggers.map((name) => `DROP TRIGGER IF EXISTS ${quoted(name)}`), `DROP INDEX IF EXISTS ${quoted(org)}`, - `DROP INDEX IF EXISTS ${quoted(index)}`, `DROP TABLE IF EXISTS ${quoted(side)}`, ]; } @@ -366,35 +347,32 @@ export type VectorIndexShape = 'none' | 'complete' | 'partial' | 'other'; /** * Reads the shape of a passage table's vector index, as {@link * keywordIndexShape} reads its keyword index: `complete` when the side table - * (exactly its three columns), its DiskANN index, the organization index and - * the three triggers are all there and are this module's; `none` when nothing + * (exactly its two columns, a one-bit vector), the organization index and the + * three triggers are all there and are this module's; `none` when nothing * is; `partial` when only some are; `other` when an object under one of those - * names (or the DiskANN shadow's) is not this module's — never dropped or used. - * `complete` says the structure is there, not that every row was copied in. + * names is not this module's — never dropped or used. `complete` says the + * structure is there, not that every row was copied in. */ export function vectorIndexShape( table: string, rows: ReadonlyArray>, sideColumns: ReadonlyArray>, ): VectorIndexShape { - const { side, index, shadow, org, triggers } = vectorIndexNames(table); - const byName = new Map( - rows.map((r) => [String(r.name), { type: String(r.type), on: String(r.tbl_name), sql: String(r.sql ?? '') }]), - ); - const own = [side, index, org, ...triggers]; + const { side, org, triggers } = vectorIndexNames(table); + const byName = new Map(rows.map((r) => [String(r.name), { type: String(r.type), on: String(r.tbl_name) }])); + const own = [side, org, ...triggers]; const found = own.filter((n) => byName.has(n)); - if (found.length === 0 && !byName.has(shadow)) return 'none'; + if (found.length === 0) return 'none'; const is = (name: string, type: string, on: string) => !byName.has(name) || (byName.get(name)!.type === type && byName.get(name)!.on === on); + const columns = new Map(sideColumns.map((c) => [String(c.name), String(c.type).replace(/\s+/g, '')])); const sideOk = is(side, 'table', side) && - (!byName.has(side) || sideColumns.map((c) => String(c.name)).sort().join(',') === 'chunk_id,embedding,id'); - const indexOk = is(index, 'index', side) && (!byName.has(index) || /libsql_vector_idx\s*\(/i.test(byName.get(index)!.sql)); - // The shadow is libSQL's, made with the DiskANN index and dropped with it. - const shadowOk = !byName.has(shadow) || (byName.has(index) && byName.get(shadow)!.type === 'table'); + (!byName.has(side) || + (columns.size === 2 && columns.has('chunk_id') && /^F1BIT_BLOB\(\d+\)$/i.test(columns.get('embedding') ?? ''))); const orgOk = is(org, 'index', table); const triggersOk = triggers.every((n) => is(n, 'trigger', table)); - if (!sideOk || !indexOk || !shadowOk || !orgOk || !triggersOk) return 'other'; + if (!sideOk || !orgOk || !triggersOk) return 'other'; return found.length === own.length ? 'complete' : 'partial'; } diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 526ea29639b..e9848e955c0 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -83,9 +83,10 @@ export interface TursoKnowledgeAdapterOptions { requestTimeoutMs?: number; /** * The passage count at or above which a complete build of a source makes - * its approximate vector index (libSQL's DiskANN, `vector_top_k`), so its - * vector leg reads `topK × vectorIndexOverfetch` candidates instead of - * every vector. Counted when the build completes, on the generation it + * its approximate vector index (a side table of one-bit vectors, a 32nd of + * the float32 ones), so its vector leg ranks `topK × vectorIndexOverfetch` + * candidates by that index and reads the float32 vector of those alone, + * instead of every one. Counted when the build completes, on the generation it * completes; `Infinity` never makes one. A source whose passage table holds * more than one organization never gets one, and is never searched through * one. @default 20000 @@ -96,7 +97,7 @@ export interface TursoKnowledgeAdapterOptions { * index before the organization, record-scope and metadata filter run: the * index ranks before the filter, so a filter that removes candidates is * answered from what is left, and a leg left with fewer than `topK` is run - * again as the exact scan. A whole number, 1 or more. @default 4 + * again as the exact scan. A whole number, 1 or more. @default 40 */ vectorIndexOverfetch?: number; } @@ -104,18 +105,17 @@ export interface TursoKnowledgeAdapterOptions { /** The passage count at or above which a complete build makes a source's approximate vector index. */ export const VECTOR_INDEX_THRESHOLD = 20_000; -/** How many approximate-index candidates the vector leg reads per hit it ranks. */ -export const VECTOR_INDEX_OVERFETCH = 4; - /** - * The most candidates libSQL's `vector_top_k` answers on one call, measured - * (a larger `k` answers this many); a vector leg that needs more takes the - * exact scan. + * How many approximate-index candidates the vector leg reads per hit it + * ranks. Measured at 200,000 passages of 1,536 dimensions (clustered, topK + * 10): 10 candidates a hit gave a recall@10 of 0.90 against the exact scan, + * 40 gave 0.99, 100 gave 1.00, at about the same cost — the one-bit scan + * reads every row either way. */ -export const VECTOR_TOP_K_MAX = 200; +export const VECTOR_INDEX_OVERFETCH = 40; /** 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 = 128; +const VECTOR_BACKFILL_BATCH = 2048; /** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; @@ -247,9 +247,10 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise { const near = approximate - ? ` AND chunk_id IN (SELECT s.chunk_id FROM vector_top_k('${vectorIndex.index}', vector8(?1), ${candidates}) AS a - JOIN ${quoted(vectorIndex.side)} s ON s.id = a.id)` + ? ` AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} + ORDER BY vector_distance_cos(embedding, vector1bit(?1)) LIMIT ${candidates})` : ''; return `vec AS ( SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM ( @@ -720,7 +721,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const now = await this.generations(opts.source.name); if (now.active?.generation !== active.generation) return undefined; if (terms.length > 0) await this.ensureKeywordIndex(tableName); - if (vectorLeg && topK <= VECTOR_TOP_K_MAX && (await this.approximateSearchable(tableName))) { + if (vectorLeg && (await this.approximateSearchable(tableName))) { const near = await client.execute(statement(true)); // A vector leg the filter left with fewer than topK candidates is // run again as the exact scan: an answer of fewer than topK says the @@ -1034,13 +1035,13 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { /** The shape of the vector index of the passage table `table` (`vectorIndexShape`). */ private async vectorShapeOf(db: Pick, table: string): Promise { - const { side, index, shadow, org, triggers } = vectorIndexNames(table); - const names = [side, index, shadow, org, ...triggers]; + const { side, org, triggers } = vectorIndexNames(table); + const names = [side, org, ...triggers]; const rows = await db.execute({ sql: `SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')})`, args: names, }); - const columns = await db.execute({ sql: 'SELECT name FROM pragma_table_info(?)', args: [side] }); + const columns = await db.execute({ sql: 'SELECT name, type FROM pragma_table_info(?)', args: [side] }); return vectorIndexShape(table, rows.rows, columns.rows); } @@ -1056,8 +1057,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { /** * Whether a search of the passage table `table` may rank its vector leg - * through the approximate index: its side table and DiskANN index are - * there and hold every passage of the table (once true, kept so by the + * through the approximate index: its side table and triggers are there and + * hold every passage of the table (once true, kept so by the * triggers, and remembered), and the table holds passages of one * organization at most — read at each search, from the organization index, * so a second organization written after the index was made turns the @@ -1395,10 +1396,10 @@ function switchedDuringSearch(diagnosis: string, detail: string): Error { /** The refusal of an object under a vector-index name of `table` that the store did not make. */ function vectorIndexNotOurs(table: string, sourceId: string, generation: number): Error { - const { side, index, org } = vectorIndexNames(table); + const { side, org } = vectorIndexNames(table); return notReady( `an object it did not make holds a name of the vector index of generation ${generation} of source '${sourceId}'`, - `The database holds a table, index or trigger under '${side}', '${index}', '${org}' or a '${table}-vec-*' trigger ` + + `The database holds a table, index or trigger under '${side}', '${org}' or a '${table}-vec-*' trigger ` + `that is not this store's vector index, so it is not dropped, and generation ${generation} of source ` + `'${sourceId}' cannot be built, replaced or removed. Rename or remove it, or keep the store in a database of its own.`, ); From 19841efaf20e4f76c7fde1b319243d216e402c66 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:44:49 +0000 Subject: [PATCH 07/15] docs(knowledge-turso): the measured latency and recall of the one-bit index at 200,000 passages Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/knowledge-turso-approximate-index.md | 2 +- content/docs/ai/knowledge-rag.mdx | 2 +- content/docs/protocol/knowledge.mdx | 4 +++- packages/plugins/knowledge-turso/README.md | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index 6a79e6632ed..cf7adb3160f 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -7,7 +7,7 @@ feat(knowledge-turso): an approximate vector index for a large source of one org Clause-②: yes (widening) Metadata-protocol: none -Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. TBD_CHANGESET +Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. - **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 10f71a3ed0a..849be4e411d 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -371,7 +371,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds — new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL ``` -- It searches with two legs merged by reciprocal rank fusion: a cosine ranking, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs. The cosine ranking is an exact scan — 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms — until a complete build finds a source of 20,000 passages or more (`vectorIndexThreshold`), all of one organization: that source gets an approximate index of one-bit vectors, whose nearest candidates are filtered and re-ranked by the stored vector, never over two organizations. TBD_RAG Larger sources shared by many organizations belong on pgvector. +- It searches with two legs merged by reciprocal rank fusion: a cosine ranking, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs. The cosine ranking is an exact scan — 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms — until a complete build finds a source of 20,000 passages or more (`vectorIndexThreshold`), all of one organization: that source gets an approximate index of one-bit vectors, whose nearest candidates are filtered and re-ranked by the stored vector, never over two organizations. At 200,000 passages a vector search took 81 ms at p95 instead of about a second, with a recall@10 of 0.998 against the exact scan. Larger sources shared by many organizations belong on pgvector. - A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes. - Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index dfaa700e6c3..095d51148e9 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -751,7 +751,9 @@ large source of one organization, through an approximate index. filter, so the index is never made, or used, over the passages of two organizations (passages of none count as one): each search reads the organization index and takes the exact scan once a second organization's - passage is written. TBD_DOCS libSQL's own DiskANN index (`vector_top_k`) + passage is written. At 200,000 passages of 1,536 + dimensions a search whose keyword leg matched nothing took 81 ms at p95 + (the exact scan 1,054 ms), with a recall@10 against the exact scan of 0.998. libSQL's own DiskANN index (`vector_top_k`) is not used: on the same 200,000 passages it took 24 minutes and 2.2 GB to build and answered a recall@10 of 0.39. - **Rebuilds.** A changed fingerprint is refused (§3.6). A complete reindex diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 7fb5147666c..b286cc35914 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -59,7 +59,7 @@ The organization filter, the record scope (a passage's record, or a metadata val - **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 `topK` is run again as the exact scan: 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): TBD_MEASURED +- **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. - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. From 4dbdd5bb3cc89e4d8b786a0d4a23c37f6d8ef713 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:36:50 +0000 Subject: [PATCH 08/15] fix(knowledge-turso): a thin in-scope pool and a refused one-bit DDL both keep the exact scan The approximate vector leg now answers only when at least 4 x topK of its candidates are in scope; a narrow record scope or filter runs the exact scan instead of re-ranking a thin pool. vectorIndexOverfetch is now a whole number of 4 or more to match. A database that refuses vector1bit or the side table's DDL gets no index: a probe runs before any DDL (a trigger naming an unknown function is created without complaint and then fails every write), a refused DDL transaction rolls back, a refused backfill batch ends the copy, and the build completes on the exact scan. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso-approximate-index.md | 6 +- content/docs/protocol/knowledge.mdx | 7 +- packages/plugins/knowledge-turso/README.md | 6 +- .../src/__tests__/acceptance.test.ts | 109 ++++++++++++++-- .../src/__tests__/plugin.test.ts | 2 +- .../plugins/knowledge-turso/src/plugin.ts | 2 +- .../knowledge-turso/src/turso-adapter.ts | 120 ++++++++++++------ 7 files changed, 196 insertions(+), 56 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index cf7adb3160f..a823f96be84 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -7,9 +7,9 @@ feat(knowledge-turso): an approximate vector index for a large source of one org Clause-②: yes (widening) Metadata-protocol: none -Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves short of `topK` runs again as the exact scan, so a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. +Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. -- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. +- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, and the build completes on the exact scan. - **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. -- **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch`. Nothing to migrate: a store keeps the exact scan until its next complete build. +- **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 4 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 095d51148e9..bd2934cc307 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -746,8 +746,11 @@ large source of one organization, through an approximate index. `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same `WHERE` over them, ranks those in scope by their stored vector, and feeds the fusion as the exact leg does; a leg the filter leaves - short of `topK` runs again as the exact scan, so a search never answers - fewer hits than the exact scan. The candidates are ranked before the + with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, + runs again as the exact scan, so a narrow scope keeps its recall and a + search never answers fewer hits than the exact scan. A database that + refuses the one-bit vectors or the index's DDL gets no index, and its + builds complete. The candidates are ranked before the filter, so the index is never made, or used, over the passages of two organizations (passages of none count as one): each search reads the organization index and takes the exact scan once a second organization's diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index b286cc35914..1471bb6b6f2 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -31,7 +31,7 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts | `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | | `vectorIndexThreshold` | `20000` | The passage count at or above which a complete build makes a source's approximate vector index ([Search](#search)). `Infinity` never makes one. | -| `vectorIndexOverfetch` | `40` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 1 or more. | +| `vectorIndexOverfetch` | `40` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 4 or more. | ## Its own file, never the platform's @@ -58,9 +58,9 @@ 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 `topK` is run again as the exact scan: 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 4 × `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: in a simulation 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` gave 0.98 or more at every share. 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. +- **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, and the source keeps the exact scan. - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 6c6e32de0c7..97b09222e38 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -901,6 +901,35 @@ function recording(client: Client): { client: Client; sql: string[] } { return { client: watch(client, true), sql }; } +/** + * A recorded client that refuses, as a database that does not know them + * would, the statements whose SQL matches `pattern`, the transaction's too. + */ +function refusing(watched: { client: Client; sql: string[] }, pattern: RegExp): { client: Client; sql: string[]; refused: string[] } { + const refused: string[] = []; + const sqlOf = (statement: unknown) => (typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + const guard = (target: T, onTransaction: boolean): T => + new Proxy(target, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key === 'execute') { + return async (statement: unknown, ...rest: unknown[]) => { + if (pattern.test(sqlOf(statement))) { + refused.push(sqlOf(statement)); + throw new Error(`SQL_PARSE_ERROR: refused by this database: ${pattern.source}`); + } + return fn(statement, ...rest); + }; + } + if (key === 'transaction' && onTransaction) return async (...a: unknown[]) => guard((await fn(...a)) as object, false); + return fn; + }, + }); + return { client: guard(watched.client, true), sql: watched.sql, refused }; +} + /** The vector legs of the searches recorded since `from`: how many were approximate, how many exact. */ function vectorLegs(sql: string[], from = 0): { approximate: number; exact: number } { const legs = sql.slice(from).filter((s) => s.includes('vec AS (')); @@ -1003,7 +1032,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(vectorLegs(mixed.sql, from)).toEqual({ approximate: 0, exact: 1 }); }); - it('the filter runs on the over-fetched candidates; a leg it leaves short of topK is run again exactly', async () => { + it('the filter runs on the over-fetched candidates; a leg it leaves under 4 × topK in scope is run again exactly', async () => { const s = source('ann_scope'); const QUERY = 'w1x w2x w3x w4x'; // 56 passages near the query, published; 4 far from it, drafts. @@ -1019,20 +1048,27 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(drafts).toHaveLength(3); for (const hit of drafts) expect(hit.metadata).toMatchObject({ status: 'draft' }); expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); - // A record scope of passages ranked 3rd to 8th: the first two candidates are out of scope, and the - // over-fetch (2 × 4 candidates) still fills topK in scope, without the exact scan. const t = source('ann_overfetch'); const tiers = [ ...['best_1', 'best_2'].map((n) => doc(t, n, QUERY)), ...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: 4 }); + 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, 4 × topK + // and more, so the candidates answer, without the exact scan. from = over.sql.length; - const scoped = ['second_1', 'second_4']; - const inScope = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: scoped }] }); - expect(inScope.map((h) => h.sourceRecordId).sort()).toEqual(scoped); + const allButBest = tiers.map((d) => d.sourceRecordId).filter((id) => !id.startsWith('best_')); + const wide = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: allButBest }] }); + expect(wide).toHaveLength(2); + for (const hit of wide) expect(hit.sourceRecordId).toMatch(/^second_/); expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 0 }); + // Two passages in scope: at most 2 of the 20 candidates, fewer than 4 × topK, so the exact scan answers. + 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 }); }); it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => { @@ -1086,6 +1122,28 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 1, exact: 0 }); }); + it('a database that refuses the one-bit vectors or the index DDL keeps the exact scan, and the build completes', async () => { + // A host whose libSQL lacks the one-bit type: every statement naming it is refused. + for (const [name, refused] of [ + ['ann_no_1bit', /vector1bit\(|F1BIT_BLOB/], + ['ann_no_ddl', /F1BIT_BLOB/], + ] as const) { + const s = source(name); + const watched = refusing(recording(store.client()), refused); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold: THRESHOLD }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(corpus(s, 60), ctx(s)); + await adapter.completeBuild(ctx(s)); + expect(watched.refused.length).toBeGreaterThan(0); + expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toEqual([]); + // The build switched to its generation, and writes and searches go on through the exact scan. + await adapter.upsert([doc(s, 'late', 'wzzx wyyx wxxx')], ctx(s)); + const from = watched.sql.length; + expect((await adapter.search('wzzx wyyx wxxx', { source: s, topK: 1 })).map((h) => h.sourceRecordId)).toEqual(['late']); + expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 0, exact: 1 }); + } + }); + it('an object it did not make under a vector-index name is never dropped; the build and dropSource are refused', async () => { const s = source('ann_taken'); const watched = recording(store.client()); @@ -1143,12 +1201,43 @@ describe('knowledge-turso approximate vector index: recall and options', () => { expect(found / wanted).toBeGreaterThanOrEqual(0.95); }); - it('refuses a threshold below 1 and an over-fetch that is not a whole number of 1 or more', () => { + it('recall@10 stays 0.95 or more under a record scope that keeps 10%, 5% or 3% of the passages', async () => { + const s = source('ann_scoped_recall'); + const docs = wordsOf(2000, 5).map((text, i) => doc(s, String(i).padStart(4, '0'), text)); + const make = async (vectorIndexThreshold: number) => { + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: store.client(), embedder: new FakeEmbedder(), vectorIndexThreshold }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return adapter; + }; + const approximate = await make(100); + const exact = await make(Infinity); + let x = 17; + const next = () => ((x = (x * 1103515245 + 12345) % 2147483648) / 2147483648); + for (const share of [0.1, 0.05, 0.03]) { + const ids = docs.map((d) => d.sourceRecordId).filter(() => next() < share); + const scope = [{ kind: 'record' as const, ids }]; + let found = 0; + let wanted = 0; + for (const query of wordsOf(30, 31)) { + const want = (await exact.search(query, { source: s, topK: 10, scope })).map((h) => h.chunkId); + const got = new Set((await approximate.search(query, { source: s, topK: 10, scope })).map((h) => h.chunkId)); + wanted += want.length; + found += want.filter((id) => got.has(id)).length; + } + expect(wanted, `hits wanted at a share of ${share}`).toBeGreaterThan(200); + console.info(`scoped recall@10, ${share * 100}% in scope (${ids.length} passages): ${(found / wanted).toFixed(3)}`); + expect(found / wanted, `recall@10 at a share of ${share}`).toBeGreaterThanOrEqual(0.95); + } + }); + + it('refuses a threshold below 1 and an over-fetch that is not a whole number of 4 or more', () => { const client = store.client(); const embedder = new FakeEmbedder(); - for (const bad of [{ vectorIndexThreshold: 0 }, { vectorIndexThreshold: Number.NaN }, { vectorIndexOverfetch: 0 }, { vectorIndexOverfetch: 1.5 }]) { + for (const bad of [{ vectorIndexThreshold: 0 }, { vectorIndexThreshold: Number.NaN }, { vectorIndexOverfetch: 3 }, { vectorIndexOverfetch: 4.5 }]) { expect(() => new TursoKnowledgeAdapter({ client, embedder, ...bad })).toThrow(RangeError); } - expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 1 })).not.toThrow(); + expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 4 })).not.toThrow(); }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 032967d0225..17b9ead0bb2 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -211,7 +211,7 @@ describe('KnowledgeTursoPlugin', () => { it('hands vectorIndexThreshold to its adapter: a complete build at the threshold makes the approximate index', async () => { const root = tempDir(); const { ctx, adapters } = contextOf(); - const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, vectorIndexThreshold: 3, vectorIndexOverfetch: 2 }); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, vectorIndexThreshold: 3, vectorIndexOverfetch: 5 }); await plugin.start(ctx); const adapter = adapters.get('turso')!; const source = { name: 'notes', label: 'n', adapter: 'turso', source: { kind: 'object', object: 'o', content: ['b'] } } as never; diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index c33e8cc2c58..6be0e3530d6 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -64,7 +64,7 @@ export interface KnowledgeTursoPluginOptions { * makes one. @default 20000 */ vectorIndexThreshold?: number; - /** How many approximate-index candidates the vector leg reads per hit (see the adapter's option). @default 40 */ + /** How many approximate-index candidates the vector leg reads per hit, 4 or more (see the adapter's option). @default 40 */ vectorIndexOverfetch?: number; /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ embedder?: IEmbedder; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index e9848e955c0..ea1a6e06c6c 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -96,8 +96,9 @@ export interface TursoKnowledgeAdapterOptions { * How many candidates per hit the vector leg reads from the approximate * index before the organization, record-scope and metadata filter run: the * index ranks before the filter, so a filter that removes candidates is - * answered from what is left, and a leg left with fewer than `topK` is run - * again as the exact scan. A whole number, 1 or more. @default 40 + * answered from what is left, and a leg left with fewer than + * {@link VECTOR_MIN_POOL} × `topK` candidates in scope is run again as the + * exact scan. A whole number, {@link VECTOR_MIN_POOL} or more. @default 40 */ vectorIndexOverfetch?: number; } @@ -114,6 +115,19 @@ export const VECTOR_INDEX_THRESHOLD = 20_000; */ export const VECTOR_INDEX_OVERFETCH = 40; +/** + * How many in-scope candidates per hit the approximate vector leg must keep + * after the filter for its answer to stand; below it the leg runs again as + * the exact scan. The candidates are ranked before the filter, so a filter + * that keeps a few percent of the passages leaves a pool from which the + * float32 re-rank picks the wrong neighbours. Simulated at 200,000 passages + * 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.90 at 5% and 0.88 at 3%; a pool of at least 4 × topK gave 0.98 or more + * at every share. + */ +const VECTOR_MIN_POOL = 4; + /** 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; @@ -249,8 +263,9 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise { - const near = approximate - ? ` AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} - ORDER BY vector_distance_cos(embedding, vector1bit(?1)) LIMIT ${candidates})` - : ''; - return `vec AS ( - SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM ( - SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope}${near} - ) WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`; + // that are in scope (`pool`) — that index ranks before the filter, so its + // candidates are filtered after, and the statement answers how many were + // left. Either way the leg's ranks 1…topK feed the fusion below as they are. + const vectorCtes = (approximate: boolean): string[] => { + const pool = approximate + ? `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope} + AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} + ORDER BY vector_distance_cos(embedding, vector1bit(?1)) LIMIT ${candidates})` + : `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope}`; + const ranked = (from: string) => `vec AS ( + SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM ${from} + WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`; + return approximate ? [`pool AS (${pool})`, ranked('pool')] : [ranked(`(${pool})`)]; }; - if (vectorLeg) { - ctes.push(vectorCte(false)); - legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec'); - } + if (vectorLeg) legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec'); if (terms.length > 0) { // A term's match: the trigram index for three characters or more, LIKE // over the rows in scope below that. @@ -708,9 +723,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { legs.push('SELECT chunk_id, NULL AS vpos, pos AS kpos FROM kw'); } const statement = (approximate: boolean): InStatement => ({ - sql: `WITH ${(approximate ? [vectorCte(true), ...ctes.slice(1)] : ctes).join(',\n')} + sql: `WITH ${[...(vectorLeg ? vectorCtes(approximate) : []), ...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 + p.heading_path, u.vpos, u.kpos${approximate ? ', (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`, @@ -723,10 +738,13 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (terms.length > 0) await this.ensureKeywordIndex(tableName); if (vectorLeg && (await this.approximateSearchable(tableName))) { const near = await client.execute(statement(true)); - // A vector leg the filter left with fewer than topK candidates is - // run again as the exact scan: an answer of fewer than topK says the - // source holds no more, which the candidates cannot say. - if (near.rows.filter((r) => r.vpos !== null).length >= topK) return near; + // 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; } return client.execute(statement(false)); }); @@ -1124,13 +1142,23 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { if (shape !== 'complete') { const count = await client.execute(`SELECT count(*) AS n FROM ${quoted(table)}`); if (Number(count.rows[0].n) < this.vectorIndexThreshold) return undefined; - await this.transaction(async (tx) => { - await tx.execute(organizationIndexDdl(table)); - // One organization at most, or no index: it ranks before the organization filter. - if ((await this.organizationsIn(tx, table)) > 1) return { commit: true, value: undefined }; - for (const statement of vectorIndexDdl(table, target.dim)) await tx.execute(statement); - return { commit: true, value: undefined }; - }); + // A database that refuses the one-bit vectors (a host whose libSQL + // lacks them) or the index's DDL keeps the exact scan, and the build + // completes: the index is a speed-up, never a condition of the build. + // The probe comes first because a trigger naming an unknown function + // is created without complaint and then fails every write of a passage. + if (!(await oneBitVectorsWork(client))) return undefined; + try { + await this.transaction(async (tx) => { + await tx.execute(organizationIndexDdl(table)); + // One organization at most, or no index: it ranks before the organization filter. + if ((await this.organizationsIn(tx, table)) > 1) return { commit: true, value: undefined }; + for (const statement of vectorIndexDdl(table, target.dim)) await tx.execute(statement); + return { commit: true, value: undefined }; + }); + } catch { + return undefined; + } if ((await this.vectorShapeOf(client, table)) !== 'complete') return undefined; } return { target, table }; @@ -1139,6 +1167,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const { target, table } = planned; const { last, copy } = vectorBackfillSql(table); for (let cursor = ''; ; ) { + // A batch the database refuses ends the copy, and the build completes: + // a side table short of its passage table is never searched (its count + // differs), the triggers keep the rows they hold in step, and the next + // complete build resumes the copy. const step = await this.queued(client, () => this.transaction(async (tx) => { const still = await tx.execute({ @@ -1151,7 +1183,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { await tx.execute({ sql: copy, args: [cursor, String(upTo)] }); return { commit: true, value: String(upTo) }; }), - ); + ).catch(() => undefined); if (step === undefined) return; cursor = step; } @@ -1315,6 +1347,22 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } } +/** + * Whether the database computes one-bit vectors and their distance, as the + * approximate vector index needs (libSQL's `vector1bit`); a database that + * refuses the probe gets no index. + */ +async function oneBitVectorsWork(db: Pick): Promise { + try { + const probe = await db.execute( + "SELECT vector_distance_cos(vector1bit(vector32('[1,-1,1,-1]')), vector1bit(vector32('[1,-1,1,-1]'))) AS d", + ); + return Number(probe.rows[0]?.d) === 0; + } catch { + return false; + } +} + /** * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank * in each leg, or null): best first, at most `topK`; a tie goes to the better From d256d2dd0884ac073b7569ac3225284376075f72 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:55:37 +0000 Subject: [PATCH 09/15] test(knowledge-turso): read the optional record id of the scoped fixtures as present Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../plugins/knowledge-turso/src/__tests__/acceptance.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 97b09222e38..d0865f5d378 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1058,7 +1058,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { // Every passage but the two best in scope: 18 or more of the 2 × 10 candidates are left, 4 × topK // and more, so the candidates answer, without the exact scan. from = over.sql.length; - const allButBest = tiers.map((d) => d.sourceRecordId).filter((id) => !id.startsWith('best_')); + const allButBest = tiers.flatMap((d) => d.sourceRecordId ?? []).filter((id) => !id.startsWith('best_')); const wide = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: allButBest }] }); expect(wide).toHaveLength(2); for (const hit of wide) expect(hit.sourceRecordId).toMatch(/^second_/); @@ -1216,7 +1216,7 @@ describe('knowledge-turso approximate vector index: recall and options', () => { let x = 17; const next = () => ((x = (x * 1103515245 + 12345) % 2147483648) / 2147483648); for (const share of [0.1, 0.05, 0.03]) { - const ids = docs.map((d) => d.sourceRecordId).filter(() => next() < share); + const ids = docs.flatMap((d) => d.sourceRecordId ?? []).filter(() => next() < share); const scope = [{ kind: 'record' as const, ids }]; let found = 0; let wanted = 0; From 212c147c66dcb2a52ec9b887d360d65a84454920 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:03:55 +0000 Subject: [PATCH 10/15] test(knowledge-turso): a host without one-bit vectors accepts the DDL and refuses each statement that computes one Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso/src/__tests__/acceptance.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index d0865f5d378..f0600b66d16 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1123,9 +1123,11 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { }); it('a database that refuses the one-bit vectors or the index DDL keeps the exact scan, and the build completes', async () => { - // A host whose libSQL lacks the one-bit type: every statement naming it is refused. for (const [name, refused] of [ - ['ann_no_1bit', /vector1bit\(|F1BIT_BLOB/], + // A host whose libSQL lacks the one-bit vectors: like SQLite, it creates a column of any type and a + // trigger naming an unknown function, and refuses each statement that computes `vector1bit`. + ['ann_no_1bit', /^(?!\s*CREATE\s)[\s\S]*vector1bit\(/i], + // A host that refuses the side table's column type. ['ann_no_ddl', /F1BIT_BLOB/], ] as const) { const s = source(name); From 0fc18f03c2d34c6a2f9e8763cb3651941fc4f46e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:31:43 +0000 Subject: [PATCH 11/15] feat(knowledge-turso): the health check names a refused approximate vector index A database without one-bit vectors is named by healthCheck's message at boot (the plugin logs it), and each source whose complete build had its index refused is named with the reason until a later build makes it or the source is dropped. ok stays true: the index is a speed-up, and a store whose index works keeps the message it had. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso-approximate-index.md | 2 +- content/docs/protocol/knowledge.mdx | 4 +- packages/plugins/knowledge-turso/README.md | 2 +- .../src/__tests__/acceptance.test.ts | 15 +++++++- .../knowledge-turso/src/turso-adapter.ts | 38 ++++++++++++++++--- 5 files changed, 51 insertions(+), 10 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index a823f96be84..01830eb399d 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -10,6 +10,6 @@ Metadata-protocol: none Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. -- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, and the build completes on the exact scan. +- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. - **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. - **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 4 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index bd2934cc307..78de22f0460 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -749,8 +749,8 @@ large source of one organization, through an approximate index. with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow scope keeps its recall and a search never answers fewer hits than the exact scan. A database that - refuses the one-bit vectors or the index's DDL gets no index, and its - builds complete. The candidates are ranked before the + refuses the one-bit vectors or the index's DDL gets no index, its builds + complete, and the adapter's health check names the source and the reason. The candidates are ranked before the filter, so the index is never made, or used, over the passages of two organizations (passages of none count as one): each search reads the organization index and takes the exact scan once a second organization's diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 1471bb6b6f2..bfb4b9a305f 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -60,7 +60,7 @@ The organization filter, the record scope (a passage's record, or a metadata val - **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 4 × `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: in a simulation 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` gave 0.98 or more at every share. 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, and the source keeps the exact scan. +- **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. - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index f0600b66d16..b4ce399ecb6 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1122,7 +1122,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 1, exact: 0 }); }); - it('a database that refuses the one-bit vectors or the index DDL keeps the exact scan, and the build completes', async () => { + it('a database that refuses the one-bit vectors or the index DDL keeps the exact scan, the build completes, and the health check names it', async () => { for (const [name, refused] of [ // A host whose libSQL lacks the one-bit vectors: like SQLite, it creates a column of any type and a // trigger naming an unknown function, and refuses each statement that computes `vector1bit`. @@ -1143,6 +1143,19 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const from = watched.sql.length; expect((await adapter.search('wzzx wyyx wxxx', { source: s, topK: 1 })).map((h) => h.sourceRecordId)).toEqual(['late']); expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 0, exact: 1 }); + // The refusal is named to the operator, through the health check the boot line and the health endpoint + // read; the store stays ready. + const health = await adapter.healthCheck(); + expect(health.ok).toBe(true); + expect(health.message).toContain(`the approximate vector index of source '${s.name}' was not made`); + const noOneBit = 'this database does not compute one-bit vectors (vector1bit), so no source gets an approximate vector index'; + if (name === 'ann_no_1bit') expect(health.message).toContain(noOneBit); + else expect(health.message).toContain('the database refused its DDL'); + // A dropped source is no longer named. + await adapter.dropSource(ctx(s)); + const after = await adapter.healthCheck(); + expect(after.message).not.toContain(`source '${s.name}'`); + if (name === 'ann_no_ddl') expect(after).toEqual({ ok: true, message: 'libSQL vectors ready' }); } }); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index ea1a6e06c6c..f3eb0a4cfcb 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -341,6 +341,12 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { private readonly keyed = new Set(); /** Passage tables whose vector side table is known to hold every passage (triggers keep it so). */ private readonly vectorIndexed = new Set(); + /** + * Sources whose last complete build did not make their approximate vector + * index because the database refused it, with the reason: named by + * {@link healthCheck} until a later build of the source makes it. + */ + private readonly vectorIndexRefused = new Map(); private readonly vectorIndexThreshold: number; private readonly vectorIndexOverfetch: number; @@ -886,6 +892,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return { commit: true, value: undefined }; }); if (legacy) this.noLegacy.add(sourceId); + this.vectorIndexRefused.delete(sourceId); }); } @@ -893,7 +900,19 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { try { this.requireClient(); await this.ready(); - return { ok: true, message: 'libSQL vectors ready' }; + // A refused approximate vector index is a speed-up lost, never a fault: + // `ok` stays true, and the message names it for the operator. + const notes: string[] = []; + if (this.vectorIndexThreshold !== Infinity && !(await oneBitVectorsWork(this.requireClient()))) { + notes.push( + 'this database does not compute one-bit vectors (vector1bit), so no source gets an approximate vector ' + + 'index and every search reads every vector in scope', + ); + } + for (const [sourceId, reason] of this.vectorIndexRefused) { + notes.push(`the approximate vector index of source '${sourceId}' was not made: ${reason}`); + } + return { ok: true, message: ['libSQL vectors ready', ...notes].join('; ') }; } catch (err) { const remedy = remedyOf(err); return { ok: false, message: `${errorText(err)}${remedy === undefined ? '' : ` ${remedy}`}` }; @@ -1130,6 +1149,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { */ private async buildVectorIndex(sourceId: string, fingerprint: string): Promise { const client = this.requireClient(); + // Each complete build says anew whether the database refused the index. + this.vectorIndexRefused.delete(sourceId); const planned = await this.queued(client, async () => { const { active, building } = await this.generations(sourceId); const target = @@ -1147,7 +1168,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // completes: the index is a speed-up, never a condition of the build. // The probe comes first because a trigger naming an unknown function // is created without complaint and then fails every write of a passage. - if (!(await oneBitVectorsWork(client))) return undefined; + if (!(await oneBitVectorsWork(client))) { + this.vectorIndexRefused.set(sourceId, 'this database does not compute one-bit vectors (vector1bit)'); + return undefined; + } try { await this.transaction(async (tx) => { await tx.execute(organizationIndexDdl(table)); @@ -1156,7 +1180,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { for (const statement of vectorIndexDdl(table, target.dim)) await tx.execute(statement); return { commit: true, value: undefined }; }); - } catch { + } catch (err) { + this.vectorIndexRefused.set(sourceId, `the database refused its DDL (${errorText(err)})`); return undefined; } if ((await this.vectorShapeOf(client, table)) !== 'complete') return undefined; @@ -1183,8 +1208,11 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { await tx.execute({ sql: copy, args: [cursor, String(upTo)] }); return { commit: true, value: String(upTo) }; }), - ).catch(() => undefined); - if (step === undefined) return; + ).catch((err: unknown) => { + this.vectorIndexRefused.set(sourceId, `the database refused its copy (${errorText(err)}); the next complete build resumes it`); + return null; + }); + if (step === null || step === undefined) return; cursor = step; } } From d3772d1288b67a9157b293efc03722c59c816afc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 00:32:29 +0000 Subject: [PATCH 12/15] fix(knowledge-turso): the approximate vector leg needs 8 x topK candidates in scope, and the over-fetch 8 or more Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/knowledge-turso-approximate-index.md | 4 ++-- content/docs/protocol/knowledge.mdx | 2 +- packages/plugins/knowledge-turso/README.md | 4 ++-- .../src/__tests__/acceptance.test.ts | 16 ++++++++-------- .../knowledge-turso/src/__tests__/plugin.test.ts | 2 +- packages/plugins/knowledge-turso/src/plugin.ts | 2 +- .../plugins/knowledge-turso/src/turso-adapter.ts | 8 ++++---- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index 01830eb399d..69ff92f836d 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -7,9 +7,9 @@ feat(knowledge-turso): an approximate vector index for a large source of one org Clause-②: yes (widening) Metadata-protocol: none -Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. +Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. - **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. - **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. -- **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 4 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. +- **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 8 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 78de22f0460..047d1d19d6d 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -746,7 +746,7 @@ large source of one organization, through an approximate index. `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same `WHERE` over them, ranks those in scope by their stored vector, and feeds the fusion as the exact leg does; a leg the filter leaves - with fewer than 4 × `topK` candidates in scope, or short of `topK` hits, + with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow scope keeps its recall and a search never answers fewer hits than the exact scan. A database that refuses the one-bit vectors or the index's DDL gets no index, its builds diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index bfb4b9a305f..890228ea547 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -31,7 +31,7 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts | `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | | `vectorIndexThreshold` | `20000` | The passage count at or above which a complete build makes a source's approximate vector index ([Search](#search)). `Infinity` never makes one. | -| `vectorIndexOverfetch` | `40` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 4 or more. | +| `vectorIndexOverfetch` | `40` | How many approximate-index candidates the vector leg reads per hit, before the filter runs. A whole number, 8 or more. | ## Its own file, never the platform's @@ -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 4 × `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: in a simulation 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` gave 0.98 or more at every share. 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. 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. - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index b4ce399ecb6..9fcbaf06c64 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1032,7 +1032,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(vectorLegs(mixed.sql, from)).toEqual({ approximate: 0, exact: 1 }); }); - it('the filter runs on the over-fetched candidates; a leg it leaves under 4 × topK in scope is run again exactly', async () => { + it('the filter runs on the over-fetched candidates; a leg it leaves under 8 × topK in scope is run again exactly', async () => { const s = source('ann_scope'); const QUERY = 'w1x w2x w3x w4x'; // 56 passages near the query, published; 4 far from it, drafts. @@ -1040,8 +1040,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ...Array.from({ length: 56 }, (_, i) => doc(s, `near_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 9) + 5}x`)), ...['a', 'b', 'c', 'd'].map((n) => doc(s, `far_${n}`, `w1x wqx wrx ws${n}x`, { metadata: { status: 'draft' } })), ]; - // Four candidates a hit, so the candidates are not every row of this small table. - const { adapter, sql } = await built(s, docs, { vectorIndexOverfetch: 4 }); + // Eight candidates a hit, so the candidates are not every row of this small table. + const { adapter, sql } = await built(s, docs, { vectorIndexOverfetch: 8 }); // A filter only the far passages pass: none is among the candidates, so the exact scan answers. let from = sql.length; const drafts = await adapter.search(QUERY, { source: s, topK: 3, filter: { status: 'draft' } }); @@ -1055,7 +1055,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ...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, 4 × topK + // Every passage but the two best in scope: 18 or more of the 2 × 10 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_')); @@ -1063,7 +1063,7 @@ 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 4 × topK, so the exact scan answers. + // Two passages in scope: at most 2 of the 20 candidates, fewer than 8 × topK, so the exact scan answers. 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 }] }); @@ -1247,12 +1247,12 @@ describe('knowledge-turso approximate vector index: recall and options', () => { } }); - it('refuses a threshold below 1 and an over-fetch that is not a whole number of 4 or more', () => { + it('refuses a threshold below 1 and an over-fetch that is not a whole number of 8 or more', () => { const client = store.client(); const embedder = new FakeEmbedder(); - for (const bad of [{ vectorIndexThreshold: 0 }, { vectorIndexThreshold: Number.NaN }, { vectorIndexOverfetch: 3 }, { vectorIndexOverfetch: 4.5 }]) { + for (const bad of [{ vectorIndexThreshold: 0 }, { vectorIndexThreshold: Number.NaN }, { vectorIndexOverfetch: 7 }, { vectorIndexOverfetch: 8.5 }]) { expect(() => new TursoKnowledgeAdapter({ client, embedder, ...bad })).toThrow(RangeError); } - expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 4 })).not.toThrow(); + expect(() => new TursoKnowledgeAdapter({ client, embedder, vectorIndexThreshold: Infinity, vectorIndexOverfetch: 8 })).not.toThrow(); }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts index 17b9ead0bb2..7f0faa54a43 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/plugin.test.ts @@ -211,7 +211,7 @@ describe('KnowledgeTursoPlugin', () => { it('hands vectorIndexThreshold to its adapter: a complete build at the threshold makes the approximate index', async () => { const root = tempDir(); const { ctx, adapters } = contextOf(); - const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, vectorIndexThreshold: 3, vectorIndexOverfetch: 5 }); + const plugin = new KnowledgeTursoPlugin({ projectRoot: root, env: {}, vectorIndexThreshold: 3, vectorIndexOverfetch: 10 }); await plugin.start(ctx); const adapter = adapters.get('turso')!; const source = { name: 'notes', label: 'n', adapter: 'turso', source: { kind: 'object', object: 'o', content: ['b'] } } as never; diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index 6be0e3530d6..c34a9ba88bb 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -64,7 +64,7 @@ export interface KnowledgeTursoPluginOptions { * makes one. @default 20000 */ vectorIndexThreshold?: number; - /** How many approximate-index candidates the vector leg reads per hit, 4 or more (see the adapter's option). @default 40 */ + /** How many approximate-index candidates the vector leg reads per hit, 8 or more (see the adapter's option). @default 40 */ vectorIndexOverfetch?: number; /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ embedder?: IEmbedder; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index f3eb0a4cfcb..fee74d614fd 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -120,13 +120,13 @@ export const VECTOR_INDEX_OVERFETCH = 40; * after the filter for its answer to stand; below it the leg runs again as * the exact scan. The candidates are ranked before the filter, so a filter * that keeps a few percent of the passages leaves a pool from which the - * float32 re-rank picks the wrong neighbours. Simulated at 200,000 passages + * float32 re-rank picks the wrong neighbours. Measured at 200,000 passages * 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.90 at 5% and 0.88 at 3%; a pool of at least 4 × topK gave 0.98 or more - * at every share. + * 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. */ -const VECTOR_MIN_POOL = 4; +const VECTOR_MIN_POOL = 8; /** 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; From 98ffbe43401f0ff9dd65889508de8ff5d073d9c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:33:59 +0000 Subject: [PATCH 13/15] fix(knowledge-turso): the index memory is now keyed per generation instance; reads and bound values only where used The approximate-index memory is now keyed per generation instance, and a failed approximate statement is answered by the exact scan. A search at vectorIndexThreshold Infinity reads no catalog for an index, and a build remembers what it found, so a source under the threshold costs no catalog read in its own process and two reads once in another. The candidate count is bound for the approximate statement alone. A refused copy batch is pinned beside the refused probe and DDL. The protocol doc's two leftover exact-scan sentences now name the approximate index. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../knowledge-turso-approximate-index.md | 2 +- content/docs/protocol/knowledge.mdx | 10 +- packages/plugins/knowledge-turso/README.md | 3 +- .../src/__tests__/acceptance.test.ts | 151 +++++++++++++++++- .../knowledge-turso/src/turso-adapter.ts | 97 +++++++---- 5 files changed, 221 insertions(+), 42 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index 69ff92f836d..2099ac9c162 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -10,6 +10,6 @@ Metadata-protocol: none Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. -- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. +- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. A process reads the catalog for a generation's index once (two reads) and remembers the answer; at `vectorIndexThreshold: Infinity` it never does. - **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. - **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 8 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index a7615f32303..21acd04bb4d 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -730,13 +730,13 @@ large source of one organization, through an approximate index. (`` is the source's index key). A key that is not snake_case is refused before any SQL. - **Search.** Two legs merged by reciprocal rank fusion (`k` = 60, each leg - at most `topK`) before the service's re-check: an exact scan by cosine - distance, and a keyword leg in a contentless FTS5 trigram index beside each + at most `topK`) before the service's re-check: a vector leg by cosine + distance (an exact scan, or the approximate index below), and a keyword leg in a contentless FTS5 trigram index beside each passage table (kept in step by triggers), a term of three characters or more as a quoted phrase, a shorter one by `LIKE`. The organization filter, the [record scope](#record-scope) and the metadata `filter` (JSON equality - per key) are one `WHERE`, run in both legs. The exact scan reads every row - in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about + per key) are one `WHERE`, run in both legs. Without the approximate index + the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and about 50 ms. - **Approximate index.** A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one @@ -1303,7 +1303,7 @@ followed (§4.1, §4.2) are the adapters to run in production. | `knowledge-llamaindex` | ⏳ Phase 2 | | | `knowledge-dify` | ⏳ Phase 3 / community | | | `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan and a `tsvector` keyword leg merged by RRF, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) | -| `knowledge-turso` | ✅ | A libSQL file of its own; exact scan and an FTS5 trigram keyword leg merged by RRF, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) | +| `knowledge-turso` | ✅ | A libSQL file of its own; a vector leg (an exact scan, or a one-bit approximate index for a large source of one organization) and an FTS5 trigram keyword leg merged by RRF, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) | ### 7.1 Non-goals for Phase 1 diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 3f09a0bc8a3..4e8312f8d7a 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -60,7 +60,8 @@ The organization filter, the record scope (a passage's record, or a metadata val - **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". - **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. +- **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. A generation is known by its number and the time its row was made, so a source that another process dropped and built again is a new one, read anew. 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. 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). - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 77369675e97..b2a892f0ca7 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1046,9 +1046,14 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { * a test reads which path a search took: the approximate vector leg ranks * the one-bit side table (`vector1bit`), the exact one does not. */ -function recording(client: Client): { client: Client; sql: string[] } { +function recording(client: Client): { client: Client; sql: string[]; args: unknown[][] } { const sql: string[] = []; - const note = (statement: unknown) => sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + const args: unknown[][] = []; + const note = (statement: unknown) => { + sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + const bound = typeof statement === 'string' ? undefined : (statement as { args?: unknown }).args; + args.push(Array.isArray(bound) ? bound : []); + }; const watch = (target: T, onTransaction: boolean): T => new Proxy(target, { get(t, key) { @@ -1063,14 +1068,40 @@ function recording(client: Client): { client: Client; sql: string[] } { return fn; }, }); - return { client: watch(client, true), sql }; + return { client: watch(client, true), sql, args }; +} + +/** The catalog reads of a vector index recorded since `from`: the shape reads that name a `-vec` side table. */ +function vectorCatalogReads(watched: { sql: string[]; args: unknown[][] }, from = 0): number { + return watched.sql + .slice(from) + .filter((sql, i) => /sqlite_master|pragma_table_info/.test(sql) && watched.args[from + i].some((a) => String(a).endsWith('-vec'))).length; +} + +/** The vector-leg statements recorded since `from`, each with the highest `?N` its SQL reads and the values bound. */ +function vectorStatements(watched: { sql: string[]; args: unknown[][] }, from = 0): Array<{ approximate: boolean; reads: number; bound: number }> { + return watched.sql.flatMap((sql, i) => + i < from || !sql.includes('vec AS (') + ? [] + : [{ approximate: sql.includes('vector1bit('), reads: Math.max(...[...sql.matchAll(/\?(\d+)/g)].map((m) => Number(m[1]))), bound: watched.args[i].length }], + ); +} + +/** A fake embedder that gives a query of no letters or digits, which has no keyword term, the vector of two words. */ +class TermlessQueryEmbedder extends FakeEmbedder { + override async embed(texts: string[]): Promise { + return super.embed(texts.map((t) => (/[a-z0-9]/i.test(t) ? t : 'w1x w2x'))); + } } /** * A recorded client that refuses, as a database that does not know them * would, the statements whose SQL matches `pattern`, the transaction's too. */ -function refusing(watched: { client: Client; sql: string[] }, pattern: RegExp): { client: Client; sql: string[]; refused: string[] } { +function refusing( + watched: { client: Client; sql: string[]; args: unknown[][] }, + pattern: RegExp, +): { client: Client; sql: string[]; args: unknown[][]; refused: string[] } { const refused: string[] = []; const sqlOf = (statement: unknown) => (typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); const guard = (target: T, onTransaction: boolean): T => @@ -1092,7 +1123,7 @@ function refusing(watched: { client: Client; sql: string[] }, pattern: RegExp): return fn; }, }); - return { client: guard(watched.client, true), sql: watched.sql, refused }; + return { client: guard(watched.client, true), sql: watched.sql, args: watched.args, refused }; } /** The vector legs of the searches recorded since `from`: how many were approximate, how many exact. */ @@ -1294,6 +1325,8 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ['ann_no_1bit', /^(?!\s*CREATE\s)[\s\S]*vector1bit\(/i], // A host that refuses the side table's column type. ['ann_no_ddl', /F1BIT_BLOB/], + // A host that makes the index and refuses the copy of the passages into it. + ['ann_no_copy', /^\s*INSERT INTO "[^"]+-vec"/], ] as const) { const s = source(name); const watched = refusing(recording(store.client()), refused); @@ -1302,7 +1335,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.upsert(corpus(s, 60), ctx(s)); await adapter.completeBuild(ctx(s)); expect(watched.refused.length).toBeGreaterThan(0); - expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toEqual([]); + // Refused before the copy: nothing of the index is left. Refused at the copy: the index is there, short of + // its passage table, and never searched. + expect(await vectorObjects(watched.client, `knowledge_${s.name}_g1`)).toHaveLength(name === 'ann_no_copy' ? 5 : 0); // The build switched to its generation, and writes and searches go on through the exact scan. await adapter.upsert([doc(s, 'late', 'wzzx wyyx wxxx')], ctx(s)); const from = watched.sql.length; @@ -1315,15 +1350,55 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(health.message).toContain(`the approximate vector index of source '${s.name}' was not made`); const noOneBit = 'this database does not compute one-bit vectors (vector1bit), so no source gets an approximate vector index'; if (name === 'ann_no_1bit') expect(health.message).toContain(noOneBit); - else expect(health.message).toContain('the database refused its DDL'); + else if (name === 'ann_no_ddl') expect(health.message).toContain('the database refused its DDL'); + else expect(health.message).toContain('the database refused its copy'); // A dropped source is no longer named. await adapter.dropSource(ctx(s)); const after = await adapter.healthCheck(); expect(after.message).not.toContain(`source '${s.name}'`); - if (name === 'ann_no_ddl') expect(after).toEqual({ ok: true, message: 'libSQL vectors ready' }); + if (name !== 'ann_no_1bit') expect(after).toEqual({ ok: true, message: 'libSQL vectors ready' }); + } + }); + + it('a search under the threshold, or at Infinity, reads no catalog for an index; another process reads it once', async () => { + for (const vectorIndexThreshold of [61, Infinity]) { + const s = source(`ann_reads_${vectorIndexThreshold === Infinity ? 'inf' : 'n'}`); + const watched = recording(store.client()); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(corpus(s, 60), ctx(s)); + await adapter.completeBuild(ctx(s)); + const from = watched.sql.length; + for (const query of ['w1x w2x', 'w3x w4x', 'w5x']) await adapter.search(query, { source: s, topK: 5 }); + expect(vectorCatalogReads(watched, from)).toBe(0); + expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 0, exact: 3 }); } }); + it('a query without a keyword term binds exactly the values each vector statement reads', async () => { + const s = source('ann_termless'); + const watched = recording(store.client()); + const adapter = new TursoKnowledgeAdapter({ + id: 'under_test', + client: watched.client, + embedder: new TermlessQueryEmbedder(), + vectorIndexThreshold: THRESHOLD, + }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(corpus(s, 60), ctx(s)); + 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. + 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 }] })).toHaveLength(2); + const statements = vectorStatements(watched, from); + expect(statements.map((st) => st.approximate)).toEqual([true, true, false]); + for (const st of statements) expect(st).toMatchObject({ reads: st.bound }); + }); + it('an object it did not make under a vector-index name is never dropped; the build and dropSource are refused', async () => { const s = source('ann_taken'); const watched = recording(store.client()); @@ -1353,6 +1428,66 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { }); } +describe('knowledge-turso approximate vector index: two processes on one file store', () => { + const store = storeOf('file'); + afterAll(() => store.closeAll()); + const corpus = (s: KnowledgeSource, n: number) => wordsOf(n, 7).map((text, i) => doc(s, String(i).padStart(3, '0'), text)); + const processes = () => { + const at = store.url(); + const one = () => { + const watched = recording(store.client(at)); + return { ...watched, adapter: new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold: 40 }) }; + }; + return { a: one(), b: one(), raw: store.client(at) }; + }; + const build = async (adapter: TursoKnowledgeAdapter, s: KnowledgeSource, n: number) => { + await adapter.beginBuild(ctx(s)); + await adapter.upsert(corpus(s, n), ctx(s)); + await adapter.completeBuild(ctx(s)); + }; + + it('a source another process dropped and built again under the threshold is searched by the exact scan, not by the index it had', async () => { + const s = source('ann_two_procs'); + const { a, b } = processes(); + await build(a.adapter, s, 60); + let from = b.sql.length; + expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + expect(vectorLegs(b.sql, from)).toEqual({ approximate: 1, exact: 0 }); + // Generation 1 again, made anew, under the threshold: no index. + await a.adapter.dropSource(ctx(s)); + await build(a.adapter, s, 30); + expect(await vectorObjects(a.client, `knowledge_${s.name}_g1`)).toEqual([]); + from = b.sql.length; + expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + expect(vectorLegs(b.sql, from)).toEqual({ approximate: 0, exact: 1 }); + }); + + it('an index gone under the memory of it is answered by the exact scan, and forgotten', async () => { + const s = source('ann_gone'); + const { a, b, raw } = processes(); + await build(a.adapter, s, 60); + expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + const table = `knowledge_${s.name}_g1`; + for (const name of [`${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`]) await raw.execute(`DROP TRIGGER "${name}"`); + await raw.execute(`DROP TABLE "${table}-vec"`); + let from = b.sql.length; + expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + expect(vectorLegs(b.sql, from)).toEqual({ approximate: 1, exact: 1 }); + from = b.sql.length; + expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); + expect(vectorLegs(b.sql, from)).toEqual({ approximate: 0, exact: 1 }); + }); + + it('another process reads the catalog of a source under the threshold once, then remembers it', async () => { + const s = source('ann_reads_once'); + const { a, b } = processes(); + await build(a.adapter, s, 30); + const from = b.sql.length; + for (const query of ['w1x w2x', 'w3x w4x', 'w5x']) await b.adapter.search(query, { source: s, topK: 5 }); + expect(vectorCatalogReads(b, from)).toBe(2); + }); +}); + describe('knowledge-turso approximate vector index: recall and options', () => { const store = storeOf('memory'); afterAll(() => store.closeAll()); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 0b278e0beed..6c305c220bb 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -371,8 +371,14 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { private readonly noLegacy = new Set(); /** Passage tables whose keyword index is known to be complete. */ private readonly keyed = new Set(); - /** Passage tables whose vector side table is known to hold every passage (triggers keep it so). */ - private readonly vectorIndexed = new Set(); + /** + * Whether the approximate vector index of a generation instance (its + * passage table and the time its generation row was made, {@link + * vectorIndexKey}) is complete, as this process last found it: kept true by + * the triggers while the instance lasts, and a generation another process + * drops and makes again under the same number is another instance. + */ + private readonly vectorIndexKnown = new Map(); /** * Sources whose last complete build did not make their approximate vector * index because the database refused it, with the reason: named by @@ -704,8 +710,6 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const inScope = where.length === 0 ? 'TRUE' : where.join(' AND '); args.push(topK); const limit = `?${args.length}`; - args.push(topK * this.vectorIndexOverfetch); - const candidates = `?${args.length}`; const tableName = generationTable(opts.source.name, active.generation); const table = quoted(tableName); const vectorIndex = vectorIndexNames(tableName); @@ -719,6 +723,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // candidates are filtered after, and the statement answers how many were // left. Either way the leg's ranks 1…topK feed the fusion below as they are. const vectorCtes = (approximate: boolean): string[] => { + // The candidate count is bound for the approximate statement alone, after every other value. + const candidates = `?${args.length + 1}`; const pool = approximate ? `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope} AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} @@ -768,15 +774,22 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { 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: args as InArgs, + args: (approximate ? [...args, topK * this.vectorIndexOverfetch] : args) as InArgs, }); const result = await this.queued(client, async () => { // The generation may have been switched while the query was embedded. const now = await this.generations(opts.source.name); if (now.active?.generation !== active.generation) return undefined; if (terms.length > 0) await this.ensureKeywordIndex(tableName); - if (vectorLeg && (await this.approximateSearchable(tableName))) { - const near = await client.execute(statement(true)); + const instance = now.active.createdAt; + 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)); // 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 @@ -1125,7 +1138,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { for (const statement of dropKeywordIndexDdl(table)) await tx.execute(statement); for (const statement of dropVectorIndexDdl(table)) await tx.execute(statement); this.keyed.delete(table); - this.vectorIndexed.delete(table); + this.forgetVectorIndex(table); } /** The shape of the vector index of the passage table `table` (`vectorIndexShape`). */ @@ -1151,10 +1164,13 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } /** - * Whether a search of the passage table `table` may rank its vector leg + * Whether a search of the passage table `table`, of the generation + * instance whose row was made at `instance`, may rank its vector leg * through the approximate index: its side table and triggers are there and - * hold every passage of the table (once true, kept so by the - * triggers, and remembered), and the table holds passages of one + * hold every passage of the table (read from the catalog once per instance + * and remembered, either way: the triggers keep a complete index complete, + * a build of this process records what it found, and with a threshold of + * `Infinity` nothing is read), and the table holds passages of one * organization at most — read at each search, from the organization index, * so a second organization written after the index was made turns the * table back to the exact scan at once. The index ranks before the @@ -1162,19 +1178,32 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { * organization's candidates would crowd out the other's. Runs inside the * client's queue. */ - private async approximateSearchable(table: string): Promise { + private async approximateSearchable(table: string, instance: string): Promise { + // `Infinity` never makes an index, and never reads the catalog for one. + if (this.vectorIndexThreshold === Infinity) return false; const client = this.requireClient(); - if (!this.vectorIndexed.has(table)) { - if ((await this.vectorShapeOf(client, table)) !== 'complete') return false; - const counts = await client.execute( - `SELECT (SELECT count(*) FROM ${quoted(table)}) AS n, (SELECT count(*) FROM ${quoted(vectorIndexNames(table).side)}) AS v`, - ); - if (Number(counts.rows[0].n) !== Number(counts.rows[0].v)) return false; - this.vectorIndexed.add(table); + const key = vectorIndexKey(table, instance); + let complete = this.vectorIndexKnown.get(key); + if (complete === undefined) { + complete = (await this.vectorShapeOf(client, table)) === 'complete'; + if (complete) { + const counts = await client.execute( + `SELECT (SELECT count(*) FROM ${quoted(table)}) AS n, (SELECT count(*) FROM ${quoted(vectorIndexNames(table).side)}) AS v`, + ); + complete = Number(counts.rows[0].n) === Number(counts.rows[0].v); + } + this.vectorIndexKnown.set(key, complete); } + if (!complete) return false; return (await this.organizationsIn(client, table)) <= 1; } + /** 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, ''); + for (const key of this.vectorIndexKnown.keys()) if (key.startsWith(prefix)) this.vectorIndexKnown.delete(key); + } + /** * How many organizations the passages of `table` belong to, counting * passages of no organization as one more, up to 2: three seeks of the @@ -1216,11 +1245,16 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // No generation of this fingerprint: completeBuild refuses the call. if (target === undefined) return undefined; const table = generationTable(sourceId, target.generation); + // What this build finds is what a search of this generation instance would: no index is remembered as such. + const none = () => { + this.vectorIndexKnown.set(vectorIndexKey(table, target.createdAt), false); + return undefined; + }; const shape = await this.vectorShapeOf(client, table); if (shape === 'other') throw vectorIndexNotOurs(table, sourceId, target.generation); if (shape !== 'complete') { const count = await client.execute(`SELECT count(*) AS n FROM ${quoted(table)}`); - if (Number(count.rows[0].n) < this.vectorIndexThreshold) return undefined; + if (Number(count.rows[0].n) < this.vectorIndexThreshold) return none(); // A database that refuses the one-bit vectors (a host whose libSQL // lacks them) or the index's DDL keeps the exact scan, and the build // completes: the index is a speed-up, never a condition of the build. @@ -1228,7 +1262,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // is created without complaint and then fails every write of a passage. if (!(await oneBitVectorsWork(client))) { this.vectorIndexRefused.set(sourceId, 'this database does not compute one-bit vectors (vector1bit)'); - return undefined; + return none(); } try { await this.transaction(async (tx) => { @@ -1240,9 +1274,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { }); } catch (err) { this.vectorIndexRefused.set(sourceId, `the database refused its DDL (${errorText(err)})`); - return undefined; + return none(); } - if ((await this.vectorShapeOf(client, table)) !== 'complete') return undefined; + if ((await this.vectorShapeOf(client, table)) !== 'complete') return none(); } return { target, table }; }); @@ -1257,8 +1291,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const step = await this.queued(client, () => this.transaction(async (tx) => { const still = await tx.execute({ - sql: `SELECT 1 FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ? AND fingerprint IS ?`, - args: [sourceId, target.generation, target.fingerprint], + sql: `SELECT 1 FROM ${quoted(GENERATION_TABLE)} WHERE source_id = ? AND generation = ? AND fingerprint IS ? AND created_at = ?`, + args: [sourceId, target.generation, target.fingerprint, target.createdAt], }); if (still.rows.length === 0) return { commit: false, value: undefined }; const upTo = (await tx.execute({ sql: last, args: [cursor, VECTOR_BACKFILL_BATCH] })).rows[0]?.last; @@ -1270,7 +1304,11 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { this.vectorIndexRefused.set(sourceId, `the database refused its copy (${errorText(err)}); the next complete build resumes it`); return null; }); - if (step === null || step === undefined) return; + if (step === null || step === undefined) { + // The copy ended, was refused, or its generation went away: the next search reads the index anew. + this.vectorIndexKnown.delete(vectorIndexKey(table, target.createdAt)); + return; + } cursor = step; } } @@ -1367,7 +1405,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { for (const statement of dropVectorIndexDdl(table)) await tx.execute(statement); for (const statement of passageTableDdl(table, embedder.dimensions)) await tx.execute(statement); this.keyed.add(table); - this.vectorIndexed.delete(table); + this.forgetVectorIndex(table); await tx.execute({ sql: `INSERT INTO ${quoted(GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) VALUES (?, ?, ?, ?, ?, ?)`, args: [sourceId, generation, fingerprint ?? null, embedder.dimensions, embedder.model ?? null, state], @@ -1452,6 +1490,11 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } } +/** The key of a generation instance in the memory of its approximate vector index: its passage table and the time its row was made. */ +function vectorIndexKey(table: string, createdAt: string): string { + return `${table} @ ${createdAt}`; +} + /** * Whether the database computes one-bit vectors and their distance, as the * approximate vector index needs (libSQL's `vector1bit`); a database that From b113f0830f03e4f8aed12d42c3b5e579e5e82942 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 02:09:00 +0000 Subject: [PATCH 14/15] test(knowledge-turso): an adapter that did not build the source reads no index catalog at Infinity either Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- packages/plugins/knowledge-turso/README.md | 2 +- .../src/__tests__/acceptance.test.ts | 13 ++++++++++--- .../plugins/knowledge-turso/src/turso-adapter.ts | 3 +-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 4e8312f8d7a..509a76e95c8 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -61,7 +61,7 @@ The organization filter, the record scope (a passage's record, or a metadata val - **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". - **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. A generation is known by its number and the time its row was made, so a source that another process dropped and built again is a new one, read anew. 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. 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). +- **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. 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). - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index b2a892f0ca7..222349a07f4 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1372,6 +1372,13 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { for (const query of ['w1x w2x', 'w3x w4x', 'w5x']) await adapter.search(query, { source: s, topK: 5 }); expect(vectorCatalogReads(watched, from)).toBe(0); expect(vectorLegs(watched.sql, from)).toEqual({ approximate: 0, exact: 3 }); + if (vectorIndexThreshold === Infinity) { + // An adapter that did not build the source reads no catalog for an index either. + const other = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold }); + const at = watched.sql.length; + for (const query of ['w1x w2x', 'w3x w4x']) await other.search(query, { source: s, topK: 5 }); + expect(vectorCatalogReads(watched, at)).toBe(0); + } } }); @@ -1446,14 +1453,14 @@ describe('knowledge-turso approximate vector index: two processes on one file st await adapter.completeBuild(ctx(s)); }; - it('a source another process dropped and built again under the threshold is searched by the exact scan, not by the index it had', async () => { + it('the index memory is keyed per generation instance', async () => { const s = source('ann_two_procs'); const { a, b } = processes(); await build(a.adapter, s, 60); let from = b.sql.length; expect(await b.adapter.search('w1x w2x', { source: s, topK: 5 })).toHaveLength(5); expect(vectorLegs(b.sql, from)).toEqual({ approximate: 1, exact: 0 }); - // Generation 1 again, made anew, under the threshold: no index. + // A new instance of generation 1, under the threshold. await a.adapter.dropSource(ctx(s)); await build(a.adapter, s, 30); expect(await vectorObjects(a.client, `knowledge_${s.name}_g1`)).toEqual([]); @@ -1462,7 +1469,7 @@ describe('knowledge-turso approximate vector index: two processes on one file st expect(vectorLegs(b.sql, from)).toEqual({ approximate: 0, exact: 1 }); }); - it('an index gone under the memory of it is answered by the exact scan, and forgotten', async () => { + it('a failed approximate statement is answered by the exact scan, and its memory forgotten', async () => { const s = source('ann_gone'); const { a, b, raw } = processes(); await build(a.adapter, s, 60); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 6c305c220bb..e0b816b85d3 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -375,8 +375,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { * Whether the approximate vector index of a generation instance (its * passage table and the time its generation row was made, {@link * vectorIndexKey}) is complete, as this process last found it: kept true by - * the triggers while the instance lasts, and a generation another process - * drops and makes again under the same number is another instance. + * the triggers while the instance lasts. */ private readonly vectorIndexKnown = new Map(); /** From 73d277418b303a87e50e4fd79592b6035f37fed5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:58:35 +0000 Subject: [PATCH 15/15] test(knowledge-turso): the two 2,000-passage recall cases get a 30 s timeout; the Infinity wording says what a search reads The scoped recall case took 5,971 ms on CI against the 5 s default; both 2,000-passage cases now carry an explicit timeout citing the local and CI readings. The changeset and README now say that at Infinity a search never reads the catalog for an index, and an index made earlier stays in place unsearched. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .changeset/knowledge-turso-approximate-index.md | 2 +- packages/plugins/knowledge-turso/README.md | 2 +- .../knowledge-turso/src/__tests__/acceptance.test.ts | 6 ++++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md index 2099ac9c162..631bfccebf7 100644 --- a/.changeset/knowledge-turso-approximate-index.md +++ b/.changeset/knowledge-turso-approximate-index.md @@ -10,6 +10,6 @@ Metadata-protocol: none Every search of a libSQL store read every vector in scope: at 1,536 dimensions about 1.2 GB at 200,000 passages. A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, now makes that generation's approximate index: each passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then takes the `topK × vectorIndexOverfetch` passages nearest by that index (default 40 a hit), runs the same organization, record-scope and metadata `WHERE` over them, and ranks those in scope by their stored float32 vector; its ranks feed the reciprocal rank fusion with the keyword leg as the exact scan's did. A leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, runs again as the exact scan, so a narrow record scope or filter keeps its recall and a search never answers fewer hits than before. Measured at 200,000 passages of 1,536 dimensions: a search whose keyword leg matches nothing took 81 ms at p95 instead of 1,054 ms, with a recall@10 against the exact scan of 0.998 over 100 queries. - **Never over two organizations.** The candidates are ranked before the filter, so a generation holding passages of more than one organization (passages of none count as one) gets no index, and each search reads the organization index and takes the exact scan once a second organization's passage is written. -- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. A process reads the catalog for a generation's index once (two reads) and remembers the answer; at `vectorIndexThreshold: Infinity` it never does. +- **Built at the end of a complete build, never on a search.** `os knowledge rebuild`, a fingerprint change, the boot build and the daily reconcile all end in one. The side table is made empty, then filled 2,048 passages to a transaction before the generation is switched to (200,000 passages: 3 s, 54 MB). A source that grows past the threshold between builds keeps the exact scan until its next complete build. After that, each write of a passage also writes its one-bit vector. A database that refuses the one-bit vectors or the index's DDL gets no index, the build completes on the exact scan, and the adapter's health check names the source and the reason. A process reads the catalog for a generation's index once (two reads) and remembers the answer; at `vectorIndexThreshold: Infinity` a search never reads the catalog for an index. - **Names.** `knowledge__g-vec` (the side table), `…-org` (the organization index) and three `…-vec-*` triggers, dropped with the generation by a switch and by `dropSource`. An object under one of those names that the store did not make is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming it. - **Two new options**, on `KnowledgeTursoPlugin` and `TursoKnowledgeAdapter`: `vectorIndexThreshold` (`Infinity` never makes an index) and `vectorIndexOverfetch` (a whole number, 8 or more). Nothing to migrate: a store keeps the exact scan until its next complete build. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 509a76e95c8..98dd2c14707 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -61,7 +61,7 @@ The organization filter, the record scope (a passage's record, or a metadata val - **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". - **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. 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). +- **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). - **Never over two organizations.** The candidates are ranked over every passage of the table, so over two organizations' passages the candidates for one could all be the other's. So a generation whose passages belong to more than one organization (passages of none count as one more) gets no index, and every search reads the organization index (its least and greatest value, and whether a passage has none) and takes the exact scan as soon as a second organization's passage is written. It is decided on the source's passage table, the one the candidates are ranked over, not on the whole database; a hosted database holds one organization (cloud ADR-0114). - **Not libSQL's DiskANN index (`vector_top_k`).** Measured on the same 200,000 passages, it took 24 minutes and 2.2 GB to build (one-bit neighbours, at most 32 each; libSQL's defaults took 329 MB and 21.8 s for 1,000 vectors), and its recall@10 against the exact scan was 0.39 — no larger `k` raised it past 0.46; at 20,000 passages no setting tried passed 0.85. diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 222349a07f4..cda420edc0f 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1521,7 +1521,8 @@ describe('knowledge-turso approximate vector index: recall and options', () => { } expect(wanted).toBe(400); expect(found / wanted).toBeGreaterThanOrEqual(0.95); - }); + // Two builds of 2,000 passages: 1,017 ms locally, the same shape as the scoped case below (5,971 ms on CI). + }, 30_000); it('recall@10 stays 0.95 or more under a record scope that keeps 10%, 5% or 3% of the passages', async () => { const s = source('ann_scoped_recall'); @@ -1552,7 +1553,8 @@ describe('knowledge-turso approximate vector index: recall and options', () => { console.info(`scoped recall@10, ${share * 100}% in scope (${ids.length} passages): ${(found / wanted).toFixed(3)}`); expect(found / wanted, `recall@10 at a share of ${share}`).toBeGreaterThanOrEqual(0.95); } - }); + // Two builds of 2,000 passages: 1,384 ms locally, 5,971 ms on CI (Test Core), past the 5 s default. + }, 30_000); it('refuses a threshold below 1 and an over-fetch that is not a whole number of 8 or more', () => { const client = store.client();