Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(timeline): unscoped get_timeline probes pages by (source_id, slug) per source (Cat7-1)

garrytane7c403fbed2d
diff --git a/src/core/engine-sql/timeline.ts b/src/core/engine-sql/timeline.ts
index 1388113d86..c8cbad106b 100644
--- a/src/core/engine-sql/timeline.ts
+++ b/src/core/engine-sql/timeline.ts
@@ -106,8 +106,17 @@ export async function getTimeline(exec: LegacyUnscopedRead, slug: string, opts?:
: sqlFragment``;
const afterCond = opts?.after ? sqlFragment`AND te.date >= ${opts.after}::date` : sqlFragment``;
const beforeCond = opts?.before ? sqlFragment`AND te.date <= ${opts.before}::date` : sqlFragment``;
+ // Cat7-1: no index leads with slug, so an unscoped `p.slug = $1` scans all
+ // of pages_source_slug_key whenever statistics steer the planner to drive
+ // from pages. The unscoped arm probes (source_id, slug) once per source
+ // instead, in a LATERAL fenced with OFFSET 0 so no plan can reorder it.
+ const pagesJoin = opts?.sourceIds?.length || opts?.sourceId
+ ? sqlFragment`timeline_entries te JOIN pages p ON p.id = te.page_id`
+ : sqlFragment`sources s
+ CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = s.id AND slug = ${slug} OFFSET 0) p
+ JOIN timeline_entries te ON te.page_id = p.id`;
const rows = (await exec.run(sqlFragment`
- SELECT te.* FROM timeline_entries te JOIN pages p ON p.id = te.page_id
+ SELECT te.* FROM ${pagesJoin}
WHERE p.slug = ${slug} ${sourceCond} ${afterCond} ${beforeCond}
${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}
AND ${privateTimelineEventFilterFragment('te')}`) : sqlFragment``}
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index c209694e9d..b207c5baa6 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -26,6 +26,7 @@ import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';
import { hasDatabase, setupDB, setupLegacyEmbeddingDB, teardownDB, getEngine } from './helpers.ts';
import { TRAVERSE_PATH_ROW_CAP } from '../../src/core/engine-constants.ts';
import { DENSE_HUB_SLUG, DENSE_HUB_SPOKES, seedDenseHub } from '../helpers/dense-hub.ts';
+import { timelinePageScans } from '../helpers/timeline-plan.ts';
const SKIP_PG = !hasDatabase();
const describeBoth = SKIP_PG ? describe.skip : describe;
@@ -1529,6 +1530,58 @@ describeBoth('Engine parity — federated sourceIds[] secondary reads (#2200)',
});
});
+// Cat7-1: the unscoped getTimeline read probes pages by (source_id, slug) on
+// both engines once statistics exist, and still unions every same-slug page.
+describeBoth('Engine parity — unscoped getTimeline plan (Cat7-1)', () => {
+ let pgEngine: BrainEngine;
+ let pgliteEngine: PGLiteEngine;
+
+ async function seed(eng: BrainEngine) {
+ await eng.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('beta', 'beta', '/tmp/beta') ON CONFLICT (id) DO NOTHING`);
+ await eng.executeRaw(`INSERT INTO pages (slug, type, title) SELECT 'people/person-' || g, 'person', 'Person ' || g FROM generate_series(0, 1999) g`);
+ await eng.putPage('people/person-7', { type: 'person', title: 'Person 7 (beta)', compiled_truth: 'beta copy' }, { sourceId: 'beta' });
+ await eng.addTimelineEntry('people/person-7', { date: '2026-02-02', source: 'notes', summary: 'default event' });
+ await eng.addTimelineEntry('people/person-7', { date: '2026-03-03', source: 'notes', summary: 'beta event' }, { sourceId: 'beta' });
+ await eng.executeRaw('ANALYZE sources, pages, timeline_entries');
+ }
+
+ beforeAll(async () => {
+ pgEngine = await setupDB();
+ await seed(pgEngine);
+ pgliteEngine = new PGLiteEngine();
+ await pgliteEngine.connect({});
+ await pgliteEngine.initSchema();
+ await seed(pgliteEngine);
+ }, 90_000);
+
+ afterAll(async () => {
+ await pgliteEngine.disconnect();
+ await teardownDB();
+ }, 30_000);
+
+ test('unscoped getTimeline returns the same cross-source entries on both engines', async () => {
+ for (const slug of ['people/person-7', 'people/person-500']) {
+ const pg = (await pgEngine.getTimeline(slug)).map(e => e.summary);
+ expect(pg).toEqual((await pgliteEngine.getTimeline(slug)).map(e => e.summary));
+ }
+ expect((await pgEngine.getTimeline('people/person-7')).map(e => e.summary)).toEqual(['beta event', 'default event']);
+ });
+
+ test('both engines reach pages only through (source_id, slug) index probes', async () => {
+ for (const eng of [pgEngine, pgliteEngine]) {
+ for (const slug of ['people/person-7', 'people/person-500']) {
+ const scans = await timelinePageScans(eng, slug);
+ expect(scans.length).toBeGreaterThan(0);
+ for (const scan of scans) {
+ expect(scan.node).toMatch(/Index/);
+ expect(scan.cond).toContain('source_id');
+ expect(scan.cond).toContain('slug');
+ }
+ }
+ }
+ });
+});
+
// ── ambient recall parity (v0.45.7, issue #1) ───────────────────────────
// Two seams that only real Postgres can vet:
// 1. The keyset-pagination WHERE clause (PageFilters.updatedAfterKeyset) —
diff --git a/test/engine-sql-timeline-plan.test.ts b/test/engine-sql-timeline-plan.test.ts
new file mode 100644
index 0000000000..c8ef427208
--- /dev/null
+++ b/test/engine-sql-timeline-plan.test.ts
@@ -0,0 +1,48 @@
+/**
+ * Cat7-1: the unscoped `getTimeline` read keeps a planner-proof shape.
+ *
+ * Protects: once planner statistics exist (F4b's automatic ANALYZE), the
+ * unscoped read still reaches `pages` only through full `(source_id, slug)`
+ * index probes, and it still returns every same-slug page's entries across
+ * sources.
+ * Fails when: the read filters `pages` by slug alone, so with statistics the
+ * planner drives from pages and scans all of `pages_source_slug_key` (no index
+ * leads with slug): gbrain-evals' Cat 7 get_timeline at 1,000 pages doubled.
+ * Seams: none; in-memory PGLite (the SQL is shared with Postgres, whose plan
+ * is pinned in test/e2e/engine-parity.test.ts).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { timelinePageScans } from './helpers/timeline-plan.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('beta', 'beta', '/tmp/beta') ON CONFLICT (id) DO NOTHING`);
+ await engine.executeRaw(`INSERT INTO pages (slug, type, title) SELECT 'people/person-' || g, 'person', 'Person ' || g FROM generate_series(0, 999) g`);
+ await engine.putPage('people/person-7', { type: 'person', title: 'Person 7 (beta)', compiled_truth: 'beta copy' }, { sourceId: 'beta' });
+ await engine.addTimelineEntry('people/person-7', { date: '2026-02-02', source: 'notes', summary: 'default event' });
+ await engine.addTimelineEntry('people/person-7', { date: '2026-03-03', source: 'notes', summary: 'beta event' }, { sourceId: 'beta' });
+ await engine.executeRaw('ANALYZE sources, pages, timeline_entries');
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+test('with planner statistics the unscoped read probes pages by (source_id, slug), never by slug alone', async () => {
+ for (const slug of ['people/person-7', 'people/person-500']) {
+ const scans = await timelinePageScans(engine, slug);
+ expect(scans.length).toBeGreaterThan(0);
+ for (const scan of scans) {
+ expect(scan.node).toMatch(/Index/);
+ expect(scan.cond).toContain('source_id');
+ expect(scan.cond).toContain('slug');
+ }
+ }
+});
+
+test('the unscoped read returns every same-slug page across sources; scoped reads stay in scope', async () => {
+ expect((await engine.getTimeline('people/person-7')).map(e => e.summary)).toEqual(['beta event', 'default event']);
+ expect((await engine.getTimeline('people/person-7', { sourceId: 'beta' })).map(e => e.summary)).toEqual(['beta event']);
+ expect((await engine.getTimeline('people/person-7', { sourceIds: ['default'] })).map(e => e.summary)).toEqual(['default event']);
+ expect(await engine.getTimeline('people/person-500')).toEqual([]);
+});
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 0f2896ca12..27a1496d46 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -4495,7 +4495,7 @@
"getTimeline": {
"default": [
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
@@ -4506,7 +4506,7 @@
],
"excludePrivate": [
{
- "paramCount": 2,
+ "paramCount": 3,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
diff --git a/test/fixtures/goldens/sql-text/timeline.json b/test/fixtures/goldens/sql-text/timeline.json
index 429ffcc66e..01967f8f86 100644
--- a/test/fixtures/goldens/sql-text/timeline.json
+++ b/test/fixtures/goldens/sql-text/timeline.json
@@ -121,22 +121,24 @@
{
"lane": "pool",
"params": [
+ "string",
"string",
"number"
],
- "sql": "SELECT te.* FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE p.slug = $1 ORDER BY te.date DESC, te.id DESC LIMIT $2",
- "textSha256": "14e536ecb947a78c545c0a92149eda3ef40d8da3f69701d69c52c5ff5c61f9e5"
+ "sql": "SELECT te.* FROM sources s CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = s.id AND slug = $1 OFFSET 0) p JOIN timeline_entries te ON te.page_id = p.id WHERE p.slug = $2 ORDER BY te.date DESC, te.id DESC LIMIT $3",
+ "textSha256": "70a8feb6c889c5ded02b4af84e6b01e4ed07e4031f87a9851500e2bf28c1823d"
}
],
"excludePrivate": [
{
"lane": "pool",
"params": [
+ "string",
"string",
"number"
],
- "sql": "SELECT te.* FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE p.slug = $1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END) AND NOT (jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY te.date DESC, te.id DESC LIMIT $2",
- "textSha256": "524f8ff484d29548c28d0e2027d406622ce65c88effdd7963efede2fbe566fcf"
+ "sql": "SELECT te.* FROM sources s CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = s.id AND slug = $1 OFFSET 0) p JOIN timeline_entries te ON te.page_id = p.id WHERE p.slug = $2 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END) AND NOT (jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY te.date DESC, te.id DESC LIMIT $3",
+ "textSha256": "f32c206b4dad244023ff7f8fe4ef7257ea2da99d34d4cd1259b266e9528215be"
}
],
"sourceId": [
diff --git a/test/helpers/timeline-plan.ts b/test/helpers/timeline-plan.ts
new file mode 100644
index 0000000000..99f0e88ba7
--- /dev/null
+++ b/test/helpers/timeline-plan.ts
@@ -0,0 +1,31 @@
+/**
+ * Cat7-1: the plan an engine picks for getTimeline's statement. The statement
+ * is captured from the shared engine-sql builder with a recording executor and
+ * explained on the real engine, so the plan is the one that call would run.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { TimelineOpts } from '../../src/core/types.ts';
+import type { LegacyUnscopedRead } from '../../src/core/engine-sql/brands.ts';
+import { renderFragment, type SqlFragment } from '../../src/core/engine-sql/fragment.ts';
+import { getTimeline } from '../../src/core/engine-sql/timeline.ts';
+
+export interface PlanScan { node: string; index?: string; cond?: string }
+
+/** Every plan node that reads `pages`, with its index and index condition. */
+export async function timelinePageScans(engine: BrainEngine, slug: string, opts?: TimelineOpts): Promise<PlanScan[]> {
+ let statement: SqlFragment | undefined;
+ const recorder = { dialect: engine.kind, run: async (f: SqlFragment) => { statement = f; return { rows: [], affectedRows: 0 }; } };
+ await getTimeline(recorder as unknown as LegacyUnscopedRead, slug, opts);
+ const { text, params } = renderFragment(statement!);
+ const [row] = await engine.executeRaw<Record<string, unknown>>(`EXPLAIN (FORMAT JSON) ${text}`, params);
+ const raw = row['QUERY PLAN'];
+ const scans: PlanScan[] = [];
+ const walk = (node: Record<string, unknown>) => {
+ if (node['Relation Name'] === 'pages') {
+ scans.push({ node: String(node['Node Type']), index: node['Index Name'] as string | undefined, cond: (node['Index Cond'] ?? node['Recheck Cond']) as string | undefined });
+ }
+ for (const child of (node.Plans as Record<string, unknown>[] | undefined) ?? []) walk(child);
+ };
+ walk(((typeof raw === 'string' ? JSON.parse(raw) : raw) as { Plan: Record<string, unknown> }[])[0].Plan);
+ return scans;
+}