Skip to content

Commit e9002d6

Browse files
perf(knowledge-turso): a narrow record-only scope goes straight to the exact scan (#38327)
Fixes #38215 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:托管版大知识源上,只按具体记录限定、且只覆盖不到四分之一内容的检索,直接逐条比对,不再先跑一遍近似检索;实测在 5% 到 20% 范围内从约 0.22 到 0.42 秒降到约 0.07 到 0.29 秒;范围更宽的检索和按上级记录限定的检索保持原样。 - 为什么做:属于"云上知识库(Turso)"主线,替权限范围窄的用户提速;上一张提速卡的实测发现了这处多余的开销,席位据此单独立了这张卡。 - 出错会怎样:最坏是分界判断偏了,某次检索走了较慢的一条路,结果不变、只是慢一些;召回率在每个实测范围都不低于原来;改动可以直接撤回,无需迁移。 - 要你做的:无。 ## What changes `TursoKnowledgeAdapter.search`, the vector leg on a generation that has the approximate index (`packages/plugins/knowledge-turso/src/turso-adapter.ts`). Today a scope of record terms alone (no parent term) always runs the one-bit pass first. When that pass keeps fewer than 8 x `topK` candidates in scope, the exact scan runs after it. Since the record index lets the exact scan read only the rows in scope, a narrow record scope pays for both. Now such a scope is estimated first. If the first pass's `topK x vectorIndexOverfetch` candidates are not expected to keep 1.25 x the floor in scope (`VECTOR_RECORD_SCOPE_POOL`, not exported), the search goes straight to the exact scan. With the default over-fetch of 40, that means a scope of under 25% of the source's passages. - **The estimate counts passages, not ids.** One statement reads the table's passage count and, through the record index, the passages of at most 256 of the scope's ids (`VECTOR_SCOPE_SAMPLE`), spread evenly over the terms. A scope of 256 ids or fewer is counted exactly. A record split into many passages counts as many, and an id that names no passage counts as none. It costs about 2 ms at 200,000 passages (p50 1-2 ms on the bench). - **Unchanged:** a scope with a parent (`metadata`) term, a search with no scope, and the whole of #38229's path (first pass, second pass, exact). Wider record scopes keep the first pass and its exact fallback. No option, export or stored shape changes. - The jsdoc of the constant, the class's Search section and the README state the rule and the numbers that placed it. ## Tests `src/__tests__/acceptance.test.ts` adds one case, run on each store kind. The corpus is 400 passages: records 000 to 039 hold five passages each, and records 040 to 239 hold one each. `topK` is 2 with the default over-fetch: 80 candidates, a floor of 16, and a cut-over of 100 passages. Every scope's hits equal the exact scan's. - 99 passages in scope: `{ approximate: 0, exact: 1 }`. 100 passages: `{ approximate: 1, exact: 0 }`. These two pin the cut-over exactly. - 20 records holding 100 passages take the first pass: the estimate counts passages, not ids. - Two record terms with an id in common (80 passages): the exact scan alone. - 340 ids, of which only 40 name a record of the source: sampled (256 of 340), estimated at about 40 passages, the exact scan alone. - The same narrow records beside a parent term: the approximate pass, as before. - The count statement binds only its sample, one value. Three existing pins move with the new path: - The over-fetch case: its over-fetch goes from 10 to 20. At 10, the expected pool of 58 of 60 passages is only 1.2 x the floor. Its narrow record scope now expects `{ approximate: 0, exact: 1 }`. - The retry case: its record-only control now expects `{ approximate: 0, exact: 1 }`. At over-fetch 8, no record scope can be expected to reach 1.25 x the floor. - The term-less binding case: it now runs a record-plus-parent scope (both approximate passes and the exact scan) and a record-only scope (the exact scan alone), so every statement kind is still checked to bind exactly what it reads. **Ablation** (on disk, through `scripts/ablation-replace.mjs`): the direct-exact `if` is replaced by `if (false)`. Result: `Tests 2 failed | 128 skipped`. The new case fails on both store kinds: at 99 passages it reads `{ approximate: 1, exact: 0 }` instead of `{ approximate: 0, exact: 1 }`. The file was restored to blob `ff1f06686b`, equal to `HEAD:`, with `git diff HEAD` empty. <details><summary>Local runs on the final head</summary> All test runs went through `os-verify-lock`. - **Code head `eefc6556905`** (`VERDICT command-exit 0`, held 329 s, shared box): - `pnpm --filter @objectstack/knowledge-turso test`: exit 0, `Test Files 4 passed (4)`, `Tests 280 passed (280)`. - `typecheck`: exit 0. `check:test-typecheck` is OK (0 errors). - `build`: exit 0, with `check-dts-emitted` 2/2. - The ablation leg and the bench above ran in the same hold. - **Final head `f041d0a8985`** (README and changeset only on top of `eefc6556905`): `dispatch-gates --commands --repo objectstack-ai/objectstack` derived 67 commands, all run on this head. - 66 exited 0, including `check:type-check-debt` (re-measured, 0 errors) and `check:query-options-erasure`. - `check:dual-build-cjs-loads` exited 3 (`PREREQUISITE NOT MET`: about 60 packages have no `dist` in this worktree, so it needs a whole-repo build). It is left to CI. - Reconciled with `--ran` (exit codes recorded): `67 derived, 66 run, 1 NOT-MEASURED, 0 UNRUN`. - Closure build `pnpm --filter '@objectstack/knowledge-turso^...' build`: `VERDICT command-exit 0`. - `test:repo` was not run locally (CI's `Test Core`). The diff touches no repo-project test. </details> ## Acceptance notes **Real-store bench.** 200,000 passages of 1,536 dimensions, clustered synthetic (the #38066 bench data: latent 384, 200 clusters, sigma 1.0, one passage per record). The `file:` store was built through the adapter: upsert 171 s, `completeBuild` with the one-bit index 7.0 s. - Each share ran 50 vector-only queries at `topK` 10, with record-only scopes drawn at random. - In one process, each query ran three adapters in turn: the exact scan (`vectorIndexThreshold: Infinity`, also the recall truth), then origin/main's adapter (`today`) and this head (`head`), those two alternating which goes first. - Everything ran under `os-verify-lock` on a shared box (load about 6 to 8 on 4 cores), so compare within a row, not across runs. | Record scope | ids in scope | Exact scan p95 | today p95 | **head p95** | today: queries taking the one-bit pass / the exact scan after it | recall@10 today / head | |---|---|---|---|---|---|---| | 5% | 10,037 | 81 ms | 219 ms | **74 ms** | 100% / 100% | 1.000 / 1.000 | | 10% | 20,143 | 154 ms | 321 ms | **143 ms** | 100% / 100% | 1.000 / 1.000 | | 20% | 40,247 | 291 ms | 418 ms | **289 ms** | 100% / 48% | 0.994 / 1.000 | | 25% | 50,331 | 346 ms | 190 ms | 206 ms | 100% / 2% | 0.982 / 0.982 | | 30% | 59,922 | 389 ms | 187 ms | 204 ms | 100% / 0% | 0.998 / 0.998 | | 35% | 70,267 | 451 ms | 206 ms | 207 ms | 100% / 0% | 0.992 / 0.992 | | 50% | 99,938 | 671 ms | 223 ms | 228 ms | 100% / 0% | 0.996 / 0.996 | At 5% to 20%, head runs the exact scan alone (0% of queries take the one-bit pass). At 25% and wider it takes today's path (100% take the pass, with the same exact fallback share). The head column was measured on `eefc6556905`; `f041d0a8985` changes only the README and the changeset. - **Where the cut-over sits, and why.** today's p95 is above the exact scan's while a large share of the queries pay for both passes, and below it once nearly none do. At 20% in scope, 48% of the queries ran both passes, and the exact scan wins. At 25%, 2% did, and today's path wins. The floor of 80 candidates in scope is the expected pool of the 400 candidates at 20%. So the cut-over is 1.25 x that floor, which is 25% at the default over-fetch. The earlier run that placed it, with this head's branch ablated on disk, measured p95 exact / today: 20% 228 / 373 ms, 25% 308 / 200 ms. - **Above the cut-over**, this head takes today's path plus the count statement (p50 1-2 ms, p95 2 ms). Its p95 reads +16, +17, +1 and +5 ms above today's at 25%, 30%, 35% and 50%. Read strictly, the acceptance line "no worse than the better of the two" is therefore not met at 25% and 30% in this run. The gap is not the new statement: at those two shares, the identical one-bit statement's own p95 differs between the two adapters by 14 and 15 ms (head 196 / 199 ms, today 182 / 184 ms). That is the run-to-run spread of one SQL statement on this shared box. - **Ablation pin on the bench.** With the direct-exact branch ablated on disk, the narrow shares go back to today's path: p95 212, 293 and 409 ms at 5%, 10% and 20% (today in the interleaved run: 219, 321 and 418). Every query ran the one-bit pass, and 100%, 100% and 48% ran the exact scan after it. - **Caveats.** - Synthetic vectors, one passage per record. The unit case covers records of many passages and ids absent from the source. - The bench is a scratch script and is not committed. Rebuilding it takes `gen.py` (5 s) plus a 200,000-passage build (about 3 min). - A record scope from the knowledge service holds at most 500 visible ids, or 10 x 500 of the caller's own. At 200,000 passages that is a narrow share, which now always takes the exact scan. - **The existing scoped-recall case** (record scopes of 10%, 5% and 3% of 2,000 passages) now runs the exact scan, so it pins recall 1.0 there rather than the one-bit pass's. Approximate recall under a narrow scope is still pinned under a parent scope by #38229's case. - **Out of scope, noted:** none. ## Verification Read first, by risk: 1. `turso-adapter.ts`, `recordScopeUnderCut`: the even sample over the terms, the count statement, and the comparison of `inScope x overfetch` against `1.25 x 8 x n`. 2. `turso-adapter.ts`, `searchAttempt`: the direct-exact `if`. It sits after `approximateSearchable` and before the first approximate statement, and it is gated by `recordScope`. 3. `acceptance.test.ts`: the new case's fixture (which records hold five passages) and the 99 / 100 boundary. Two-minute check: ``` pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "goes straight to the exact scan" ``` Expected: 2 passed, one per store kind. Then replace the direct-exact `if (recordScope && ...)` in `searchAttempt` with `if (false)` and run it again. Both turn red: `{ approximate: 1, exact: 0 }` instead of `{ approximate: 0, exact: 1 }`. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 783a569 commit e9002d6

4 files changed

Lines changed: 146 additions & 11 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
---
4+
5+
perf(knowledge-turso): a narrow record-only scope goes straight to the exact scan
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A vector search whose scope is record ids alone (no parent term) ran the approximate one-bit pass first, then the exact scan whenever the pass kept too few candidates in scope. Since the record index lets that exact scan read only the rows in scope, a narrow scope paid for both. The adapter now estimates how many passages such a scope keeps and goes straight to the exact scan when the first pass's `topK × vectorIndexOverfetch` candidates are not expected to keep 1.25 × the floor of 8 × `topK` in scope. With the default 40 candidates a hit, that is a scope of under 25% of the source's passages. The estimate counts, through the record index, the passages of at most 256 of the scope's ids (all of them when there are no more), so a record split into many passages counts as many. It costs one statement of about 1-2 ms at 200,000 passages.
11+
12+
Measured at 200,000 passages of 1,536 dimensions (clustered, topK 10, 50 record-scoped queries a share), p95 in ms before → after: 5% in scope 219 → 74, 10% 321 → 143, 20% 418 → 289 (the exact scan alone: 81, 154, 291); at 25%, 30%, 35% and 50% the path is unchanged (190 → 206, 187 → 204, 206 → 207, 223 → 228, the one added statement costing 1-2 ms). Recall@10 against the exact scan is equal or higher at every share (0.994 → 1.000 at 20%). A scope with a parent (metadata) term and a search with no scope keep the approximate path, the second pass included. Nothing to configure or migrate.

‎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. 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".
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".
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: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1288,21 +1288,22 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
12881288
...Array.from({ length: 6 }, (_, i) => doc(t, `second_${i}`, `${QUERY} w${i + 5}x`)),
12891289
...wordsOf(52, 11).map((text, i) => doc(t, `rest_${String(i).padStart(2, '0')}`, `w1x ${text}`)),
12901290
];
1291-
const over = await built(t, tiers, { vectorIndexOverfetch: 10 });
1292-
// Every passage but the two best in scope: 18 or more of the 2 × 10 candidates are left, 8 × topK
1291+
const over = await built(t, tiers, { vectorIndexOverfetch: 20 });
1292+
// Every passage but the two best in scope: 38 or more of the 2 × 20 candidates are left, 8 × topK
12931293
// and more, so the candidates answer, without the exact scan.
12941294
from = over.sql.length;
12951295
const allButBest = tiers.flatMap((d) => d.sourceRecordId ?? []).filter((id) => !id.startsWith('best_'));
12961296
const wide = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: allButBest }] });
12971297
expect(wide).toHaveLength(2);
12981298
for (const hit of wide) expect(hit.sourceRecordId).toMatch(/^second_/);
12991299
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 0 });
1300-
// Two passages in scope: at most 2 of the 20 candidates, fewer than 8 × topK, so the exact scan answers.
1300+
// Two passages in scope: at most 2 of the 40 candidates, fewer than 8 × topK, so the exact scan
1301+
// answers; a scope of records alone that narrow goes to it without the one-bit pass.
13011302
from = over.sql.length;
13021303
const scoped = ['second_1', 'second_4'];
13031304
const narrow = await over.adapter.search(QUERY, { source: t, topK: 2, scope: [{ kind: 'record', ids: scoped }] });
13041305
expect(narrow.map((h) => h.sourceRecordId).sort()).toEqual(scoped);
1305-
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 1, exact: 1 });
1306+
expect(vectorLegs(over.sql, from)).toEqual({ approximate: 0, exact: 1 });
13061307
});
13071308

13081309
it('a leg under 8 × topK in scope tries 10 × the candidates once before the exact scan, unless its pool is too thin or its scope is of records alone', async () => {
@@ -1353,16 +1354,67 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
13531354
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });
13541355

13551356
// 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+
// rows in scope, so there is no second pass, and at 8 candidates a hit no first one either: no share
1358+
// of the passages lets the 16 candidates be expected to keep 1.25 × the floor of 16.
13571359
const records = corpus(s)
13581360
.filter((d) => (d.metadata?.tags as string[] | undefined)?.includes('wide'))
13591361
.flatMap((d) => d.sourceRecordId ?? []);
13601362
({ hits, from } = await search([{ kind: 'record', ids: records }]));
13611363
expect(ids(hits)).toEqual(['best_1', 'best_2']);
1362-
expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 });
1364+
expect(vectorLegs(sql, from)).toEqual({ approximate: 0, exact: 1 });
13631365
// Two builds of 400 passages on each store kind: past vitest's 5 s default on a loaded CI box.
13641366
}, 30_000);
13651367

1368+
it('a scope of record terms alone that keeps under 25% of the passages goes straight to the exact scan; a wider one, or one with a parent term, takes the approximate pass', async () => {
1369+
const QUERY = 'w1x w2x w3x';
1370+
// 400 passages: records 000…039 hold five passages each, 040…239 one each.
1371+
const corpus = (s: KnowledgeSource) =>
1372+
wordsOf(240, 13).map((text, i) => {
1373+
const n = String(i).padStart(3, '0');
1374+
const d = doc(s, n, text);
1375+
if (i >= 40) return d;
1376+
return { ...d, chunks: [0, 1, 2, 3, 4].map((index) => ({ id: `${d.id}#${index}`, documentId: d.id, index, content: `${text} wz${index}x` })) };
1377+
});
1378+
const s = source('ann_record_cut');
1379+
// topK 2 and the default 40 candidates a hit: 80 candidates, a floor of 16. The first pass is taken
1380+
// when it is expected to keep 1.25 × that floor, 20 of the 80: 25% of the passages, 100 of 400.
1381+
const { adapter, sql, args } = await built(s, corpus(s));
1382+
const t = source('ann_record_cut_exact');
1383+
const exact = await built(t, corpus(t), { vectorIndexThreshold: Infinity });
1384+
const records = (from: number, to: number) => Array.from({ length: to - from }, (_, i) => String(from + i).padStart(3, '0'));
1385+
const search = async (scope: NonNullable<Parameters<TursoKnowledgeAdapter['search']>[1]['scope']>) => {
1386+
const from = sql.length;
1387+
const hits = await adapter.search(QUERY, { source: s, topK: 2, scope });
1388+
const want = await exact.adapter.search(QUERY, { source: t, topK: 2, scope });
1389+
// The passages the exact scan ranks, by record and passage: the two sources' chunk ids differ by their name.
1390+
const passages = (found: typeof hits) => found.map((h) => h.chunkId.slice(h.chunkId.indexOf(':')));
1391+
expect(passages(hits)).toEqual(passages(want));
1392+
return vectorLegs(sql, from);
1393+
};
1394+
1395+
// 99 passages in scope (records 141…239), under the cut: the exact scan alone, no one-bit pass.
1396+
expect(await search([{ kind: 'record', ids: records(141, 240) }])).toEqual({ approximate: 0, exact: 1 });
1397+
// 100 (records 140…239): the first pass, which keeps about 20 of its 80 candidates, and answers.
1398+
expect(await search([{ kind: 'record', ids: records(140, 240) }])).toEqual({ approximate: 1, exact: 0 });
1399+
// The passages in scope are counted, not the ids: 20 records holding 100 passages take the first pass
1400+
// (whose pool of near-duplicate passages may then fall short, and the exact scan follow).
1401+
expect((await search([{ kind: 'record', ids: records(0, 20) }])).approximate).toBe(1);
1402+
// Two terms of 40 records each, one id in both: 80 passages, under the cut.
1403+
expect(await search([{ kind: 'record', ids: records(100, 140) }, { kind: 'record', ids: records(139, 180) }])).toEqual({ approximate: 0, exact: 1 });
1404+
// 340 ids, of which only the last 40 name a record of this source: estimated from 256 of them,
1405+
// spread over the 340, as about 40 passages, so the exact scan alone.
1406+
const absent = Array.from({ length: 300 }, (_, i) => `gone_${i}`);
1407+
expect(await search([{ kind: 'record', ids: [...absent, ...records(200, 240)] }])).toEqual({ approximate: 0, exact: 1 });
1408+
// The narrow records beside a parent (metadata) term: the record index does not serve that scan, so
1409+
// the approximate pass runs as before, here answering from its first pool.
1410+
expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 1, exact: 0 });
1411+
// The count of the passages in scope binds the scope's ids alone, term by term.
1412+
const counts = sql.flatMap((q, i) => (!q.includes('vec AS (') && q.includes('source_record_id IN (SELECT value FROM json_each(?1))') ? [args[i]] : []));
1413+
expect(counts.map((bound) => bound.length)).toEqual([1, 1, 1, 1, 1]);
1414+
expect(JSON.parse(String(counts[3][0]))).toEqual([...records(100, 140), ...records(139, 180)]);
1415+
expect(JSON.parse(String(counts[4][0]))).toHaveLength(256);
1416+
}, 30_000);
1417+
13661418
it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => {
13671419
const s = source('ann_life');
13681420
const { adapter, client, sql } = await built(s, corpus(s, 60));
@@ -1492,13 +1544,15 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
14921544
await adapter.completeBuild(ctx(s));
14931545
expect(keywordTerms('?! …')).toEqual([]);
14941546
const from = watched.sql.length;
1495-
// Answered through the index; then a scope of its two hits, under the floor, runs both statements.
1547+
// Answered through the index; then a scope of its two records beside a parent term, under the
1548+
// floor, runs both approximate passes and the exact scan, and the two records alone the exact scan.
14961549
const hits = await adapter.search('?! …', { source: s, topK: 2 });
14971550
expect(hits).toHaveLength(2);
14981551
const ids = hits.flatMap((h) => h.sourceRecordId ?? []);
1552+
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }, { kind: 'metadata', field: 'status', ids: ['none'] }] })).toHaveLength(2);
14991553
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }] })).toHaveLength(2);
15001554
const statements = vectorStatements(watched, from);
1501-
expect(statements.map((st) => st.approximate)).toEqual([true, true, false]);
1555+
expect(statements.map((st) => st.approximate)).toEqual([true, true, true, false, false]);
15021556
for (const st of statements) expect(st).toMatchObject({ reads: st.bound });
15031557
});
15041558

0 commit comments

Comments
 (0)