Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(pages): alias snapshot reads probe indexes instead of scanning every page (#6281)

time-attack8bf74da7550e
diff --git a/docs/architecture/key-files/memory-purge.md b/docs/architecture/key-files/memory-purge.md
index 924f73f93d..3fc2e5e780 100644
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@ -9,6 +9,7 @@ User-facing contract: [expire versus purge](../../guides/memory-boundaries.md#pu
- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.
- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
- `src/core/page-state/snapshot.ts` (purge part) — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale.
+- `src/core/page-state/snapshot.ts` (alias part) — `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
- `src/core/persistence/intent-redaction.ts` — accounting-aware intent redaction: `findRequestsCarrying` (intent, outcome, error detail or message, compacted rows included) / `findRequestsForSlugs`, `redactRequestIntents` locks counters then request rows, refuses on a non-terminal or recovering request (unless `skipPending`), nulls `intent`/`error_message` and replaces every outcome or error-detail string carrying a needle with `"[purged]"` (`redactJson`), with compaction's terminal-byte accounting, so replay keeps returning the (redacted) stored outcome.
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index b57a203597..236ce37b3a 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -58,10 +58,9 @@ export async function overlayCanonicalBodies(query: ReadQuery, body: string, tim
*
* An alias-resolving read first runs the exact-slug statement: an exact match
* outranks every alias match, so a hit is the row the alias statement would
- * pick. Only a miss runs the alias statement, whose `slug = $1 OR EXISTS
- * (alias)` disjunction scans the source's pages (23-80 ms at 50k pages, under
- * 1 ms for the exact lookup). An ambiguity check counts alias matches too, so
- * it always runs the alias statement.
+ * pick. Only a miss runs the alias statement, a UNION ALL of the exact-slug
+ * probe and an alias-join probe (#6281), both index lookups. An ambiguity check
+ * counts alias matches too, so it always runs the alias statement.
*/
export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {
if (opts?.resolveAlias === true && opts.requireUnambiguous !== true) {
@@ -73,26 +72,32 @@ export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: Pa
async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {
const params: unknown[] = [slug];
- // Alias resolution is part of the statement text, not a parameter, so a
- // cached plan for an exact-slug read keeps using the slug index.
- const where = [opts?.resolveAlias === true ? `(p.slug=$1 OR (
- ${opts?.preserveExactIdentity ? 'NOT EXISTS (SELECT 1 FROM pages exact_page WHERE exact_page.source_id=p.source_id AND exact_page.slug=$1) AND' : ''}
- EXISTS (SELECT 1 FROM slug_aliases a
- WHERE a.alias_slug=$1 AND a.source_id=p.source_id AND a.canonical_slug=p.slug
- AND EXISTS (SELECT 1 FROM sources alias_source WHERE alias_source.id=a.source_id ${opts?.includeDeleted ? '' : 'AND NOT alias_source.archived'}))))` : 'p.slug=$1'];
+ const filters: string[] = [];
if (opts?.sourceIds?.length) {
params.push(opts.sourceIds);
- where.push(`p.source_id=ANY($${params.length}::text[])`);
+ filters.push(`p.source_id=ANY($${params.length}::text[])`);
} else if (opts?.sourceId) {
params.push(opts.sourceId);
- where.push(`p.source_id=$${params.length}`);
+ filters.push(`p.source_id=$${params.length}`);
}
- if (!opts?.includeDeleted) where.push('p.deleted_at IS NULL');
- if (opts?.excludePrivate) where.push(privatePagesFilterFragment('p'));
- if (opts?.requireLiveSource) where.push('EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)');
+ if (!opts?.includeDeleted) filters.push('p.deleted_at IS NULL');
+ if (opts?.excludePrivate) filters.push(privatePagesFilterFragment('p'));
+ if (opts?.requireLiveSource) filters.push('EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)');
params.push(opts?.sourceIds?.[0] ?? 'default');
+ const and = filters.map(filter => ` AND ${filter}`).join('');
+ // Alias resolution is part of the statement text, not a parameter, so a cached plan for an exact-slug read keeps
+ // using the slug index. #6281: the alias read is a UNION ALL of two indexable branches (the exact slug, and pages an
+ // alias row names), never `slug=$1 OR EXISTS(alias)`, which scans every page; `p.slug<>$1` keeps the branches disjoint
+ // so the ambiguity count still counts pages.
+ const candidates = opts?.resolveAlias === true ? `(SELECT p.* FROM pages p WHERE p.slug=$1${and}
+ UNION ALL
+ SELECT p.* FROM slug_aliases a JOIN pages p ON p.source_id=a.source_id AND p.slug=a.canonical_slug
+ WHERE a.alias_slug=$1 AND p.slug<>$1
+ AND EXISTS (SELECT 1 FROM sources alias_source WHERE alias_source.id=a.source_id ${opts?.includeDeleted ? '' : 'AND NOT alias_source.archived'})
+ ${opts?.preserveExactIdentity ? 'AND NOT EXISTS (SELECT 1 FROM pages exact_page WHERE exact_page.source_id=a.source_id AND exact_page.slug=$1)' : ''}${and}) p`
+ : `pages p WHERE p.slug=$1${and}`;
const rows = await query<Record<string, unknown>>(`WITH chosen AS (
- SELECT p.*${opts?.requireUnambiguous ? ', count(*) OVER () AS snapshot_matches' : ''} FROM pages p WHERE ${where.join(' AND ')}
+ SELECT p.*${opts?.requireUnambiguous ? ', count(*) OVER () AS snapshot_matches' : ''} FROM ${candidates}
ORDER BY (p.slug=$1) DESC, (p.source_id=$${params.length}) DESC, p.source_id ASC LIMIT 1
) SELECT p.*,
(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,
diff --git a/test/e2e/page-snapshot-alias-plan-postgres.test.ts b/test/e2e/page-snapshot-alias-plan-postgres.test.ts
new file mode 100644
index 0000000000..02b69fa810
--- /dev/null
+++ b/test/e2e/page-snapshot-alias-plan-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../page-snapshot-alias-plan.test.ts'));
diff --git a/test/page-snapshot-alias-plan.test.ts b/test/page-snapshot-alias-plan.test.ts
new file mode 100644
index 0000000000..94915070c5
--- /dev/null
+++ b/test/page-snapshot-alias-plan.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #6281: an alias-resolving snapshot read never scans every page.
+ *
+ * Protects: `readPageSnapshot` with `resolveAlias` (get_page's alias hit and miss, fetch's `requireUnambiguous`
+ * exact hit), scoped to the caller's readable sources as every caller scopes it, visits only a handful of `pages` rows
+ * on a brain with thousands of pages, measured from
+ * EXPLAIN (ANALYZE, FORMAT JSON) of each statement it sends, on PGLite and Postgres; and the alias semantics hold
+ * (exact outranks alias, source preference, ambiguity across sources, preserveExactIdentity, deleted target,
+ * archived alias source, includeDeleted). Regression it catches: `slug=$1 OR EXISTS(alias)`, which reads every page.
+ * No wall-clock thresholds.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { readPageSnapshot } from '../src/core/page-state/snapshot.ts';
+import { PageSnapshotAmbiguousError } from '../src/core/page-state/types.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const FILLER = 12_000;
+
+type PlanNode = { 'Relation Name'?: string; 'Actual Rows'?: number; 'Actual Loops'?: number; 'Rows Removed by Filter'?: number; 'Rows Removed by Index Recheck'?: number; Plans?: PlanNode[] };
+function pagesVisited(node: PlanNode): number {
+ const own = node['Relation Name'] === 'pages'
+ ? ((node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0) + (node['Rows Removed by Index Recheck'] ?? 0)) * (node['Actual Loops'] ?? 1) : 0;
+ return own + (node.Plans ?? []).reduce((sum, child) => sum + pagesVisited(child), 0);
+}
+
+for (const kind of testBackends()) {
+ describe(`alias snapshot reads use the indexes (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('alt','alt'),('gone','gone') ON CONFLICT (id) DO NOTHING");
+ for (const source of ['default', 'alt']) {
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)
+ SELECT $1, 'filler/p-' || g, 'note', 'Filler ' || g, 'filler body' FROM generate_series(1, $2::int) g`, [source, FILLER / 2]);
+ }
+ const put = (slug: string, sourceId: string, frontmatter: Record<string, unknown> = {}) =>
+ engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} body`, frontmatter }, { sourceId });
+ await put('people/alice-example', 'default');
+ await put('people/alice-example', 'alt');
+ await put('people/bob-example', 'default');
+ await put('people/ann-example', 'default');
+ await put('people/private-example', 'default', { visibility: 'private' });
+ await put('people/carol-example', 'default');
+ await put('people/carol-example', 'gone');
+ await engine.executeRaw(`INSERT INTO slug_aliases(source_id,alias_slug,canonical_slug) VALUES
+ ('default','bob','people/bob-example'),
+ ('default','alice','people/alice-example'),('alt','alice','people/alice-example'),
+ ('default','people/ann-example','people/bob-example'),
+ ('default','people/private-example','people/carol-example'),
+ ('gone','carol','people/carol-example')`);
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='gone'");
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE slug_aliases');
+ }, 180_000);
+ afterAll(async () => { await close?.(); });
+
+ async function visits(slug: string, opts: Parameters<typeof readPageSnapshot>[2]) {
+ const counts: number[] = [];
+ const query = async <T,>(sql: string, params?: unknown[]): Promise<T[]> => {
+ if (sql.trimStart().startsWith('WITH chosen')) {
+ const [plan] = await engine.executeRaw<{ 'QUERY PLAN': unknown }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${sql}`, params);
+ const parsed = (typeof plan!['QUERY PLAN'] === 'string' ? JSON.parse(plan!['QUERY PLAN'] as string) : plan!['QUERY PLAN']) as Array<{ Plan: PlanNode }>;
+ counts.push(pagesVisited(parsed[0]!.Plan));
+ }
+ return engine.executeRaw<T>(sql, params);
+ };
+ const snapshot = await readPageSnapshot(query as Parameters<typeof readPageSnapshot>[0], slug, opts).catch((error: unknown) => error);
+ return { counts, snapshot };
+ }
+
+ test.each([
+ ['get_page alias hit', 'bob', { resolveAlias: true, sourceIds: ['default', 'alt'] }],
+ ['get_page alias hit in one source', 'bob', { resolveAlias: true, sourceId: 'default' }],
+ ['get_page miss', 'nobody-example', { resolveAlias: true, sourceIds: ['default', 'alt'] }],
+ ['fetch exact hit across sources', 'people/bob-example', { resolveAlias: true, requireUnambiguous: true, sourceIds: ['default', 'alt'] }],
+ ['fetch exact hit in one source', 'people/bob-example', { resolveAlias: true, requireUnambiguous: true, sourceId: 'default' }],
+ ['private exact with preserveExactIdentity', 'people/private-example', { resolveAlias: true, excludePrivate: true, preserveExactIdentity: true, sourceIds: ['default', 'alt'] }],
+ ] as const)('%s visits fewer than 100 pages rows per statement', async (_name, slug, opts) => {
+ const { counts } = await visits(slug, opts);
+ expect(counts.length).toBeGreaterThan(0);
+ for (const count of counts) expect(count).toBeLessThan(100);
+ });
+
+ test('semantics: exact outranks alias, alias resolves, source preference, ambiguity, preserveExactIdentity, archived alias source', async () => {
+ const read = (slug: string, opts: Parameters<typeof readPageSnapshot>[2]) => readPageSnapshot((sql, params) => engine.executeRaw(sql, params), slug, opts);
+ expect((await read('people/ann-example', { resolveAlias: true }))?.page.slug).toBe('people/ann-example');
+ expect((await read('bob', { resolveAlias: true }))?.page.slug).toBe('people/bob-example');
+ expect((await read('alice', { resolveAlias: true, sourceIds: ['alt', 'default'] }))?.page.source_id).toBe('alt');
+ expect((await read('alice', { resolveAlias: true }))?.page.source_id).toBe('default');
+ await expect(read('alice', { resolveAlias: true, requireUnambiguous: true })).rejects.toBeInstanceOf(PageSnapshotAmbiguousError);
+ expect((await read('people/bob-example', { resolveAlias: true, requireUnambiguous: true, sourceId: 'default' }))?.page.slug).toBe('people/bob-example');
+ expect(await read('people/private-example', { resolveAlias: true, excludePrivate: true, preserveExactIdentity: true })).toBeNull();
+ expect((await read('people/private-example', { resolveAlias: true, excludePrivate: true }))?.page.slug).toBe('people/carol-example');
+ expect(await read('carol', { resolveAlias: true })).toBeNull();
+ expect((await read('carol', { resolveAlias: true, includeDeleted: true }))?.page.source_id).toBe('gone');
+ expect(await read('nobody-example', { resolveAlias: true })).toBeNull();
+ await engine.executeRaw("UPDATE pages SET deleted_at=now() WHERE slug='people/bob-example' AND source_id='default'");
+ try {
+ expect(await read('bob', { resolveAlias: true })).toBeNull();
+ expect((await read('bob', { resolveAlias: true, includeDeleted: true }))?.page.slug).toBe('people/bob-example');
+ } finally { await engine.executeRaw("UPDATE pages SET deleted_at=NULL WHERE slug='people/bob-example' AND source_id='default'"); }
+ });
+ });
+}