Skip to content

Commit fccb36c

Browse files
committed
wip(knowledge-turso): estimate a record scope's passages from a sample of its ids; tests
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
1 parent 5caac29 commit fccb36c

2 files changed

Lines changed: 109 additions & 32 deletions

File tree

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

Lines changed: 54 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,59 @@ 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+
expect(hits.map((h) => h.chunkId)).toEqual(want.map((h) => h.chunkId));
1390+
return vectorLegs(sql, from);
1391+
};
1392+
1393+
// 99 passages in scope (records 141…239), under the cut: the exact scan alone, no one-bit pass.
1394+
expect(await search([{ kind: 'record', ids: records(141, 240) }])).toEqual({ approximate: 0, exact: 1 });
1395+
// 100 (records 140…239): the first pass, which keeps about 20 of its 80 candidates, and answers.
1396+
expect(await search([{ kind: 'record', ids: records(140, 240) }])).toEqual({ approximate: 1, exact: 0 });
1397+
// The passages in scope are counted, not the ids: 20 records holding 100 passages take the first pass.
1398+
expect(await search([{ kind: 'record', ids: records(0, 20) }])).toEqual({ approximate: 1, exact: 0 });
1399+
// Two terms of 40 records each, one id in both: 80 passages, under the cut.
1400+
expect(await search([{ kind: 'record', ids: records(100, 140) }, { kind: 'record', ids: records(139, 180) }])).toEqual({ approximate: 0, exact: 1 });
1401+
// The narrow records beside a parent (metadata) term: the record index does not serve that scan, so
1402+
// the approximate passes run as before (a thin first pool, then the wider pass, which answers).
1403+
expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 2, exact: 0 });
1404+
// The count of the passages in scope binds the scope's ids alone, each once.
1405+
const counts = sql.flatMap((q, i) => (!q.includes('vec AS (') && q.includes('source_record_id IN (SELECT value FROM json_each(?1))') ? [args[i]] : []));
1406+
expect(counts.map((bound) => bound.length)).toEqual([1, 1, 1, 1]);
1407+
expect(JSON.parse(String(counts[3][0]))).toEqual(records(100, 180));
1408+
}, 30_000);
1409+
13661410
it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => {
13671411
const s = source('ann_life');
13681412
const { adapter, client, sql } = await built(s, corpus(s, 60));
@@ -1492,13 +1536,15 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
14921536
await adapter.completeBuild(ctx(s));
14931537
expect(keywordTerms('?! …')).toEqual([]);
14941538
const from = watched.sql.length;
1495-
// Answered through the index; then a scope of its two hits, under the floor, runs both statements.
1539+
// Answered through the index; then a scope of its two records beside a parent term, under the
1540+
// floor, runs both approximate passes and the exact scan, and the two records alone the exact scan.
14961541
const hits = await adapter.search('?! …', { source: s, topK: 2 });
14971542
expect(hits).toHaveLength(2);
14981543
const ids = hits.flatMap((h) => h.sourceRecordId ?? []);
1544+
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }, { kind: 'metadata', field: 'status', ids: ['none'] }] })).toHaveLength(2);
14991545
expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }] })).toHaveLength(2);
15001546
const statements = vectorStatements(watched, from);
1501-
expect(statements.map((st) => st.approximate)).toEqual([true, true, false]);
1547+
expect(statements.map((st) => st.approximate)).toEqual([true, true, true, false, false]);
15021548
for (const st of statements) expect(st).toMatchObject({ reads: st.bound });
15031549
});
15041550

‎packages/plugins/knowledge-turso/src/turso-adapter.ts‎

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -151,15 +151,22 @@ const VECTOR_RETRY_POOL = 10;
151151
/**
152152
* How many times the floor ({@link VECTOR_MIN_POOL} × topK) the first
153153
* approximate pass must be expected to keep in scope for a scope of record
154-
* terms alone to take that pass: the `topK × vectorIndexOverfetch`
155-
* candidates times the share of the passages in scope, which a count of the
156-
* rows in scope, served by the record index and stopped at the cut-over,
157-
* reads. A narrower scope goes straight to the exact scan, which the record
158-
* index serves from the rows in scope: the one-bit pass, which reads every
159-
* row of the table, would mostly leave a pool under the floor and be followed
160-
* by that scan anyway. PLACEHOLDER — placed by the bench.
154+
* terms alone to take it: its `topK × vectorIndexOverfetch` candidates times
155+
* the share of the passages in scope. A narrower scope goes straight to the
156+
* exact scan, which the record index serves from the rows in scope; the
157+
* one-bit pass reads every row of the table, and under such a scope it often
158+
* leaves a pool under the floor, so the exact scan follows it anyway. With
159+
* the default 40 candidates a hit, the cut-over is 25% of the passages in
160+
* scope. Measured at 200,000 passages of 1,536 dimensions (clustered, topK
161+
* 10), 50 queries a share, the p95 of the exact scan and of the search
162+
* through the one-bit pass first: at 20% in scope 228 and 373 ms (48% of the
163+
* queries ran both), at 25% 308 and 200 ms (2% ran both), at 10% 133 and
164+
* 282, at 35% 435 and 188, at 50% 689 and 221.
161165
*/
162-
const VECTOR_RECORD_SCOPE_POOL = 1.5;
166+
const VECTOR_RECORD_SCOPE_POOL = 1.25;
167+
168+
/** At most how many of a record scope's ids the estimate of its passages counts ({@link VECTOR_RECORD_SCOPE_POOL}). */
169+
const VECTOR_SCOPE_SAMPLE = 256;
163170

164171
/** 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. */
165172
const VECTOR_BACKFILL_BATCH = 2048;
@@ -322,7 +329,9 @@ function withTimeout<T>(work: Promise<T>, ms: number, commit = false): Promise<T
322329
* `topK` hits, is run once more over {@link VECTOR_RETRY_POOL} times the
323330
* candidates when its pool says that can clear the floor and its scope is
324331
* not of record terms alone, and is run again exactly otherwise, or when
325-
* that pass falls short too.
332+
* that pass falls short too. A scope of record terms alone that keeps too
333+
* few passages for the first pass to be expected to clear the floor
334+
* ({@link VECTOR_RECORD_SCOPE_POOL}) goes straight to the exact scan.
326335
* - The keyword leg: the query's terms ({@link keywordTerms}). A term of three
327336
* characters or more is matched as one FTS5 phrase in the passage table's
328337
* trigram index (so `X-200` is a phrase, never FTS5 syntax); a shorter one
@@ -708,6 +717,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
708717
const where: string[] = [];
709718
// Whether the record index can serve the exact scan: a scope of record terms alone.
710719
let recordScope = false;
720+
// The ids of the scope's record terms, each once.
721+
const recordIds = new Set<string>();
711722
if (opts.organizationIds !== undefined) {
712723
args.push(JSON.stringify(opts.organizationIds));
713724
where.push(`organization_id IN (SELECT value FROM json_each(?${args.length}))`);
@@ -727,6 +738,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
727738
const ids = `(SELECT value FROM json_each(?${args.length}))`;
728739
if (term.kind === 'record') {
729740
scopeTerms.push(`source_record_id IN ${ids}`);
741+
for (const id of term.ids) recordIds.add(id);
730742
continue;
731743
}
732744
parentTerm = true;
@@ -825,21 +837,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
825837
const instance = now.active.createdAt;
826838
if (vectorLeg && (await this.approximateSearchable(tableName, instance))) {
827839
const candidates = topK * this.vectorIndexOverfetch;
828-
// A scope of record terms alone too narrow for the first pass to be
829-
// expected to clear the floor (VECTOR_RECORD_SCOPE_POOL) goes straight
830-
// to the exact scan, which the record index serves from the rows in
831-
// scope. The count reads those rows' index entries, at most up to the cut-over.
832-
if (recordScope) {
833-
const cut = (VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL) / this.vectorIndexOverfetch;
834-
const counted = await client.execute({
835-
sql: `WITH total AS (SELECT count(*) AS n FROM ${table})
836-
SELECT n, (SELECT count(*) FROM (SELECT 1 FROM ${table} WHERE ${inScope}
837-
LIMIT (SELECT CAST(n * ?${args.length + 1} AS INTEGER) + 1 FROM total))) AS k FROM total`,
838-
args: [...args, cut] as InArgs,
839-
});
840-
const { n, k } = counted.rows[0];
841-
if (Number(k) < Number(n) * cut) return client.execute(statement());
842-
}
840+
// A scope of record terms alone that the first pass is not expected
841+
// to answer goes straight to the exact scan, which the record index
842+
// serves from the rows in scope.
843+
if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordIds))) return client.execute(statement());
843844
// A failed approximate statement (its index gone under this process's
844845
// memory of it) forgets that memory and is answered by the exact scan.
845846
const approximate = (candidates: number) =>
@@ -1268,6 +1269,36 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
12681269
return (await this.organizationsIn(client, table)) <= 1;
12691270
}
12701271

1272+
/**
1273+
* Whether a scope of record terms alone, of the distinct `recordIds`, keeps
1274+
* fewer of the passages of `table` than the first approximate pass needs to
1275+
* be expected to keep {@link VECTOR_RECORD_SCOPE_POOL} × the floor in scope:
1276+
* a share under that many times {@link VECTOR_MIN_POOL} /
1277+
* `vectorIndexOverfetch`. The passages in scope are estimated from those of
1278+
* at most {@link VECTOR_SCOPE_SAMPLE} of the ids, spread evenly over them,
1279+
* counted through the record index (exactly, for a scope of no more ids),
1280+
* so a record of many passages counts as many and an id of no passage as
1281+
* none. The organization and metadata filters are not counted: the exact
1282+
* scan reads every row the record index finds for the scope. Runs inside
1283+
* the client's queue.
1284+
*/
1285+
private async recordScopeUnderCut(db: Pick<Client, 'execute'>, table: string, recordIds: ReadonlySet<string>): Promise<boolean> {
1286+
const ids = [...recordIds];
1287+
const sample =
1288+
ids.length <= VECTOR_SCOPE_SAMPLE
1289+
? ids
1290+
: Array.from({ length: VECTOR_SCOPE_SAMPLE }, (_, i) => ids[Math.floor((i * ids.length) / VECTOR_SCOPE_SAMPLE)]);
1291+
const t = quoted(table);
1292+
const counted = await db.execute({
1293+
sql: `SELECT (SELECT count(*) FROM ${t}) AS n,
1294+
(SELECT count(*) FROM ${t} WHERE source_record_id IN (SELECT value FROM json_each(?1))) AS k`,
1295+
args: [JSON.stringify(sample)],
1296+
});
1297+
const n = Number(counted.rows[0].n);
1298+
const inScope = (Number(counted.rows[0].k) * ids.length) / Math.max(1, sample.length);
1299+
return inScope * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL * n;
1300+
}
1301+
12711302
/** Forgets what this process knew of the approximate vector index of every instance of the passage table `table`. */
12721303
private forgetVectorIndex(table: string): void {
12731304
const prefix = vectorIndexKey(table, '');

0 commit comments

Comments
 (0)