Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): count scope chunks in the background so a search inside a transaction never waits on its own pool
time-attack7d033781c448
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex f164815eb5..b2dc86a09d 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -219,17 +219,22 @@ export function sourceScope(stats: PageSourceStats | undefined, opts?: SearchOpt* The engines' scope lookup, only for source-scoped searches:* PAGE_SOURCE_STATS_SQL through `load` at most once a minute, and for a scope* under SCOPE_SCAN_MAX_SHARE of pages (the only scopes whose chunk count picks- * a path) SCOPE_CHUNKS_SQL through `count`, at most once a minute per scope.- * The estimate only picks the walk, the scope scan or the joined statement,- * each of which falls back to the joined statement when it comes back short,- * so stale or missing statistics, or a failed count, cost speed at most.+ * a path) SCOPE_CHUNKS_SQL through `count`, refreshed at most once a minute+ * per scope. The count never blocks a search: until a scope's first count+ * lands, and while a refresh runs, the search routes on the last count or the+ * share estimate. (`count` runs on the engine's own pool, so a search inside+ * a caller's transaction on a one-connection pool would otherwise wait on+ * itself.) The estimate only picks the walk, the scope scan or the joined+ * statement, each of which falls back to the joined statement when it comes+ * back short, so stale or missing statistics, or a failed count, cost speed+ * at most.*/export function vectorScopeLoader(load: () => Promise<PageSourceStats[]>,count?: (sourceIds: string[]) => Promise<ScopeChunkCount[]>,): (opts?: SearchOpts) => Promise<VectorScope | undefined> {let cached: { at: number; stats: Promise<PageSourceStats | undefined> } | undefined;- const counts = new Map<string, { at: number; count: Promise<ScopeChunkCount | undefined> }>();+ const counts = new Map<string, { at: number; value?: ScopeChunkCount }>();return async opts => {const ids = scopeSourceIds(opts);if (!ids) return undefined;@@ -238,12 +243,13 @@ export function vectorScopeLoader(const share = sourceScopeShare(stats, opts);if (!count || share === undefined || share >= SCOPE_SCAN_MAX_SHARE) return sourceScope(stats, opts);const key = [...ids].sort().join('\u0000');- let entry = counts.get(key);+ const entry = counts.get(key);if (!entry || performance.now() - entry.at > 60_000) {- entry = { at: performance.now(), count: count(ids).then(rows => rows[0], () => undefined) };- counts.set(key, entry);+ const next: { at: number; value?: ScopeChunkCount } = { at: performance.now(), value: entry?.value };+ counts.set(key, next);+ count(ids).then(rows => { if (rows[0]) next.value = rows[0]; }, () => { /* keep the last count or the share estimate */ });}- return sourceScope(stats, opts, await entry.count);+ return sourceScope(stats, opts, counts.get(key)!.value);};}diff --git a/test/search/vector-scope-chunks.test.ts b/test/search/vector-scope-chunks.test.tsindex 1d6ff96175..7590c3be08 100644--- a/test/search/vector-scope-chunks.test.ts+++ b/test/search/vector-scope-chunks.test.ts@@ -3,7 +3,8 @@* SCOPE_CHUNK_SAMPLE_PAGES pages is counted exactly (soft-deleted pages* excluded), a larger one through its hash-stride sample lands near the true* count, and the engine's loader routes a source of long pages on that count- * where the page share would have undercounted it. No embeddings are needed:+ * where the page share would have undercounted it (once the background count+ * lands; the first search routes on the share). No embeddings are needed:* routing reads only pages, chunks and planner statistics.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';@@ -84,7 +85,10 @@ describe('SCOPE_CHUNKS_SQL', () => {const opts: SearchOpts = { embeddingColumn: column, sourceId: 'sessions' };const [stats] = await engine.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL);const byShare = sourceScope(stats, opts)!;- const routed = await (engine as unknown as { vectorScope: (o?: SearchOpts) => Promise<VectorScope | undefined> }).vectorScope(opts);+ const loader = (engine as unknown as { vectorScope: (o?: SearchOpts) => Promise<VectorScope | undefined> }).vectorScope;+ expect(await loader(opts)).toEqual(byShare);+ let routed = await loader(opts);+ for (let i = 0; i < 50 && routed!.chunks === byShare.chunks; i++) routed = (await Bun.sleep(20), await loader(opts));const truth = await trueChunks(['sessions']);expect(byShare.chunks!).toBeLessThan(SCOPE_SCAN_FIRST_MAX_CHUNKS);expect(Math.abs(routed!.chunks! - truth) / truth).toBeLessThan(0.05);diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex afb1231f21..454ebf031f 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -263,26 +263,36 @@ describe('source scope strategy: walk overfetch, walk skip and scope scan', () =expect(walkFirst.scopeScanSql).toBe(scanFirst.scopeScanSql!);});- test('the loader counts chunks only for scopes under SCOPE_SCAN_MAX_SHARE, once a minute per scope, and falls back on a failed count', async () => {+ test('the loader counts chunks only for scopes under SCOPE_SCAN_MAX_SHARE, in the background, once a minute per scope, and keeps the estimate on a failed count', async () => {const asked: string[][] = [];- const scope = vectorScopeLoader(async () => [stats], async ids => { asked.push(ids); return [{ pages: 250, sampled: 250, sample_chunks: 90_000 }]; });+ let release: () => void = () => {};+ const gate = new Promise<void>(resolve => { release = resolve; });+ const scope = vectorScopeLoader(async () => [stats], async ids => { asked.push(ids); await gate; return [{ pages: 250, sampled: 250, sample_chunks: 90_000 }]; });expect(await scope({ sourceIds: ['notes'] })).toEqual({ share: 0.7, chunks: 140_000 });expect(asked).toEqual([]);- expect(await scope({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 90_000 });- expect(await scope({ sourceIds: ['sessions', 'sessions'] })).toEqual({ share: 0.25, chunks: 90_000 });+ // The first search routes on the share estimate while the count runs.+ expect(await scope({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 50_000 });+ expect(await scope({ sourceIds: ['sessions', 'sessions'] })).toEqual({ share: 0.25, chunks: 50_000 });expect(asked).toEqual([['sessions']]);- expect((await scope({ sourceIds: ['small', 'sessions'] }))?.chunks).toBe(90_000);+ release();+ await Bun.sleep(0);+ expect(await scope({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 90_000 });+ await scope({ sourceIds: ['small', 'sessions'] });+ await Bun.sleep(0);expect((await scope({ sourceIds: ['sessions', 'small'] }))?.chunks).toBe(90_000);expect(asked).toEqual([['sessions'], ['small', 'sessions']]);const now = performance.now();const clock = spyOn(performance, 'now').mockReturnValue(now + 61_000);try {- await scope({ sourceId: 'sessions' });+ // A refresh keeps routing on the last count until it lands.+ expect((await scope({ sourceId: 'sessions' }))?.chunks).toBe(90_000);expect(asked).toHaveLength(3);} finally {clock.mockRestore();}const failing = vectorScopeLoader(async () => [stats], async () => { throw new Error('canceling statement due to statement timeout'); });+ await failing({ sourceId: 'sessions' });+ await Bun.sleep(0);expect(await failing({ sourceId: 'sessions' })).toEqual({ share: 0.25, chunks: 50_000 });});