diff --git a/.changeset/knowledge-turso-approximate-index.md b/.changeset/knowledge-turso-approximate-index.md new file mode 100644 index 00000000000..631bfccebf7 --- /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 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` 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/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 3cbdf5258a6..b5379b49b2d 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: 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 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 b2150448b3f..0bb613b16cb 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -738,7 +738,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 @@ -757,16 +758,36 @@ the `embedder` it is given), and answers a search by an exact scan. (`` 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 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. 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 + 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 + 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 + 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 + 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 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 @@ -1314,7 +1335,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 e0cbfccc38d..98dd2c14707 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` | `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 @@ -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 build's writes, listing and completion are refused `LOCK_CONFLICT` (409) and that build ends; a write outside a build under the replaced fingerprint is 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`, `…-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. A build of the source under way when it is dropped, in this process or another, is ended: its next write, listing or completion is refused `LOCK_CONFLICT` (409) and opens nothing, so the build never brings the source back. A build that begins after the drop builds the source from nothing. @@ -50,9 +53,19 @@ 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 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, 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. + +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__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 14cd3182ef6..cda420edc0f 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -1040,3 +1040,528 @@ 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 ranks + * the one-bit side table (`vector1bit`), the exact one does not. + */ +function recording(client: Client): { client: Client; sql: string[]; args: unknown[][] } { + const sql: string[] = []; + 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) { + 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, 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[]; 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 => + 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, args: watched.args, 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 (')); + const approximate = legs.filter((s) => s.includes('vector1bit(')).length; + return { approximate, exact: legs.length - approximate }; +} + +/** 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}-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 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(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); + 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 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. + 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' } })), + ]; + // 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' } }); + expect(drafts).toHaveLength(3); + for (const hit of drafts) expect(hit.metadata).toMatchObject({ status: 'draft' }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); + 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: 10 }); + // 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_')); + 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 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 }] }); + 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 () => { + 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(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 } }); + 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 '%-org'"); + 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(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 }); + }); + + 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`. + ['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); + 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); + // 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; + 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 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_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 }); + 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); + } + } + }); + + 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()); + 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: 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('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 }); + // 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([]); + 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('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); + 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()); + + 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(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)); + 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); + // 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'); + 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.flatMap((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); + } + // 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(); + const embedder = new FakeEmbedder(); + 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: 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 ac599acb64a..7f0faa54a43 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: 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; + 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..c34a9ba88bb 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, 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; /** @@ -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/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index fd3f5c345fb..de8dc32ea81 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -252,6 +252,130 @@ 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`: 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; + org: string; + triggers: [string, string, string]; +} { + return { + side: `${table}-vec`, + org: `${table}-org`, + triggers: [`${table}-vec-insert`, `${table}-vec-delete`, `${table}-vec-update`], + }; +} + +/** + * 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, org, triggers } = vectorIndexNames(table); + const t = quoted(table); + const s = quoted(side); + return [ + ...dropVectorIndexDdl(table).filter((statement) => !statement.includes(quoted(org))), + `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, vector1bit(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 = vector1bit(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, 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. */ +export function dropVectorIndexDdl(table: string): string[] { + const { side, org, triggers } = vectorIndexNames(table); + return [ + ...triggers.map((name) => `DROP TRIGGER IF EXISTS ${quoted(name)}`), + `DROP INDEX IF EXISTS ${quoted(org)}`, + `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 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 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, 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) 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) || + (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 || !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 34bcda2d6f0..e0b816b85d3 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,56 @@ 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 (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 + */ + 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 + * {@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; } +/** 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. 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_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. 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.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 = 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; + /** 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'; @@ -223,8 +278,15 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise(); /** Passage tables whose keyword index is known to be complete. */ private readonly keyed = 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. + */ + 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 + * {@link healthCheck} until a later build of the source makes it. + */ + private readonly vectorIndexRefused = new Map(); + private readonly vectorIndexThreshold: number; + private readonly vectorIndexOverfetch: number; constructor(opts: TursoKnowledgeAdapterOptions) { this.id = opts.id ?? 'turso'; @@ -319,6 +397,18 @@ 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 < VECTOR_MIN_POOL) { + throw new RangeError( + `knowledge-turso: vectorIndexOverfetch must be a whole number, ${VECTOR_MIN_POOL} or more, got ${String(overfetch)}`, + ); + } + this.vectorIndexOverfetch = overfetch; this.client = opts.client === undefined || opts.requestTimeoutMs === undefined ? opts.client @@ -621,16 +711,30 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const limit = `?${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 ( - 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})`); - legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec'); - } + // 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 (`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[] => { + // 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)} + 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) 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. @@ -662,20 +766,38 @@ 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 ${[...(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${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`, + 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); - return client.execute({ - sql: `WITH ${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, - }); + 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 + // 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)); }); if (result === undefined) { // Switched while the query was embedded: searched again, a bounded number of times. @@ -766,6 +888,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) => { @@ -836,6 +961,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return { commit: true, value: undefined }; }); if (legacy) this.noLegacy.add(sourceId); + this.vectorIndexRefused.delete(sourceId); }); } @@ -843,7 +969,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}`}` }; @@ -994,9 +1132,184 @@ 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.forgetVectorIndex(table); + } + + /** The shape of the vector index of the passage table `table` (`vectorIndexShape`). */ + private async vectorShapeOf(db: Pick, table: string): Promise { + 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, type 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`, 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 (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 + * 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, 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(); + 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 + * 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(); + // 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 = + 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); + // 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 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. + // 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))) { + this.vectorIndexRefused.set(sourceId, 'this database does not compute one-bit vectors (vector1bit)'); + return none(); + } + 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 (err) { + this.vectorIndexRefused.set(sourceId, `the database refused its DDL (${errorText(err)})`); + return none(); + } + if ((await this.vectorShapeOf(client, table)) !== 'complete') return none(); + } + return { target, table }; + }); + if (planned === undefined) return; + 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({ + 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; + 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) }; + }), + ).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) { + // 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; + } } /** The shape of the keyword index of the passage table `table` (`keywordIndexShape`). */ @@ -1085,8 +1398,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.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], @@ -1171,6 +1489,27 @@ 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 + * 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 @@ -1270,6 +1609,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, 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}', '${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