Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema): a base-schema replay Postgres aborts as a deadlock victim against a live reader runs again (#6143)

garrytan4e148e3fa8ad
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index d60bb8aa68..407c2a777c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -23,7 +23,7 @@ import { traceSqlOptions } from './sql-trace.ts';
import { hasPostgresCancellationCapability, postgresCancellationUnavailable, reserveWithCancellation } from './postgres-engine/cancellation.ts';
import { runBoundedStatement } from './postgres-engine/bounded-statement.ts';
import { needsJitOff, runJitOffStatement } from './postgres-engine/jit-off-statement.ts';
-import { schemaDiagnosticConnection, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';
+import { retrySchemaReplayOnDeadlock, schemaDiagnosticConnection, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';
export { hasPostgresCancellationCapability } from './postgres-engine/cancellation.ts';
import type {
BrainEngine,
@@ -620,7 +620,7 @@ export class PostgresEngine implements BrainEngine {
// transaction pooler. Codex P1 finding from v0.36 dreamy-thompson wave.
await this.applyForwardReferenceBootstrap(conn);
- await withSchemaLockTimeout(conn, () => conn.unsafe(sqlText), { step: 'replay', diagnostic: schemaDiagnosticConnection(this._savedConfig?.database_url) }); // #5227: bounded wait, typed schema_lock_blocked
+ await retrySchemaReplayOnDeadlock(() => withSchemaLockTimeout(conn, () => conn.unsafe(sqlText), { step: 'replay', diagnostic: schemaDiagnosticConnection(this._savedConfig?.database_url) })); // #5227: bounded wait, typed schema_lock_blocked; #6143: a deadlock victim runs again
// Run any pending migrations automatically
const { applied } = await (await import('./migrate.ts')).runMigrations(this); // engine-dynamic-import-ok: initSchema only, keeps the ~220 migration modules off every connect
diff --git a/src/core/postgres-engine/schema-lock-timeout.ts b/src/core/postgres-engine/schema-lock-timeout.ts
index d4274610ed..31365d2cc5 100644
--- a/src/core/postgres-engine/schema-lock-timeout.ts
+++ b/src/core/postgres-engine/schema-lock-timeout.ts
@@ -141,3 +141,24 @@ export async function withSchemaLockTimeout<T>(conn: Queryable, run: () => Promi
await conn.unsafe(`SET lock_timeout = '${previous.replace(/'/g, '')}'`).catch(() => {});
}
}
+
+
+/** #6143: attempts of the schema replay when Postgres aborts it as a deadlock victim. */
+const SCHEMA_REPLAY_DEADLOCK_ATTEMPTS = 3;
+
+/**
+ * #6143: the base-schema replay is one implicit transaction that takes ACCESS EXCLUSIVE locks as it goes (pages'
+ * triggers long before sources' managed_writer_guard), while live readers (the resident consumer's probe, serve queries)
+ * lock tables in their own order, so a reader holding sources that then reads pages deadlocks with it. Postgres aborts
+ * the replay, which waited first, and rolls all of it back, so running it again is safe.
+ */
+export async function retrySchemaReplayOnDeadlock<T>(run: () => Promise<T>, attempt = 1): Promise<T> {
+ try {
+ return await run();
+ } catch (error) {
+ if ((error as { code?: unknown }).code !== '40P01' || attempt >= SCHEMA_REPLAY_DEADLOCK_ATTEMPTS) throw error;
+ process.stderr.write(` Schema replay deadlocked with a concurrent query (40P01); nothing was applied, retrying (${attempt + 1}/${SCHEMA_REPLAY_DEADLOCK_ATTEMPTS})\n`);
+ await new Promise(resolve => setTimeout(resolve, 250 * attempt));
+ return retrySchemaReplayOnDeadlock(run, attempt + 1);
+ }
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 557d5fde77..d6a4d90430 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -413,6 +413,7 @@ test/repair-receipt-compaction.test.ts
test/repair-rename-identity-6729.test.ts
test/retrieval-coverage-notices.test.ts
test/schema-missing-tables.test.ts
+test/schema-replay-deadlock-6143.test.ts
test/scripts/test-stress-postgres.test.ts
test/search-read-keyword-bound.test.ts
test/search/page-rank-cut.test.ts
diff --git a/test/schema-replay-deadlock-6143.test.ts b/test/schema-replay-deadlock-6143.test.ts
new file mode 100644
index 0000000000..a0c2c248bb
--- /dev/null
+++ b/test/schema-replay-deadlock-6143.test.ts
@@ -0,0 +1,34 @@
+/**
+ * #6143: the base-schema replay (PostgresEngine.initSchema) is one implicit transaction that takes ACCESS EXCLUSIVE
+ * locks as it goes, pages' triggers long before sources' managed_writer_guard. A live reader that holds sources and then
+ * reads pages (the resident persistence consumer's idle probe did, on the nightly arm) closes a cycle with it, and
+ * Postgres aborts the replay with deadlock_detected. The replay rolls back whole, so initSchema runs it again.
+ * Forced: a reader transaction takes sources, waits until the replay is queued on sources, then reads pages. Postgres only.
+ */
+import { describe, expect, test } from 'bun:test';
+import postgres from '#postgres';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+describe.skipIf(!testBackends().includes('postgres'))('#6143 schema replay against a live reader', () => {
+ test('a reader that holds sources and then reads pages no longer fails the replay with a deadlock', async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const reader = postgres(pg.databaseUrl, { max: 1, onnotice: () => {} });
+ const watcher = postgres(pg.databaseUrl, { max: 1, onnotice: () => {} });
+ try {
+ let replay: Promise<unknown> | undefined;
+ await reader.begin(async sql => {
+ await sql`SELECT 1 FROM sources LIMIT 1`;
+ replay = pg.engine.initSchema().then(() => 'ok', (error: { code?: string; message?: string }) => `${error.code ?? ''} ${error.message ?? error}`);
+ for (let i = 0; i < 400; i++) {
+ const [row] = await watcher<{ n: number }[]>`SELECT count(*)::int AS n FROM pg_locks WHERE NOT granted AND relation = 'sources'::regclass`;
+ if (row!.n > 0) break;
+ await Bun.sleep(25);
+ }
+ await sql`SELECT 1 FROM pages LIMIT 1`;
+ });
+ expect(await replay).toBe('ok');
+ expect(await pg.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pg_trigger WHERE tgname = 'managed_writer_guard' AND tgrelid = 'sources'::regclass")).toEqual([{ n: 1 }]);
+ } finally { await reader.end(); await watcher.end(); await pg.close(); }
+ }, 120_000);
+});