Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): route source scopes on a sampled per-scope chunk count

time-attack9f02c59ee67d
diff --git a/scripts/bench/vector-scope-share.ts b/scripts/bench/efficiency/vector-scope-share.ts
similarity index 83%
rename from scripts/bench/vector-scope-share.ts
rename to scripts/bench/efficiency/vector-scope-share.ts
index 7a93648abc..398baa22d9 100644
--- a/scripts/bench/vector-scope-share.ts
+++ b/scripts/bench/efficiency/vector-scope-share.ts
@@ -3,7 +3,7 @@
* Vector search latency and recall per source scope, against an existing
* brain. Opt-in, never run in CI, not shipped in the CLI; reads only.
*
- * bun scripts/bench/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... \
+ * bun scripts/bench/efficiency/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... \
* [--queries 25] [--limit 20] [--remote] [--window] [--json]
*
* A scope is a source id, several joined with `+`, or `all` (unscoped). Query
@@ -16,10 +16,10 @@
* candidate), the share of pages the scope holds per planner statistics, and
* underfilled exits. `--remote` adds the private-page rule (`excludePrivate`).
*/
-import { PostgresEngine } from '../../src/core/postgres-engine.ts';
-import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, sourceScope, type PageSourceStats } from '../../src/core/search/vector-statement.ts';
-import type { SearchOpts } from '../../src/core/types.ts';
+import { PostgresEngine } from '../../../src/core/postgres-engine.ts';
+import { PGLiteEngine } from '../../../src/core/pglite-engine.ts';
+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, sourceScope, type PageSourceStats } from '../../../src/core/search/vector-statement.ts';
+import type { SearchOpts } from '../../../src/core/types.ts';
const args = process.argv.slice(2);
const flag = (name: string) => args.includes(`--${name}`);
@@ -30,7 +30,7 @@ const option = (name: string, fallback: number) => {
const positional = args.filter((arg, i) => !arg.startsWith('--') && !['--queries', '--limit'].includes(args[i - 1] ?? ''));
const [target, ...scopes] = positional;
if (!target || scopes.length === 0) {
- console.error('usage: bun scripts/bench/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... [--queries N] [--limit N] [--remote] [--window] [--json]');
+ console.error('usage: bun scripts/bench/efficiency/vector-scope-share.ts <postgres-url | pglite-dir> <scope>... [--queries N] [--limit N] [--remote] [--window] [--json]');
process.exit(2);
}
const queries = option('queries', 25);
@@ -73,8 +73,9 @@ for (const scope of scopes) {
total += truth.size;
hit += results[k]!.filter(id => truth.has(id)).length;
}
+ const routed = await (engine as unknown as { vectorScope: (o: SearchOpts) => Promise<{ chunks?: number } | undefined> }).vectorScope(opts);
rows.push({
- scope, share: scope === 'all' ? 1 : +(sourceScope(stats, opts)?.share ?? NaN).toFixed(4), n: ms.length,
+ scope, share: scope === 'all' ? 1 : +(sourceScope(stats, opts)?.share ?? NaN).toFixed(4), chunks: routed?.chunks === undefined ? null : Math.round(routed.chunks), n: ms.length,
p50_ms: percentile(ms, 0.5), p95_ms: percentile(ms, 0.95),
results: +(results.reduce((sum, r) => sum + r.length, 0) / results.length).toFixed(1),
recall: +(hit / Math.max(1, total)).toFixed(3), underfilled,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 3c6f918dc2..6f54c4a7f5 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -74,7 +74,7 @@ import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatch
import { supportsHnswIterativeScan } from './vector-index.ts';
import { searchIndexWalk, searchVectorPool, readVectorPool, type VectorPoolAttempt } from './search/vector-pool.ts';
import { beforePlannerRead, plannerRead } from './planner-stats.ts';
-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats } from './search/vector-statement.ts';
+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_CHUNKS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type ScopeChunkCount } from './search/vector-statement.ts';
import { withVectorSettings } from './search/vector-settings.ts';
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
@@ -705,7 +705,10 @@ export async function probePgliteScratchStore(
export class PGLiteEngine implements BrainEngine {
private vectorIterativeScan?: Promise<boolean>;
- private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));
+ private readonly vectorScope = vectorScopeLoader(
+ () => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL),
+ ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]),
+ );
/** Transaction clones keep chunk invalidation and replacement atomic. */
private _chunkWritesInTransaction = false;
private _checkpointGuard: PgliteCheckpointGuard | undefined;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index fa1df50ee4..79b699f265 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -65,7 +65,7 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { verifySchema } from './schema-verify.ts';
import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';
import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';
-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';
+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_CHUNKS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type ScopeChunkCount, type VectorSearchStatement } from './search/vector-statement.ts';
import { withVectorSettings } from './search/vector-settings.ts';
import {
vectorCastSuffix,
@@ -179,7 +179,10 @@ export function getPostgresSchema(
export class PostgresEngine implements BrainEngine {
private vectorIterativeScan?: Promise<boolean>;
- private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL));
+ private readonly vectorScope = vectorScopeLoader(
+ () => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL),
+ ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]),
+ );
/** Transaction clones keep chunk invalidation and replacement atomic. */
private _chunkWritesInTransaction = false;
readonly kind = 'postgres' as const;
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index 51212c7f60..665e0edc75 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -40,8 +40,8 @@
* window.
*
* `scopeScanSql` serves a source scope under SCOPE_SCAN_MAX_SHARE of pages
- * whose estimated chunk count (`scope.chunks`, the share times
- * `content_chunks` reltuples) is at most SCOPE_SCAN_MAX_CHUNKS: an exact
+ * whose estimated chunk count (`scope.chunks`, SCOPE_CHUNKS_SQL's sampled
+ * count) is at most SCOPE_SCAN_MAX_CHUNKS: an exact
* distance scan over the scope's chunks with every filter applied, ordering
* only chunk ids (`+ 0` keeps the index out), then the window joins back for
* its columns. The eligible page ids come first as `= ANY(ARRAY(...))`, so
@@ -146,42 +146,98 @@ export interface PageSourceStats {
export interface VectorScope {
share: number;
- /** Estimated chunks in the scope (share times `content_chunks` reltuples), absent without chunk statistics. */
+ /**
+ * Estimated chunks in the scope: SCOPE_CHUNKS_SQL's count for a scope under
+ * SCOPE_SCAN_MAX_SHARE, else the share times `content_chunks` reltuples;
+ * absent without either.
+ */
chunks?: number;
}
+/** Pages of a source scope whose chunks SCOPE_CHUNKS_SQL counts; a smaller scope has every page counted. */
+export const SCOPE_CHUNK_SAMPLE_PAGES = 400;
+
+/**
+ * Chunks in a source scope (`$1`, source ids): its live pages, and the chunks
+ * of a hash-stride sample of about SCOPE_CHUNK_SAMPLE_PAGES of them through
+ * `idx_chunks_page`. Page share alone undercounts a source of long pages (a
+ * sessions-like source holds 9.4 chunks per page against a brain average of
+ * 5), which sent a 74k-chunk scope down the path sized for 39k. The sample is
+ * deterministic (`hashint4`, so interleaved page ids do not alias a stride)
+ * and costs one pass over the scope's page ids plus ~400 index probes.
+ */
+export const SCOPE_CHUNKS_SQL = `WITH scope_pages AS MATERIALIZED (
+ SELECT id FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL),
+ total AS (SELECT count(*)::int AS pages FROM scope_pages),
+ sample AS (SELECT id FROM scope_pages, total WHERE hashint4(id) % GREATEST(1, total.pages / ${SCOPE_CHUNK_SAMPLE_PAGES}) = 0)
+ SELECT (SELECT pages FROM total) AS pages, (SELECT count(*)::int FROM sample) AS sampled,
+ (SELECT count(*)::int FROM content_chunks WHERE page_id = ANY(ARRAY(SELECT id FROM sample))) AS sample_chunks`;
+
+export interface ScopeChunkCount {
+ pages: number;
+ sampled: number;
+ sample_chunks: number;
+}
+
/** Share of pages the source scope holds, or undefined without a scope or statistics. */
export function sourceScopeShare(stats: PageSourceStats | undefined, opts?: SearchOpts): number | undefined {
- const scope = opts?.sourceIds?.length ? opts.sourceIds : opts?.sourceId ? [opts.sourceId] : undefined;
+ const scope = scopeSourceIds(opts);
if (!scope || !stats) return undefined;
const sources = stats.sources ?? [];
const freqs = (stats.freqs ?? []).map(Number);
const distinct = Number(stats.n_distinct) < 0 ? -Number(stats.n_distinct) * Number(stats.reltuples) : Number(stats.n_distinct);
const unlisted = Math.max(0, 1 - Number(stats.null_frac) - freqs.reduce((sum, freq) => sum + freq, 0)) / Math.max(1, distinct - sources.length);
- return [...new Set(scope)].reduce((sum, id) => sum + (sources.includes(id) ? freqs[sources.indexOf(id)]! : unlisted), 0);
+ return scope.reduce((sum, id) => sum + (sources.includes(id) ? freqs[sources.indexOf(id)]! : unlisted), 0);
}
-/** Share of pages and estimated chunks the source scope holds, or undefined without a scope or statistics. */
-export function sourceScope(stats: PageSourceStats | undefined, opts?: SearchOpts): VectorScope | undefined {
+function scopeSourceIds(opts?: SearchOpts): string[] | undefined {
+ const scope = opts?.sourceIds?.length ? opts.sourceIds : opts?.sourceId ? [opts.sourceId] : undefined;
+ return scope && [...new Set(scope)];
+}
+
+/**
+ * Share of pages and estimated chunks the source scope holds, or undefined
+ * without a scope or statistics. A SCOPE_CHUNKS_SQL count, when given and
+ * sampled, replaces the share-of-reltuples chunk estimate.
+ */
+export function sourceScope(stats: PageSourceStats | undefined, opts?: SearchOpts, counted?: ScopeChunkCount): VectorScope | undefined {
const share = sourceScopeShare(stats, opts);
if (share === undefined) return undefined;
+ const sampled = Number(counted?.sampled ?? 0);
+ if (sampled > 0) return { share, chunks: Math.round((Number(counted!.pages) * Number(counted!.sample_chunks)) / sampled) };
const chunks = Number(stats?.chunk_reltuples ?? -1);
return chunks > 0 ? { share, chunks: share * chunks } : { share };
}
/**
- * The engines' scope lookup: PAGE_SOURCE_STATS_SQL through `load`, at most
- * once a minute and only for source-scoped searches. 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 cost speed at most.
+ * 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.
*/
-export function vectorScopeLoader(load: () => Promise<PageSourceStats[]>): (opts?: SearchOpts) => Promise<VectorScope | undefined> {
+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> }>();
return async opts => {
- if (!opts?.sourceIds?.length && !opts?.sourceId) return undefined;
+ const ids = scopeSourceIds(opts);
+ if (!ids) return undefined;
if (!cached || performance.now() - cached.at > 60_000) cached = { at: performance.now(), stats: load().then(rows => rows[0], () => undefined) };
- return sourceScope(await cached.stats, opts);
+ const stats = await cached.stats;
+ 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);
+ if (!entry || performance.now() - entry.at > 60_000) {
+ entry = { at: performance.now(), count: count(ids).then(rows => rows[0], () => undefined) };
+ counts.set(key, entry);
+ }
+ return sourceScope(stats, opts, await entry.count);
};
}