Skip to content

Commit 69bb8ae

Browse files
perf(knowledge-turso): a narrowly scoped vector search tries a wider approximate pass before the exact scan (#38229)
Fixes #38066 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:托管版大知识源上,按上级记录(例如某个客户名下)限定、只覆盖一到两成内容的检索,从约 0.9 秒降到约 0.35 秒;按具体记录限定的检索保持原样。 - 为什么做:属于“云上知识库(Turso)”主线,替检索范围窄的用户提速;席位已按实测把范围收窄到这一种限定方式。 - 出错会怎样:最坏是多做一次近似检索后照旧逐条比对,结果与以前一致、只慢约 0.2 秒;召回率实测与原规则相同;改动可以直接撤回,无需迁移。 - 要你做的:无。 ## What changes `TursoKnowledgeAdapter.search`, the approximate vector leg (`packages/plugins/knowledge-turso/src/turso-adapter.ts`). Today, the leg runs the exact scan when the filter leaves fewer than 8 x `topK` of its `topK x vectorIndexOverfetch` candidates in scope. Such a leg now first runs one more approximate pass over 10 times the candidates (`VECTOR_RETRY_POOL`, not exported), with the same `WHERE` and the same floor. It keeps that answer only if it clears the floor; otherwise the exact scan answers, as before. The second pass is tried only when both hold: - **The scope cannot use the record index.** That means no scope, or a scope with at least one parent (`metadata`) term. A scope of record terms alone keeps today's path, because since #38160 its exact scan reads only the rows in scope through the record index. This is the seat's ruling B on this card, comment 7236023531 (option A of os-dev-report 7235999186). The ruling also files a separate card for a narrow record-only scope that skips the one-bit pass; this PR does not touch that path. - **The first pool says the wider pass can clear the floor**, that is pool x 10 is at least 8 x `topK`. A scope too narrow for that goes to the exact scan without a pass that could not answer. A failed second statement is treated like a failed first one: the index memory is forgotten and the exact scan answers. No option, export or stored shape changes. The README Search section and the jsdoc carry the rule and the numbers. ## Tests `src/__tests__/acceptance.test.ts` gets a new case, run on each store kind, with an explicit 30 s timeout. The corpus is 400 passages with tag lists that a parent scope term matches; `topK` is 2 and over-fetch 8, so there are 16 candidates, a floor of 16 and 160 for the second pass. Every scope's hits equal the exact scan's. - `wide` (the 2 best plus half the far passages): `{ approximate: 2, exact: 0 }`. The bound candidate counts are `[16, 160]`, and each pass binds exactly the values it reads. - `short` (5 passages): `{ approximate: 2, exact: 1 }`. Both passes fall short, then the exact scan answers. - `thin` (one far passage): `{ approximate: 1, exact: 1 }`. The pool is too thin for a second pass. - **Record-only control** (the `wide` passages as record ids): `{ approximate: 1, exact: 1 }`. There is no second pass. The two existing pins that run a record scope under the floor, the over-fetch case and the term-less binding case, keep their expectations unchanged. That is the record-only path staying as it is. **Ablation**, an on-disk edit replacing the second pass's condition with `false`: `Tests 2 failed | 126 skipped` (the new case on both store kinds, `{ approximate: 1, exact: 1 }` instead of `{ approximate: 2, exact: 0 }`). The file was restored to a blob equal to `HEAD:` (`git hash-object` 5573a5c on both sides), with an empty `git status`. <details><summary>Local runs on the final head</summary> All ran on head `07a84d2e10` (origin/main `2d95781690` merged), under `os-verify-lock` (`VERDICT command-exit 0`, held 1,194 s). - **Typecheck:** `pnpm --filter @objectstack/knowledge-turso typecheck` exits 0. `check:test-typecheck` is OK (0 errors). - **Tests:** `pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2` exits 0, with `Test Files 4 passed (4)` and `Tests 278 passed (278)`. - **Derived gates:** `dispatch-gates --commands` derived 67 commands at `07a84d2e10`. 66 ran, and each exited 0. - `check:dual-build-cjs-loads` was left to CI. A first pass refused it with exit 3 (`PREREQUISITE NOT MET`: 60 packages have no `dist` in this worktree; it needs a whole-repo build). - Reconciled with `--ran`: `67 derived, 66 run, 0 NOT-MEASURED, 1 UNRUN`. The one UNRUN is that gate. - **Tests on `5447b42c76`:** the run there found a TS18048 in the new test's fixture (`d.metadata` possibly undefined). `07a84d2e10` fixes it. </details> ## Acceptance notes **Real-store bench, restated to the parent scope by the ruling.** 200,000 passages of 1,536 dimensions, clustered synthetic (the data model of `scoped-recall-floor8-retry-sim.py`: latent 384, 200 clusters, sigma 1.0). The `file:` store was built through the adapter: upsert 149 s, `completeBuild` with the one-bit index 8.1 s, 1.72 GB. - Each share ran 50 vector-only queries at `topK` 10. Each query was run by the exact scan (an adapter at `vectorIndexThreshold: Infinity`, which is also the recall truth) and by the adapter under test, interleaved. - The parent scope is one `metadata` term over a `bucket` key holding 10, 15 or 20 of 100 buckets. - "Floor 8" is this head with the second pass ablated on disk, which equals `main`'s rule. - Everything ran under `os-verify-lock` (`VERDICT command-exit 0`) on head 6c530b0; later commits change only a test line. The box was shared (load 1.6 to 3.3 on 4 cores), and each row's exact column is that same run's. | Parent scope | Exact scan p95 | Floor 8 p95 | Second pass p95 | recall@10, floor 8 / second pass | Sent exact, floor 8 / second pass | |---|---|---|---|---|---| | 10% | 810 / 848 ms | 947 ms | **351 ms** | 1.000 / 1.000 | 100% / 0% | | 15% | 824 / 907 ms | 948 ms | **328 ms** | 1.000 / 1.000 | 100% / 0% | | 20% | 910 / 908 ms | 974 ms | **337 ms** | 0.986 / 0.986 (worst 0.8 on both) | 44% / 0% | - The exact column gives two readings: the one from the floor-8 run, then the one from the second-pass run. - **Ablation pin on the bench.** With the second pass removed, the share of queries sent exact goes back up from 0% to 100%, 100% and 44%. - **Statement costs (p50):** the first one-bit pass (400 candidates) takes 115 to 119 ms, and the second (4,000) takes 168 to 175 ms. - **The recall at 20% is the first pass's.** The 56% of queries that clear the floor in the first pass are answered there, under both rules. The second pass answered the other 44% with the exact scan's top 10. **Record-scope control** (this head): the second pass never runs (0 of 150), and the path is the floor-8 rule. | Record scope | Exact scan p95 | This head p95 | Sent exact | |---|---|---|---| | 10% | 135 ms | 262 ms | 100% | | 15% | 177 ms | 345 ms | 98% | | 20% | 269 ms | 422 ms | 48% | Under a record scope, the ungated second pass measured 333, 313 and 407 ms p95 against 128, 207 and 265 ms for the exact scan (os-dev-report 7235999186). That is why the record-only path is left alone here. The floor-8 path's own excess over the exact scan in the table above belongs to the separate card the ruling files. - **Caveats.** - Synthetic vectors only, as in #38056. - The bench is a scratch script and is not committed. Its data was deleted after the run; rebuilding it is `gen.py` (5 s) plus a 200,000-passage build (about 160 s). - A hybrid query also re-runs its keyword leg in the second statement. This bench measured vector-only queries. - **Out of scope, noted:** none beyond the ruling's separate card. ## Verification Read first, by risk: 1. `turso-adapter.ts`, `searchAttempt`: the `recordScope` flag set in the scope loop, the `approximate` and `stands` closures, and the order first pass, second pass, exact. 2. `turso-adapter.ts`, `VECTOR_RETRY_POOL`: the gate: the first pool times `VECTOR_RETRY_POOL` is at least `VECTOR_MIN_POOL * topK`. 3. `acceptance.test.ts`, the fixture of the new case: which tags hold which passages. Two-minute check: ``` pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "tries 10" ``` Expected: 2 passed, one per store kind. Then, in `searchAttempt`, replace the whole condition of the `if` that guards `approximate(candidates * VECTOR_RETRY_POOL)` with `false` and run it again: both turn red with `{ approximate: 1, exact: 1 }`. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent bd5407e commit 69bb8ae

4 files changed

Lines changed: 137 additions & 20 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
---
4+
5+
perf(knowledge-turso): a narrowly scoped vector search tries a wider approximate pass before the exact scan
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The approximate vector leg runs the exact scan when its filter leaves fewer than 8 × `topK` candidates in scope. A search whose scope keeps a fifth of the passages or less hit that floor almost every time and paid the full exact scan. Such a leg now first reads 10 times the candidates once, with the same `WHERE` and the same floor. It keeps that answer only if it clears the floor, and otherwise runs the exact scan as before.
11+
12+
- **Where it runs.** With no scope, or a scope that holds a parent (metadata) term. A scope of record terms alone keeps the old path: its exact scan reads only the rows in scope through the record index, and that costs less than the wider pass.
13+
- **When it is skipped.** When the first pool, times 10, cannot reach the floor, for example a scope of one or two passages. Those go to the exact scan without the extra pass.
14+
- **Measured** at 200,000 passages of 1,536 dimensions (clustered synthetic, `topK` 10, 50 queries per share), under a parent scope keeping 10%, 15% and 20% of the passages: p95 351, 328 and 337 ms, against 848, 907 and 908 ms for the exact scan. recall@10 is the same as the floor's alone.
15+
16+
No option and no export changes, and there is nothing to migrate.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge
5858
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.
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. 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 goes straight to the exact scan after the first pass, since the record index reads only the rows in scope. So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there".
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).

‎packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1305,6 +1305,64 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
13051305
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 1 });
13061306
});
13071307

1308+
it('a leg under 8 × topK in scope tries 10 × the candidates once before the exact scan, unless its pool is too thin or its scope is of records alone', async () => {
1309+
const QUERY = 'w1x w2x w3x w4x';
1310+
// Two best passages, 30 next to them and 368 further away, each with a list of tags a parent
1311+
// (metadata) scope term matches: 'wide' holds the two best and half the far ones, 'short' the two
1312+
// best and 3 next ones, 'thin' one far passage.
1313+
const corpus = (s: KnowledgeSource) => [
1314+
...['best_1', 'best_2'].map((n) => doc(s, n, QUERY, { metadata: { tags: ['wide', 'short'] } })),
1315+
...Array.from({ length: 30 }, (_, i) =>
1316+
doc(s, `mid_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 20) + 5}x w${(i % 7) + 30}x`, { metadata: { tags: [i < 3 ? 'short' : 'out'] } }),
1317+
),
1318+
...wordsOf(368, 23).map((text, i) =>
1319+
doc(s, `rest_${String(i).padStart(3, '0')}`, `w1x ${text}`, { metadata: { tags: i % 2 === 0 ? ['wide'] : i === 1 ? ['out', 'thin'] : ['out'] } }),
1320+
),
1321+
];
1322+
const s = source('ann_retry');
1323+
// topK 2 and 8 candidates a hit: 16 candidates, a floor of 16, and 160 for the second pass.
1324+
const { adapter, sql, args } = await built(s, corpus(s), { vectorIndexOverfetch: 8 });
1325+
const t = source('ann_retry_exact');
1326+
const exact = await built(t, corpus(t), { vectorIndexThreshold: Infinity });
1327+
const ids = (hits: Array<{ sourceRecordId?: string }>) => hits.map((h) => h.sourceRecordId);
1328+
const tagged = (tag: string) => [{ kind: 'metadata' as const, field: 'tags', ids: [tag] }];
1329+
const search = async (scope: NonNullable<Parameters<TursoKnowledgeAdapter['search']>[1]['scope']>) => {
1330+
const from = sql.length;
1331+
const hits = await adapter.search(QUERY, { source: s, topK: 2, scope });
1332+
expect(ids(hits), JSON.stringify(scope).slice(0, 60)).toEqual(ids(await exact.adapter.search(QUERY, { source: t, topK: 2, scope })));
1333+
return { hits, from };
1334+
};
1335+
1336+
// 'wide': the first pass keeps the 2 best of its 16 candidates; 10 × a pool of 2 can reach 16, and the
1337+
// second pass keeps far more than 16 of its 160, so it answers, as the exact scan would, without it.
1338+
let { hits, from } = await search(tagged('wide'));
1339+
expect(ids(hits)).toEqual(['best_1', 'best_2']);
1340+
expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 0 });
1341+
expect(sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : []))).toEqual([16, 160]);
1342+
// Each pass binds exactly the values it reads, its candidate count last.
1343+
for (const st of vectorStatements({ sql, args }, from)) expect(st).toMatchObject({ reads: st.bound });
1344+
1345+
// 'short': five passages in scope, so both passes keep at most 5, and the exact scan answers after both.
1346+
({ from } = await search(tagged('short')));
1347+
expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 1 });
1348+
1349+
// 'thin': one far passage, no candidate of the first pass; 10 × 0 cannot reach 16, so there is no
1350+
// second pass.
1351+
({ hits, from } = await search(tagged('thin')));
1352+
expect(ids(hits)).toEqual(['rest_001']);
1353+
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });
1354+
1355+
// The 'wide' passages as a scope of records alone: the record index serves the exact scan from the
1356+
// rows in scope, so there is no second pass, whatever the first pool.
1357+
const records = corpus(s)
1358+
.filter((d) => (d.metadata?.tags as string[] | undefined)?.includes('wide'))
1359+
.flatMap((d) => d.sourceRecordId ?? []);
1360+
({ hits, from } = await search([{ kind: 'record', ids: records }]));
1361+
expect(ids(hits)).toEqual(['best_1', 'best_2']);
1362+
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });
1363+
// Two builds of 400 passages on each store kind: past vitest's 5 s default on a loaded CI box.
1364+
}, 30_000);
1365+
13081366
it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => {
13091367
const s = source('ann_life');
13101368
const { adapter, client, sql } = await built(s, corpus(s, 60));

0 commit comments

Comments
 (0)