Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(migrate): apply the #1178 invalid-index-guard fix to 10 more historical sites (#3192)
Masae7439828f154
diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex ff666d3d5e..708bb0c4cb 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -546,18 +546,7 @@ export const MIGRATIONS: Migration[] = [sql: '',handler: async (engine) => {if (engine.kind === 'postgres') {- await engine.runMigration(- 14,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'idx_pages_updated_at_desc' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS idx_pages_updated_at_desc';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 14, 'idx_pages_updated_at_desc');await engine.runMigration(14,`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_pages_updated_at_desc@@ -1663,18 +1652,7 @@ export const MIGRATIONS: Migration[] = [// 3. Partial index for the autopilot purge sweep. Postgres CONCURRENTLY// avoids the SHARE lock on `pages`; PGLite has no concurrent writers.if (engine.kind === 'postgres') {- // Pre-drop any invalid index from a prior CONCURRENTLY failure (matches v14 pattern).- await engine.runMigration(34, `- DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_deleted_at_purge_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_deleted_at_purge_idx';- END IF;- END $$;- `);+ await dropInvalidConcurrentIndex(engine, 34, 'pages_deleted_at_purge_idx');await engine.runMigration(34, `CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_deleted_at_purge_idxON pages (deleted_at) WHERE deleted_at IS NOT NULL;@@ -2011,18 +1989,7 @@ export const MIGRATIONS: Migration[] = [// 2. Expression index for since/until date-range filters.if (engine.kind === 'postgres') {- // Pre-drop any invalid index from a prior CONCURRENTLY failure.- await engine.runMigration(38, `- DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_coalesce_date_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_coalesce_date_idx';- END IF;- END $$;- `);+ await dropInvalidConcurrentIndex(engine, 38, 'pages_coalesce_date_idx');await engine.runMigration(38, `CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_coalesce_date_idxON pages ((COALESCE(effective_date, updated_at)));@@ -3584,19 +3551,7 @@ export const MIGRATIONS: Migration[] = [sql: '',handler: async (engine) => {if (engine.kind === 'postgres') {- // Pre-drop invalid remnant from a failed CONCURRENTLY attempt.- await engine.runMigration(- 71,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'takes_resolved_at_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS takes_resolved_at_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 71, 'takes_resolved_at_idx');await engine.runMigration(71,`CREATE INDEX CONCURRENTLY IF NOT EXISTS takes_resolved_at_idx@@ -4256,20 +4211,7 @@ export const MIGRATIONS: Migration[] = [await engine.runMigration(91, columnsAndTrigger);if (engine.kind === 'postgres') {- // Pre-drop any invalid index from a prior CONCURRENTLY failure- // (matches v14 pattern).- await engine.runMigration(- 91,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_generation_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_generation_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 91, 'pages_generation_idx');await engine.runMigration(91,`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_generation_idx ON pages (generation);`@@ -4523,18 +4465,7 @@ export const MIGRATIONS: Migration[] = [sql: '',handler: async (engine) => {if (engine.kind === 'postgres') {- await engine.runMigration(- 96,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'idx_facts_extract_conversation_session' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS idx_facts_extract_conversation_session';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 96, 'idx_facts_extract_conversation_session');await engine.runMigration(96,`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_facts_extract_conversation_session@@ -4576,18 +4507,7 @@ export const MIGRATIONS: Migration[] = [transaction: false,handler: async (engine) => {if (engine.kind === 'postgres') {- await engine.runMigration(- 97,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_dedup_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_dedup_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 97, 'pages_dedup_idx');await engine.runMigration(97,`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_dedup_idx@@ -4755,18 +4675,7 @@ export const MIGRATIONS: Migration[] = [);if (engine.kind === 'postgres') {- await engine.runMigration(- 103,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'content_chunks_stale_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS content_chunks_stale_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 103, 'content_chunks_stale_idx');await engine.runMigration(103,`CREATE INDEX CONCURRENTLY IF NOT EXISTS content_chunks_stale_idx@@ -4800,18 +4709,7 @@ export const MIGRATIONS: Migration[] = [sql: '',handler: async (engine) => {if (engine.kind === 'postgres') {- await engine.runMigration(- 104,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_atom_source_hash_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_atom_source_hash_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 104, 'pages_atom_source_hash_idx');await engine.runMigration(104,`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_atom_source_hash_idx@@ -5112,18 +5010,7 @@ export const MIGRATIONS: Migration[] = [`ALTER TABLE pages ADD COLUMN IF NOT EXISTS links_extracted_at TIMESTAMPTZ;`);if (engine.kind === 'postgres') {- await engine.runMigration(- 112,- `DO $$ BEGIN- IF EXISTS (- SELECT 1 FROM pg_index i- JOIN pg_class c ON c.oid = i.indexrelid- WHERE c.relname = 'pages_links_extracted_at_idx' AND NOT i.indisvalid- ) THEN- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS pages_links_extracted_at_idx';- END IF;- END $$;`- );+ await dropInvalidConcurrentIndex(engine, 112, 'pages_links_extracted_at_idx');await engine.runMigration(112,`CREATE INDEX CONCURRENTLY IF NOT EXISTS pages_links_extracted_at_idxdiff --git a/test/e2e/migration-drop-invalid-concurrent-index.test.ts b/test/e2e/migration-drop-invalid-concurrent-index.test.tsindex 56d18d50fe..0fcad66da1 100644--- a/test/e2e/migration-drop-invalid-concurrent-index.test.ts+++ b/test/e2e/migration-drop-invalid-concurrent-index.test.ts@@ -1,18 +1,25 @@/**- * E2E regression for #1178: migration v66 (`embed_stale_partial_index`)- * pre-drops an invalid CONCURRENTLY-build remnant using- * `DO $$ BEGIN ... EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS <name>'; END IF;- * END $$;`. Postgres rejects CONCURRENTLY from any function/EXECUTE context,- * so the guard's EXISTS check passed but the EXECUTE inside it always threw- * "DROP INDEX CONCURRENTLY cannot be executed from a function" — the- * migration only failed on brains carrying an invalid-index leftover from a- * prior interrupted CREATE INDEX CONCURRENTLY.+ * E2E regression for #1178: 11 historical migrations (v14, v34, v38, v66, v71,+ * v91, v96, v97, v103, v104, v112) pre-drop an invalid CONCURRENTLY-build+ * remnant using `DO $$ BEGIN ... EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS+ * <name>'; END IF; END $$;`. Postgres rejects CONCURRENTLY from any+ * function/EXECUTE context, so the guard's EXISTS check passed but the+ * EXECUTE inside it always threw "DROP INDEX CONCURRENTLY cannot be executed+ * from a function" — each migration only failed on brains carrying an+ * invalid-index leftover from a prior interrupted CREATE INDEX CONCURRENTLY.*- * The fix replaces the DO block with dropInvalidConcurrentIndex(): the- * validity probe runs as a plain application-level SELECT, and the DROP (when- * needed) runs as its own top-level statement. This test reproduces the- * issue's exact repro steps against real Postgres and confirms the migration- * now recovers instead of throwing.+ * The fix (introduced for the issue-reported migration, v66, in a prior PR)+ * replaces the DO block with dropInvalidConcurrentIndex(): the validity probe+ * runs as a plain application-level SELECT, and the DROP (when needed) runs+ * as its own top-level statement. This PR applies the same helper to the+ * remaining 10 historical sites the issue's own re-scan found — the+ * "recurrence" half of #1178 (5 new copies had shipped since the bug was+ * first reported, via copy-paste of the nearest similar migration).+ *+ * This test reproduces the issue's exact repro steps against real Postgres+ * for the two most structurally distinct sites (v66, already covered by the+ * prior PR, kept here for full-suite context; v112, a second independent+ * site) and confirms both migrations now recover instead of throwing.** Real Postgres only — gated by DATABASE_URL, skips otherwise.*@@ -96,4 +103,19 @@ describeE2E('migration invalid-remnant recovery (#1178)', () => {// wouldn't catch a spurious drop+recreate (codex review, #1178).expect(await indexOid('idx_chunks_embedding_null')).toBe(oidBefore);});++ test('v112 (pages_links_extracted_at_idx, a second independent site from this batch): same recovery', async () => {+ await plantInvalidIndex(+ 'pages_links_extracted_at_idx',+ `CREATE INDEX pages_links_extracted_at_idx ON pages (source_id, links_extracted_at)`,+ );+ expect(await isIndexValid('pages_links_extracted_at_idx')).toBe(false);++ const v112 = MIGRATIONS.find(m => m.version === 112);+ expect(v112?.handler).toBeDefined();++ await expect(v112!.handler!(getEngine())).resolves.toBeUndefined();++ expect(await isIndexValid('pages_links_extracted_at_idx')).toBe(true);+ });});diff --git a/test/migrate.test.ts b/test/migrate.test.tsindex f35daaff80..93e312854c 100644--- a/test/migrate.test.ts+++ b/test/migrate.test.ts@@ -624,27 +624,78 @@ describe('migrate v14 — pages_updated_at_index (handler-based, engine-aware)',expect(v14!.sql).toBe('');});- test('v14 handler source contains CONCURRENTLY + invalid-index cleanup for Postgres branch', async () => {+ test('v14 handler source delegates invalid-remnant cleanup to the shared helper (#1178)', async () => {const { readFileSync } = await import('fs');const src = readFileSync('src/core/migrate.ts', 'utf-8');const v14Start = src.indexOf("name: 'pages_updated_at_index'");expect(v14Start).toBeGreaterThan(-1);const v14Block = src.slice(v14Start, v14Start + 3000);- expect(v14Block).toContain('pg_index');- expect(v14Block).toContain('indisvalid');- expect(v14Block).toContain('DROP INDEX CONCURRENTLY IF EXISTS idx_pages_updated_at_desc');+ expect(v14Block).toContain("dropInvalidConcurrentIndex(engine, 14, 'idx_pages_updated_at_desc')");expect(v14Block).toContain('CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_pages_updated_at_desc');- // Order within the handler body: DROP IF EXISTS must precede CREATE IF NOT EXISTS,- // so a failed prior CONCURRENTLY build is cleaned before re-create. Anchor on the- // explicit "IF EXISTS" / "IF NOT EXISTS" phrases so the header doc-comment- // (which mentions both unqualified) doesn't fool the ordering assertion.- const dropIdx = v14Block.indexOf('DROP INDEX CONCURRENTLY IF EXISTS');+ expect(v14Block).not.toContain('DO $$');+ // Order within the handler body: the cleanup call must precede CREATE IF NOT+ // EXISTS, so a failed prior CONCURRENTLY build is cleaned before re-create.+ const dropIdx = v14Block.indexOf('dropInvalidConcurrentIndex');const createIdx = v14Block.indexOf('CREATE INDEX CONCURRENTLY IF NOT EXISTS');expect(dropIdx).toBeLessThan(createIdx);expect(v14Block).toContain('engine.kind');});});+// #1178: DO $$ ... EXECUTE 'DROP INDEX CONCURRENTLY ...' END $$ is rejected by+// Postgres whenever the guard condition fires (CONCURRENTLY can't run from any+// function/EXECUTE context). All 11 historical migrations that pre-drop an+// invalid CONCURRENTLY remnant now route through the dropInvalidConcurrentIndex()+// helper instead. This locks the whole file against the old shape reappearing —+// e.g. a future migration copy-pasting the nearest similar one instead of+// reaching for the helper.+describe('migrate — DROP INDEX CONCURRENTLY invalid-remnant cleanup (#1178, file-wide)', () => {+ const KNOWN_SITES: Array<{ version: number; indexName: string }> = [+ { version: 14, indexName: 'idx_pages_updated_at_desc' },+ { version: 34, indexName: 'pages_deleted_at_purge_idx' },+ { version: 38, indexName: 'pages_coalesce_date_idx' },+ { version: 66, indexName: 'idx_chunks_embedding_null' },+ { version: 71, indexName: 'takes_resolved_at_idx' },+ { version: 91, indexName: 'pages_generation_idx' },+ { version: 96, indexName: 'idx_facts_extract_conversation_session' },+ { version: 97, indexName: 'pages_dedup_idx' },+ { version: 103, indexName: 'content_chunks_stale_idx' },+ { version: 104, indexName: 'pages_atom_source_hash_idx' },+ { version: 112, indexName: 'pages_links_extracted_at_idx' },+ ];++ test('no DO $$ ... EXECUTE .DROP INDEX CONCURRENTLY. shape remains anywhere in migrate.ts', async () => {+ const { readFileSync } = await import('fs');+ const src = readFileSync('src/core/migrate.ts', 'utf-8');+ // `DO $$ ... END $$` blocks are a normal Postgres idiom used all over this+ // file for unrelated conditional DDL — only the specific combination that+ // EXECUTEs a DROP INDEX CONCURRENTLY string is the #1178 bug shape.+ expect(src).not.toMatch(/EXECUTE\s+'DROP INDEX CONCURRENTLY/);+ });++ test('every known invalid-remnant site calls dropInvalidConcurrentIndex(engine, version, indexName)', async () => {+ const { readFileSync } = await import('fs');+ const src = readFileSync('src/core/migrate.ts', 'utf-8');+ for (const { version, indexName } of KNOWN_SITES) {+ expect(src).toContain(`dropInvalidConcurrentIndex(engine, ${version}, '${indexName}')`);+ }+ });++ test('dropInvalidConcurrentIndex helper itself probes pg_index.indisvalid and issues a standalone DROP (no DO block)', async () => {+ const { readFileSync } = await import('fs');+ const src = readFileSync('src/core/migrate.ts', 'utf-8');+ const helperStart = src.indexOf('async function dropInvalidConcurrentIndex');+ expect(helperStart).toBeGreaterThan(-1);+ const helperBlock = src.slice(helperStart, helperStart + 1200);+ expect(helperBlock).toContain('pg_index');+ expect(helperBlock).toContain('indisvalid');+ expect(helperBlock).toContain('executeRaw');+ expect(helperBlock).toContain('DROP INDEX CONCURRENTLY IF EXISTS');+ expect(helperBlock).not.toContain('DO $$');+ expect(helperBlock).not.toContain('EXECUTE ');+ });+});+describe('migrate v15 — minion_jobs_max_stalled_default_5', () => {const v15 = MIGRATIONS.find(m => m.version === 15);test('v15 exists and alters max_stalled default to 5', () => {