Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): alias reads look the matching aliases up first; the #5094 alias foreign key had flipped the stats-free PGLite plan into a walk over every readable page (~20 ms per MCP search at 10k pages)

garrytanfee4ba84db8b
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 7c21bdf0d9..9edb5497ca 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -170,11 +170,20 @@ export async function readAliases(query: ReadQuery, aliases: string[], scope?: P
const out = new Map<string, PageRef[]>();
if (!aliases.length) return out;
const params: unknown[] = [aliases];
+ const aliasScope = pageReadFilter('m', scope && { sourceId: scope.sourceId, sourceIds: scope.sourceIds }, params);
const filter = pageReadFilter('p', scope, params, true);
+ // Alias matches first, then one unique-key page lookup each (OFFSET 0 keeps the
+ // read filter out of that lookup): without planner statistics (PGLite has no
+ // autovacuum) the page_aliases -> sources foreign key otherwise makes the planner
+ // walk every readable page and probe aliases per page.
const rows = await query<PageRef & { alias_norm: string }>(`
- SELECT a.alias_norm, a.slug, a.source_id FROM page_aliases a
- JOIN pages p ON p.source_id = a.source_id AND p.slug = a.slug
- WHERE a.alias_norm = ANY($1::text[]) AND ${filter}
+ WITH a AS MATERIALIZED (
+ SELECT m.alias_norm, m.slug, m.source_id FROM page_aliases m
+ WHERE m.alias_norm = ANY($1::text[]) AND ${aliasScope}
+ )
+ SELECT a.alias_norm, a.slug, a.source_id FROM a
+ CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = a.source_id AND slug = a.slug OFFSET 0) p
+ WHERE ${filter}
ORDER BY a.alias_norm, a.source_id, a.slug`, params);
for (const row of rows) {
const refs = out.get(row.alias_norm) ?? [];
diff --git a/test/search/alias-read-plan.test.ts b/test/search/alias-read-plan.test.ts
new file mode 100644
index 0000000000..b46e108173
--- /dev/null
+++ b/test/search/alias-read-plan.test.ts
@@ -0,0 +1,45 @@
+/**
+ * Alias resolution drives from the matching alias rows. Without planner
+ * statistics (PGLite has no autovacuum), the page_aliases -> sources foreign key
+ * (#5094) flipped the plan so every alias lookup walked all readable pages; at
+ * 10k pages that added about 20 ms to every MCP search.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+
+let engine: PGLiteEngine;
+let captured: { sql: string; params: unknown[] } | null = null;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('second-example', 'second-example') ON CONFLICT DO NOTHING");
+ for (let i = 0; i < 300; i++) {
+ await engine.putPage(`notes/page-${i}`, { type: 'note', title: `Page ${i}`, compiled_truth: `Body ${i}.` }, { sourceId: i % 2 ? 'default' : 'second-example' });
+ }
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+type PlanNode = { 'Node Type': string; 'Relation Name'?: string; 'Index Name'?: string; 'Actual Loops'?: number; Plans?: PlanNode[] };
+const nodes = (node: PlanNode): PlanNode[] => [node, ...(node.Plans ?? []).flatMap(nodes)];
+
+describe('alias reads look aliases up first', () => {
+ test('a lookup whose alias matches nothing reads no page rows', async () => {
+ const original = engine.executeRaw.bind(engine);
+ (engine as unknown as { executeRaw: typeof original }).executeRaw = (async (sql: string, params?: unknown[]) => {
+ if (/FROM page_aliases/.test(sql)) captured = { sql, params: params ?? [] };
+ return original(sql, params);
+ }) as typeof original;
+ try {
+ await engine.resolveAliases(['missing-alias-example'], { sourceIds: ['default', 'second-example'] });
+ } finally {
+ (engine as unknown as { executeRaw: typeof original }).executeRaw = original;
+ }
+ expect(captured).not.toBeNull();
+ const [row] = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: PlanNode }> }>(`EXPLAIN (ANALYZE, FORMAT JSON) ${captured!.sql}`, captured!.params);
+ const all = nodes(row!['QUERY PLAN'][0]!.Plan);
+ const pageScans = all.filter(n => n['Relation Name'] === 'pages' && /Scan/.test(n['Node Type']) && (n['Actual Loops'] ?? 0) > 0);
+ expect(pageScans).toEqual([]);
+ });
+});