Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): index live pages by (source_id, created_at) so relink --conversation stops timing out (#7379)

garrytan4924cdc42294
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index ac34d3ebda..38bbe95f83 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 269;
+export const LATEST_SCHEMA_VERSION = 270;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index add2f5097d..416ba8eac7 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -270,6 +270,7 @@ import { v266 } from './v266-derived-generation-activations.ts';
import { v267 } from './v267-pages-title-search-index.ts';
import { v268 } from './v268-effect-claim-owner.ts';
import { v269 } from './v269-links-supersedes-index.ts';
+import { v270 } from './v270-pages-source-created-index.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -538,4 +539,5 @@ export const MIGRATIONS: Migration[] = [
v267,
v268,
v269,
+ v270,
];
diff --git a/src/core/schema-migrations/v270-pages-source-created-index.ts b/src/core/schema-migrations/v270-pages-source-created-index.ts
new file mode 100644
index 0000000000..424abd3f48
--- /dev/null
+++ b/src/core/schema-migrations/v270-pages-source-created-index.ts
@@ -0,0 +1,35 @@
+import type { Migration } from './types.ts';
+import { buildIndexOnline, migrationNotice } from './helpers.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #7379: `gbrain facts relink --conversation` and doctor `unlinked_facts` re-arm an
+// unmemoized miss when a live page was created in the fact's source after the
+// attempt (facts/conversation-memo.ts conversationTriedSql:
+// `EXISTS (SELECT 1 FROM pages np WHERE np.source_id = f.source_id AND
+// np.deleted_at IS NULL AND np.created_at > a.attempted_at)`). The probe runs
+// once per attempt row, and no pages index covered created_at, so each probe
+// read every live page of the source: a few thousand attempts over a large
+// brain hit statement_timeout, dry run included. This partial index answers
+// each probe with one descent. Built online (CONCURRENTLY on Postgres); an
+// interrupted build leaves an INVALID index that the next initSchema drops and
+// rebuilds. Not in schema.sql: Postgres initSchema replays that blob before
+// migrations, which would build the index as a plain, write-blocking CREATE
+// INDEX on every upgrading brain.
+export const PAGES_SOURCE_CREATED_INDEX = {
+ name: 'pages_source_created_idx',
+ table: 'pages',
+ sql: 'CREATE INDEX IF NOT EXISTS pages_source_created_idx ON pages (source_id, created_at) WHERE deleted_at IS NULL',
+};
+
+export const v270: Migration = {
+ version: 270,
+ name: 'pages_source_created_index',
+ idempotent: true,
+ transaction: false,
+ sql: '',
+ handler: async engine => {
+ await buildIndexOnline(engine, 270, PAGES_SOURCE_CREATED_INDEX, { notice: migrationNotice });
+ },
+};
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 560884ee82..7b7e693366 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1357,6 +1357,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index b1424e7f81..195f585823 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1357,6 +1357,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 754f8e1ab5..4c946e50b3 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1353,6 +1353,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 7434340249..34ef89e510 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1361,6 +1361,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index e303698b95..6daaa770ef 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1361,6 +1361,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 5101d05ad6..9ff262608d 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1357,6 +1357,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index df20078320..f1791ee8dd 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 264,
+ "count": 265,
"gaps": [
17,
18,
@@ -29,6 +29,7 @@
"PAGES_NAME_LOOKUP_INDEXES": "1ca830342164b5606e96cf0090645364f9145d36178d90f166230189fe8d2705",
"PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a",
"PAGES_SEGMENTED_BODY_BYTES_INDEX": "c904a4f68cf190cce6bc68c03219c7b62d05b77eeb557db946a4f58a4f965e57",
+ "PAGES_SOURCE_CREATED_INDEX": "33411b4d6fc2287ee8fa37b1ebf2cc36a076101dbd3f3f6ac492aed06288513a",
"PAGES_TITLE_SEARCH_INDEX": "27e8e1a6c9a2069ee6c6af6fa99b9a7e9e9c118c7a933ffa80ba1864bf68baa3",
"PAGE_TIMELINE_FTS_MAX_CHARS": "f7d29264f4144976bbe2e1ded0251095b638175f8e1d711c36f1e80d2263e172",
"PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533",
@@ -74,7 +75,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 269,
+ "latest": 270,
"records": [
{
"handler": {
@@ -4300,6 +4301,35 @@
"transaction": false,
"verify": "absent",
"version": 269
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [
+ "PAGES_SOURCE_CREATED_INDEX",
+ "PLANNER_REPAIR_TABLES",
+ "analyzeAfterIndexBuild",
+ "analyzeDeferred",
+ "analyzeYieldingToVacuum",
+ "buildIndexOnline",
+ "dropInvalidConcurrentIndex",
+ "lockTableForAnalyze",
+ "migrationNotice",
+ "quietMigrationNotices",
+ "tableRows"
+ ],
+ "sha256": "61bbcf074ff9a40f227b7836eb1b4fefb5cc3ec22c4845c556c9e1f4e3e92b3b"
+ },
+ "idempotent": true,
+ "name": "pages_source_created_index",
+ "sql": {
+ "length": 0,
+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "sqlFor": "absent",
+ "transaction": false,
+ "verify": "absent",
+ "version": 270
}
],
"versions": [
@@ -4566,7 +4596,8 @@
266,
267,
268,
- 269
+ 269,
+ 270
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index a84fec79ff..e419515fc1 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1357,6 +1357,7 @@
"pages_pkey": "CREATE UNIQUE INDEX pages_pkey ON public.pages USING btree (id)",
"pages_safe_chunk_pending_idx": "CREATE INDEX pages_safe_chunk_pending_idx ON public.pages USING btree (source_id) WHERE (chunker_version < 4)",
"pages_segmented_body_bytes_idx": "CREATE INDEX pages_segmented_body_bytes_idx ON public.pages USING btree (body_bytes) WHERE (body_storage = 'segmented'::text)",
+ "pages_source_created_idx": "CREATE INDEX pages_source_created_idx ON public.pages USING btree (source_id, created_at) WHERE (deleted_at IS NULL)",
"pages_source_path_idx": "CREATE INDEX pages_source_path_idx ON public.pages USING btree (source_path) WHERE (source_path IS NOT NULL)",
"pages_source_path_name_idx": "CREATE INDEX pages_source_path_name_idx ON public.pages USING btree (source_id, regexp_replace(replace(btrim(source_path), chr(92), '/'::text), '^.*/'::text, ''::text)) WHERE (source_path IS NOT NULL)",
"pages_source_slug_key": "CREATE UNIQUE INDEX pages_source_slug_key ON public.pages USING btree (source_id, slug)",
diff --git a/test/pages-source-created-idx-7379.test.ts b/test/pages-source-created-idx-7379.test.ts
new file mode 100644
index 0000000000..a93ac6aada
--- /dev/null
+++ b/test/pages-source-created-idx-7379.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #7379: `gbrain facts relink --conversation` (and doctor `unlinked_facts`) re-arm an
+ * unmemoized miss when a live page was created in the fact's source after the
+ * attempt (`conversationTriedSql`, src/core/facts/conversation-memo.ts). That
+ * probe runs once per attempt row, and with no pages index on created_at every
+ * probe was a sequential scan of pages: a few thousand attempts over a large
+ * brain hit statement_timeout, dry run included. Protects: initSchema leaves a
+ * valid partial index on pages (source_id, created_at) WHERE deleted_at IS NULL,
+ * and the planner answers the real re-arm probe from it. PGLite always,
+ * Postgres when DATABASE_URL is set (testBackends).
+ */
+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 { conversationTriedSql } from '../src/core/facts/conversation-memo.ts';
+import { MIGRATIONS, runMigrations } from '../src/core/migrate.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: Array<{ backend: string; engine: BrainEngine }> = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema();
+ engines.push({ backend: 'pglite', engine });
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push({ backend: 'postgres', engine: pg.engine }); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const { engine } of engines) await engine.disconnect();
+ await closePostgres?.();
+});
+
+describe('#7379 pages (source_id, created_at) index for the relink re-arm probe', () => {
+ for (const backend of backends) {
+ const engineFor = () => engines.find(e => e.backend === backend)!.engine;
+
+ test(`[${backend}] initSchema builds a valid live-page (source_id, created_at) index`, async () => {
+ const rows = await engineFor().executeRaw<{ indexdef: string; valid: boolean }>(
+ `SELECT i.indexdef, x.indisvalid AS valid FROM pg_indexes i JOIN pg_index x ON x.indexrelid = to_regclass(i.indexname)
+ WHERE i.tablename = 'pages' AND i.indexname = 'pages_source_created_idx'`);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.valid).toBe(true);
+ expect(rows[0]!.indexdef).toContain('(source_id, created_at)');
+ expect(rows[0]!.indexdef).toContain('WHERE (deleted_at IS NULL)');
+ });
+
+ test(`[${backend}] upgrading a brain without the index builds it online`, async () => {
+ const engine = engineFor();
+ const latest = await engine.getConfig('version');
+ const version = MIGRATIONS.find(m => m.name === 'pages_source_created_index')!.version;
+ await engine.executeRaw('DROP INDEX pages_source_created_idx');
+ await engine.setConfig('version', String(version - 1));
+ await runMigrations(engine);
+ const [row] = await engine.executeRaw<{ valid: boolean }>(`SELECT indisvalid AS valid FROM pg_index WHERE indexrelid = to_regclass('pages_source_created_idx')`);
+ expect(row?.valid).toBe(true);
+ expect(await engine.getConfig('version')).toBe(latest);
+ });
+
+ test(`[${backend}] the conversation re-arm probe reads pages through that index`, async () => {
+ const engine = engineFor();
+ // Page rows as wide as real ones and a vacuumed table: without the index
+ // the planner reads pages with a per-probe Seq Scan (the reported plan).
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, created_at)
+ SELECT 'default', 'notes/idx-probe-' || g, 'note', 'Probe ' || g, repeat('x', 1500), now() - (g || ' minutes')::interval
+ FROM generate_series(1, 500) g`);
+ await engine.executeRaw('VACUUM ANALYZE pages');
+ const plan = (await engine.executeRaw<{ 'QUERY PLAN': string }>(`EXPLAIN SELECT f.id FROM facts f WHERE ${conversationTriedSql}`))
+ .map(r => r['QUERY PLAN']).join('\n');
+ expect(plan).toMatch(/Index (Only )?Scan using pages_source_created_idx on pages np/);
+ expect(plan).not.toContain('Seq Scan on pages np');
+ });
+ }
+});