Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(migrate): drop invalid CONCURRENTLY-build remnants without a DO block (#3191)

Masa2b00b7abeb1f
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 9dd889af9e..e0caafbe2f 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -110,6 +110,43 @@ export class MigrationRetryExhausted extends Error {
}
}
+/**
+ * Postgres-only: drops `indexName` iff it currently exists AND is invalid — the
+ * leftover of a `CREATE INDEX CONCURRENTLY` that failed partway through. Callers
+ * MUST already be inside an `engine.kind === 'postgres'` branch (PGLite has no
+ * concurrent-build invalid-index concept and no `pg_index` catalog in the same
+ * shape) and MUST run this before their own `CREATE INDEX CONCURRENTLY IF NOT
+ * EXISTS`, since a stale invalid entry blocks the create from ever landing.
+ *
+ * Deliberately does NOT wrap the drop in `DO $$ ... EXECUTE '...' END $$`
+ * (#1178): Postgres rejects `CONCURRENTLY` from any function/EXECUTE context —
+ * the guard condition works, but the EXECUTE that follows always throws
+ * "DROP INDEX CONCURRENTLY cannot be executed from a function". The validity
+ * probe runs as a plain application-level SELECT instead, and the DROP (when
+ * needed) runs as its own top-level `runMigration` call.
+ */
+async function dropInvalidConcurrentIndex(
+ engine: BrainEngine,
+ version: number,
+ indexName: string,
+): Promise<boolean> {
+ // to_regclass() resolves the unqualified name through search_path — the same
+ // resolution the unqualified DROP below relies on — instead of matching
+ // pg_class.relname bare, which could hit a same-named index in a different
+ // schema on a non-default search_path (codex review, #1178).
+ const rows = await engine.executeRaw<{ invalid: boolean }>(
+ `SELECT NOT i.indisvalid AS invalid
+ FROM pg_index i
+ WHERE i.indexrelid = to_regclass($1)`,
+ [indexName],
+ );
+ const isInvalid = rows.some((r) => r.invalid);
+ if (isInvalid) {
+ await engine.runMigration(version, `DROP INDEX CONCURRENTLY IF EXISTS ${indexName};`);
+ }
+ return isInvalid;
+}
+
// Migrations are embedded here, not loaded from files.
// Add new migrations at the end. Never modify existing ones.
// Exported for tests that structurally assert migration contents (e.g., "v9 must
@@ -3280,18 +3317,7 @@ export const MIGRATIONS: Migration[] = [
sql: '',
handler: async (engine) => {
if (engine.kind === 'postgres') {
- await engine.runMigration(
- 66,
- `DO $$ BEGIN
- IF EXISTS (
- SELECT 1 FROM pg_index i
- JOIN pg_class c ON c.oid = i.indexrelid
- WHERE c.relname = 'idx_chunks_embedding_null' AND NOT i.indisvalid
- ) THEN
- EXECUTE 'DROP INDEX CONCURRENTLY IF EXISTS idx_chunks_embedding_null';
- END IF;
- END $$;`
- );
+ await dropInvalidConcurrentIndex(engine, 66, 'idx_chunks_embedding_null');
await engine.runMigration(
66,
`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chunks_embedding_null
diff --git a/test/e2e/migration-drop-invalid-concurrent-index.test.ts b/test/e2e/migration-drop-invalid-concurrent-index.test.ts
new file mode 100644
index 0000000000..56d18d50fe
--- /dev/null
+++ b/test/e2e/migration-drop-invalid-concurrent-index.test.ts
@@ -0,0 +1,99 @@
+/**
+ * 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.
+ *
+ * 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.
+ *
+ * Real Postgres only — gated by DATABASE_URL, skips otherwise.
+ *
+ * Run: DATABASE_URL=... bun test test/e2e/migration-drop-invalid-concurrent-index.test.ts
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB, getConn, getEngine, runMigrationsUpTo } from './helpers.ts';
+import { MIGRATIONS, LATEST_VERSION } from '../../src/core/migrate.ts';
+
+const skip = !hasDatabase();
+const describeE2E = skip ? describe.skip : describe;
+
+if (skip) {
+ console.log('Skipping migration-drop-invalid-concurrent-index E2E tests (DATABASE_URL not set)');
+}
+
+async function isIndexValid(indexName: string): Promise<boolean | null> {
+ const conn = getConn();
+ const rows = await conn<Array<{ invalid: boolean }>>`
+ SELECT NOT i.indisvalid AS invalid
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ WHERE c.relname = ${indexName}
+ `;
+ if (rows.length === 0) return null; // does not exist
+ return !rows[0].invalid;
+}
+
+/** OID of the index relation — used to prove a "no-op" run didn't silently drop+recreate (a recreated index gets a new OID under the same name). */
+async function indexOid(indexName: string): Promise<string | null> {
+ const conn = getConn();
+ const rows = await conn<Array<{ oid: string }>>`SELECT to_regclass(${indexName})::oid::text AS oid`;
+ return rows[0]?.oid ?? null;
+}
+
+/** Simulates a prior failed `CREATE INDEX CONCURRENTLY` per the issue's repro. */
+async function plantInvalidIndex(indexName: string, createSQL: string): Promise<void> {
+ const conn = getConn();
+ await conn.unsafe(`DROP INDEX IF EXISTS ${indexName}`);
+ await conn.unsafe(createSQL);
+ await conn.unsafe(`UPDATE pg_index SET indisvalid = false WHERE indexrelid = '${indexName}'::regclass`);
+}
+
+describeE2E('migration invalid-remnant recovery (#1178)', () => {
+ beforeAll(async () => {
+ await setupDB();
+ await runMigrationsUpTo(getEngine(), LATEST_VERSION);
+ }, 30_000);
+
+ afterAll(async () => {
+ await teardownDB();
+ });
+
+ test('v66 (idx_chunks_embedding_null, the issue-reported migration): invalid leftover no longer breaks the migration', async () => {
+ await plantInvalidIndex(
+ 'idx_chunks_embedding_null',
+ `CREATE INDEX idx_chunks_embedding_null ON content_chunks (page_id, chunk_index) WHERE embedding IS NULL`,
+ );
+ expect(await isIndexValid('idx_chunks_embedding_null')).toBe(false);
+
+ const v66 = MIGRATIONS.find(m => m.version === 66);
+ expect(v66?.handler).toBeDefined();
+
+ // Pre-fix, this threw "DROP INDEX CONCURRENTLY cannot be executed from a function".
+ await expect(v66!.handler!(getEngine())).resolves.toBeUndefined();
+
+ expect(await isIndexValid('idx_chunks_embedding_null')).toBe(true);
+ });
+
+ test('re-running the migration when the index is already valid is a no-op (no spurious drop/recreate)', async () => {
+ expect(await isIndexValid('idx_chunks_embedding_null')).toBe(true);
+ const oidBefore = await indexOid('idx_chunks_embedding_null');
+ expect(oidBefore).not.toBeNull();
+
+ const v66 = MIGRATIONS.find(m => m.version === 66);
+ await v66!.handler!(getEngine());
+
+ expect(await isIndexValid('idx_chunks_embedding_null')).toBe(true);
+ // Same OID proves the valid index survived untouched — validity alone
+ // wouldn't catch a spurious drop+recreate (codex review, #1178).
+ expect(await indexOid('idx_chunks_embedding_null')).toBe(oidBefore);
+ });
+});
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 13067b2c01..f35daaff80 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -736,28 +736,48 @@ describe('migrate v66 — embed_stale_partial_index (D6)', () => {
expect(v66!.sql).toBe('');
});
- test('v66 handler source: CONCURRENTLY + invalid-index cleanup on Postgres branch', async () => {
+ test('v66 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 v66Start = src.indexOf("name: 'embed_stale_partial_index'");
expect(v66Start).toBeGreaterThan(-1);
const v66Block = src.slice(v66Start, v66Start + 3000);
- expect(v66Block).toContain('pg_index');
- expect(v66Block).toContain('indisvalid');
- expect(v66Block).toContain('DROP INDEX CONCURRENTLY IF EXISTS idx_chunks_embedding_null');
+ // #1178: `DO $$ BEGIN ... EXECUTE 'DROP INDEX CONCURRENTLY ...'; END $$;`
+ // is rejected by Postgres whenever the guard condition actually fires
+ // (CONCURRENTLY can't run from any function/EXECUTE context). The fix
+ // moves the probe + drop to the dropInvalidConcurrentIndex() helper
+ // (defined above MIGRATIONS, tested directly in
+ // test/e2e/migration-drop-invalid-concurrent-index.test.ts) — the
+ // migration body just calls it.
+ expect(v66Block).toContain("dropInvalidConcurrentIndex(engine, 66, 'idx_chunks_embedding_null')");
expect(v66Block).toContain('CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chunks_embedding_null');
+ expect(v66Block).not.toMatch(/EXECUTE\s+'DROP INDEX CONCURRENTLY/);
// Partial index predicate must match the production query in
// postgres-engine.ts / pglite-engine.ts: `WHERE embedding IS NULL`.
expect(v66Block).toContain('WHERE embedding IS NULL');
- // DROP IF EXISTS must precede CREATE IF NOT EXISTS so a failed prior
+ // The cleanup call must precede CREATE IF NOT EXISTS so a failed prior
// CONCURRENTLY build is cleaned before re-create.
- const dropIdx = v66Block.indexOf('DROP INDEX CONCURRENTLY IF EXISTS');
+ const dropIdx = v66Block.indexOf('dropInvalidConcurrentIndex');
const createIdx = v66Block.indexOf('CREATE INDEX CONCURRENTLY IF NOT EXISTS');
expect(dropIdx).toBeLessThan(createIdx);
// Branches on engine.kind (handler-pattern from v14).
expect(v66Block).toContain('engine.kind');
});
+ 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 ');
+ });
+
test('v66 idempotent flag is true (re-run safety)', () => {
expect(v66!.idempotent).toBe(true);
});