Skip to content

Commit 80ddfb5

Browse files
perf(knowledge-turso): compute the keyword leg once a search; send a scope too narrow for the approximate pass straight to the exact scan (#38697)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Es8AjkqFCZ7RyXPBkdgAD3)_ Part of #38676 **Stacked on #38693.** The base is that PR's branch, so this diff shows only #38676's commit. After #38693 lands, main is merged in and the PR is retargeted to `main`. ## What changes `packages/plugins/knowledge-turso` only (`turso-adapter.ts`, `sql.ts`, tests, README). 1. **The keyword leg is computed once a search.** The first statement of a search computes it, as before. When the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered (`kw AS (SELECT … FROM json_each(?n))`) instead of matching up to 16 terms again. A statement binds only the shared values (query vector, scope and filter values, `topK`), the ranks, and its candidate count. 2. **A scope too narrow for the approximate pass goes straight to the exact scan, judged by its share of the rows.** Before, only a scope of record terms alone was checked (through the record index). Now a scope with a parent (metadata) term, or a metadata `filter`, has its share estimated by `scopeSampleSql`: 256 rows at evenly spread rowids, with `min(rowid)`/`max(rowid)` seeks for the bounds, so no pass over the table. The cut is the record scope's (`VECTOR_RECORD_SCOPE_POOL`: 25% of the passages at the default over-fetch of 40). **Not built here: cause 3, the question embedded again on the second round.** The adapter embeds once per `search()` call. The repeat comes from `service-knowledge`'s second `searchRound` calling `adapter.search` again. That file is held by #38660 and is outside this order's surface, so #38676 stays open for it (see the os-dev report on the card). ## Why Re-measured on #38693's head (d3c750a), on the same local corpus as #38693: a `file:` libSQL with 59,621 one-passage records, 1,024 dimensions, approximate index built, and the 16-term Chinese question. Total per search (statements): | Search, `topK` 40 | #38693 head | This PR | |---|---|---| | 3 policies (0.15%) | 190 ms (approx+kw 120, exact+kw 74) | 80 ms (sample 5, exact+kw 75) | | Leaf unit (1.7%) | 310–680 ms (approx+kw, wide+kw, exact+kw) | 150 ms (sample 5, exact+kw 145) | | Division (10%) | 570–700 ms (approx+kw 240, wide+kw 330–440) | 230–280 ms (sample 5, exact+kw 225–274) | | Root (100%) | 810–900 ms (approx+kw) | 820–880 ms (sample 5, approx+kw) | | No scope | 620–690 ms | 620–660 ms (unchanged path) | `topK` 8 shows the same pattern: the leaf unit went from 318–372 to 143–147 ms and the division from 227–507 to 210–214 ms. - Cause 1 held: every vector statement of one search carried the keyword CTE. - Cause 2 held: under a parent-term scope of 1.7% or 10%, the search ran 2–3 statements where 1 exact scan answered. - Cause 3: the adapter embedded once per call (31 embeds for 31 searches), so the repeat lives in the caller. ## Verification - **Pins**, all from plans and statement shape, none on wall-clock. With `turso-adapter.ts` and `sql.ts` reverted to #38693's head, 10 of 301 tests fail: - `scope-plan.test.ts`: across one search's statements, `MATERIALIZE cand` appears once, in the first. - `acceptance.test.ts` retry case, rewritten for the new routing: the wide pass and the exact scan after a short first pass bind the keyword ranks (`computed: 1, bound: 1`); a 1% scope goes exact alone; the sample's plan reads the table by `SEARCH` only, never `SCAN`; each pass binds exactly what it reads. - Filter, record-cut and termless cases: a parent term or filter under the cut now runs `{approximate: 0, exact: 1}`, and a parent-term scope over the cut still takes the first pass. - Hits still equal the exact-scan adapter's in every routed case (the existing `exact` twin comparisons). - `pnpm --filter @objectstack/knowledge-turso test`: 5 files, 301 tests pass. `pnpm typecheck` passes. eslint on the changed files is clean. `check:issue-citations`, `check:doc-authoring`, `check:objectql-double-limit`, `check:where-matcher` and `check:empty-changeset` exit 0. Clause-②: no Metadata-protocol: none ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran. eslint is clean on the changed files; the repo-wide `pnpm lint` was not run locally. - [x] 4. One issue, one branch, one pull request. It is stacked on #38693 by the seat's order. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [ ] The *Before Submitting* list in CONTRIBUTING.md is done. The full repo-wide suite was not run; CI runs it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2d6102c commit 80ddfb5

6 files changed

Lines changed: 175 additions & 59 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
---
4+
5+
perf(knowledge-turso): the keyword leg is computed once a search, and a scope too narrow for the approximate pass goes straight to the exact scan
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Before, every vector statement of one search carried the keyword leg. When the approximate pass fell short and a wider pass or the exact scan followed, the keyword terms (up to 16, the two-character ones matched by `LIKE` over every row in scope) were matched again in each statement. Only a scope of record ids alone was checked for being too narrow for the approximate pass. A scope with a parent (metadata) term or a metadata filter always took the one-bit pass first, then often a pass over 10 times the candidates, then the exact scan.
11+
12+
Now the first statement of a search computes the keyword leg, and a statement after it binds the ranks the first one answered. A scope with a parent term, or a metadata filter, has its share of the passages estimated from 256 rows of the table, read by rowid (no pass over the table). Under the same cut as a record scope (25% of the passages at the default over-fetch), it goes straight to the exact scan. On 59,621 one-passage records of 1,024 dimensions (`topK` 40, a 16-term Chinese question), a search scoped to 3 policies took about 80 ms instead of 190 ms, one scoped to a unit holding 1.7% of the passages about 150 ms instead of 310 to 680 ms, and one holding 10% about 240 ms instead of 570 to 700 ms. The hits are those of the exact scan, as before.
13+
14+
The question is still embedded once per call to the adapter. The knowledge service's second round makes a second call, so it embeds the question again.

‎packages/plugins/knowledge-turso/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,10 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge
5555
- **Keyword index.** Each passage table `knowledge_<source>_g<n>` 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.
5656
- **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.
5757

58-
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. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks.
58+
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. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. And the keyword leg is computed once a search: when the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered.
5959

6060
- **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.
61-
- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope, and when it keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages, estimated from the passages of at most 256 of its ids), it skips the first pass too and goes straight to the exact scan: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there".
61+
- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope. Any scope, or a metadata `filter`, that keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages) skips the first pass too and goes straight to the exact scan. A scope of record terms alone is estimated from the passages of at most 256 of its ids, counted through the record index; any other is estimated from 256 rows of the table at evenly spread rowids, read by key: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there".
6262
- **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.
6363
- **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.
6464
- **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).

0 commit comments

Comments
 (0)