Skip to content

Commit eefc655

Browse files
committed
perf(knowledge-turso): sample a record scope's ids without a set of all of them
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
1 parent f041fa7 commit eefc655

3 files changed

Lines changed: 47 additions & 20 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: BENCH_TABLE. Recall@10 against the exact scan is equal or higher at every share. 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/src/__tests__/acceptance.test.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1401,13 +1401,18 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
14011401
expect((await search([{ kind: 'record', ids: records(0, 20) }])).approximate).toBe(1);
14021402
// Two terms of 40 records each, one id in both: 80 passages, under the cut.
14031403
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 });
14041408
// The narrow records beside a parent (metadata) term: the record index does not serve that scan, so
1405-
// the approximate passes run as before (a thin first pool, then the wider pass, which answers).
1406-
expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 2, exact: 0 });
1407-
// The count of the passages in scope binds the scope's ids alone, each once.
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.
14081412
const counts = sql.flatMap((q, i) => (!q.includes('vec AS (') && q.includes('source_record_id IN (SELECT value FROM json_each(?1))') ? [args[i]] : []));
1409-
expect(counts.map((bound) => bound.length)).toEqual([1, 1, 1, 1]);
1410-
expect(JSON.parse(String(counts[3][0]))).toEqual(records(100, 180));
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);
14111416
}, 30_000);
14121417

14131418
it('keeps the index in step with every write and removal; a generation swap and dropSource drop it whole', async () => {

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

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -717,8 +717,8 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
717717
const where: string[] = [];
718718
// Whether the record index can serve the exact scan: a scope of record terms alone.
719719
let recordScope = false;
720-
// The ids of the scope's record terms, each once.
721-
const recordIds = new Set<string>();
720+
// The ids of the scope's record terms, term by term.
721+
const recordTerms: string[][] = [];
722722
if (opts.organizationIds !== undefined) {
723723
args.push(JSON.stringify(opts.organizationIds));
724724
where.push(`organization_id IN (SELECT value FROM json_each(?${args.length}))`);
@@ -738,7 +738,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
738738
const ids = `(SELECT value FROM json_each(?${args.length}))`;
739739
if (term.kind === 'record') {
740740
scopeTerms.push(`source_record_id IN ${ids}`);
741-
for (const id of term.ids) recordIds.add(id);
741+
recordTerms.push(term.ids);
742742
continue;
743743
}
744744
parentTerm = true;
@@ -840,7 +840,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
840840
// A scope of record terms alone that the first pass is not expected
841841
// to answer goes straight to the exact scan, which the record index
842842
// serves from the rows in scope.
843-
if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordIds))) return client.execute(statement());
843+
if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordTerms))) return client.execute(statement());
844844
// A failed approximate statement (its index gone under this process's
845845
// memory of it) forgets that memory and is answered by the exact scan.
846846
const approximate = (candidates: number) =>
@@ -1270,32 +1270,42 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
12701270
}
12711271

12721272
/**
1273-
* Whether a scope of record terms alone, of the distinct `recordIds`, keeps
1273+
* Whether a scope of record terms alone, of the ids `terms` hold, keeps
12741274
* fewer of the passages of `table` than the first approximate pass needs to
12751275
* be expected to keep {@link VECTOR_RECORD_SCOPE_POOL} × the floor in scope:
12761276
* a share under that many times {@link VECTOR_MIN_POOL} /
12771277
* `vectorIndexOverfetch`. The passages in scope are estimated from those of
12781278
* at most {@link VECTOR_SCOPE_SAMPLE} of the ids, spread evenly over them,
12791279
* counted through the record index (exactly, for a scope of no more ids),
12801280
* 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.
1281+
* none (an id two terms name is one id to the count, and weighs twice in
1282+
* the estimate of a sampled scope). The organization and metadata filters
1283+
* are not counted: the exact scan reads every row the record index finds
1284+
* for the scope. Runs inside the client's queue.
12841285
*/
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)]);
1286+
private async recordScopeUnderCut(db: Pick<Client, 'execute'>, table: string, terms: readonly (readonly string[])[]): Promise<boolean> {
1287+
const total = terms.reduce((sum, ids) => sum + ids.length, 0);
1288+
const sample: string[] = [];
1289+
if (total <= VECTOR_SCOPE_SAMPLE) {
1290+
for (const ids of terms) sample.push(...ids);
1291+
} else {
1292+
// The ids at evenly spread positions of the terms taken one after another.
1293+
let term = 0;
1294+
let before = 0;
1295+
for (let i = 0; i < VECTOR_SCOPE_SAMPLE; i++) {
1296+
const at = Math.floor((i * total) / VECTOR_SCOPE_SAMPLE);
1297+
while (at >= before + terms[term].length) before += terms[term++].length;
1298+
sample.push(terms[term][at - before]);
1299+
}
1300+
}
12911301
const t = quoted(table);
12921302
const counted = await db.execute({
12931303
sql: `SELECT (SELECT count(*) FROM ${t}) AS n,
12941304
(SELECT count(*) FROM ${t} WHERE source_record_id IN (SELECT value FROM json_each(?1))) AS k`,
12951305
args: [JSON.stringify(sample)],
12961306
});
12971307
const n = Number(counted.rows[0].n);
1298-
const inScope = (Number(counted.rows[0].k) * ids.length) / Math.max(1, sample.length);
1308+
const inScope = (Number(counted.rows[0].k) * total) / Math.max(1, sample.length);
12991309
return inScope * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL * n;
13001310
}
13011311

0 commit comments

Comments
 (0)