Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: serialize boot schema DDL across processes with an advisory lock (#5977)

Adam Eivy07cb920e68d6
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 2db36def8f..5e720c7c85 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -171,6 +171,8 @@ The escape hatch is **guarded from bitrot by the test suite** (tests boot with `
`ensureSchema()` in `server/lib/db.js` applies **idempotent** schema upgrades on every boot (`CREATE TABLE IF NOT EXISTS`, `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`). Every index it creates — including the HNSW vector index and the GIN full-text index on `catalog_scraps` — is a plain, **non-`CONCURRENT`** build.
+There is one Postgres per install, shared by every process that opens it (the server, `portos-cos`, and every CoS agent worktree), so two processes calling `ensureSchema()` at once is routine — most visibly when an update restart overlaps an outgoing server still shutting down with the incoming one. The DDL block is idempotent **within one session** but not atomic **across sessions**: the per-table audit triggers are installed as a `DROP TRIGGER IF EXISTS` / `CREATE TRIGGER` pair, and two interleaved sessions can both pass the `DROP` before either reaches `CREATE`, so the second `CREATE` throws "already exists" (#5977). `ensureSchemaImpl()` takes a dedicated client and holds a session-level `pg_advisory_lock` around the entire DDL block (upgrades + catalog) to serialize this cluster-wide; the lock is released in `finally` on both the success and throw path, and a dropped connection (a hard kill mid-boot) releases it automatically so a later boot is never blocked by a stale lock.
+
The **first** time a given index materializes on a table that **already holds many rows** (an existing install upgrading into a newly-added index), Postgres takes a `SHARE` lock that **blocks writes** (INSERT/UPDATE/DELETE) to that table until the build completes. So an existing install can see a one-time write stall at boot proportional to the table's row count — HNSW builds are the slowest. Fresh installs never see this: they build every index on an **empty** table, so the lock is effectively instant.
This is left as-is deliberately rather than switched to `CREATE INDEX CONCURRENTLY`, because `CONCURRENTLY` cannot run inside a transaction block, needs its own retry/cleanup path (a failed concurrent build leaves an `INVALID` index that must be dropped by hand), and roughly doubles build time — too fragile to run unattended on every boot for a stall that only bites large-table upgrades.
diff --git a/server/lib/db.js b/server/lib/db.js
index 93ce6dfb15..dc116c1951 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -14,13 +14,20 @@ if (!process.env.PGPASSWORD) {
console.warn('⚠️ PGPASSWORD not set — using default. Set PGPASSWORD env var for production.');
}
-// Connection config from environment or defaults
-const pool = new Pool({
+// Connection config from environment or defaults. Exported so callers that
+// need a SECOND, independent connection to the same database (a raw `pg`
+// client outside the pool) don't have to re-derive these defaults and risk
+// drifting from them — see server/lib/db.test.js.
+export const POOL_CONFIG = {
host: process.env.PGHOST || 'localhost',
port: parseInt(process.env.PGPORT || '5432', 10),
database: process.env.PGDATABASE || 'portos',
user: process.env.PGUSER || 'portos',
password: process.env.PGPASSWORD || 'portos',
+};
+
+const pool = new Pool({
+ ...POOL_CONFIG,
max: 20,
idleTimeoutMillis: 30000,
// 10s (was 2s) — a single-user box periodically runs heavy local workloads
@@ -316,6 +323,19 @@ export async function checkHealth() {
// on pg_type / pg_class). Sharing one in-flight promise serializes them; it's
// cleared on settle so a deliberate later call (the gate runs it twice) still
// re-applies (cheap — ~30 no-op parses on an up-to-date DB).
+//
+// That dedup only covers callers IN THIS PROCESS. There is one Postgres per
+// install shared by every process that opens it — the server, `portos-cos`,
+// and every CoS agent worktree — so a restart during an update routinely
+// overlaps an outgoing server (still finishing its shutdown) with an
+// incoming one, both calling ensureSchema() at once. Each `DROP TRIGGER IF
+// EXISTS` / `CREATE TRIGGER` pair (server/scripts/init-db.sql) is idempotent
+// WITHIN one session but not atomic ACROSS sessions: A drops, B's drop is a
+// no-op, A creates, B's create then throws "already exists" (#5977). A
+// session-level Postgres advisory lock serializes the whole DDL block
+// cluster-wide — a dropped connection releases it automatically, so a hard
+// kill mid-boot can never strand a later boot waiting forever.
+export const SCHEMA_DDL_ADVISORY_LOCK_KEY = 5977001;
let ensureSchemaInFlight = null;
// Every DB-backed store self-runs ensureSchema() when it warms its backend at
// boot (memory, creative-director, media index, catalog, universe/story/writers
@@ -360,28 +380,59 @@ async function ensureSchemaImpl() {
// either — it must be issued from a dedicated non-transactional path (a
// standalone maintenance script / manual step run outside any transaction).
// See docs/STORAGE.md ("Boot schema upgrades & lock windows").
- const upgrades = buildUpgradeDdl();
- for (const sql of upgrades) {
- await pool.query(sql);
- }
+ // Serialize the whole DDL block cluster-wide with a session-level advisory
+ // lock — see SCHEMA_DDL_ADVISORY_LOCK_KEY above. Held on a single dedicated
+ // client (NOT the pool) for the entire block, released in `finally` on both
+ // the success and throw path. Session-level, not transaction-scoped: none of
+ // this runs inside a transaction (the non-CONCURRENT index builds above are
+ // deliberately not wrapped in one either — see the comment block above), so
+ // nothing here may be wrapped in withTransaction()/BEGIN.
+ const client = await pool.connect();
+ try {
+ const { rows: [{ locked }] } = await client.query('SELECT pg_try_advisory_lock($1) AS locked', [SCHEMA_DDL_ADVISORY_LOCK_KEY]);
+ if (!locked) {
+ // Another process is already running this block — normal during a boot
+ // overlap, but pg_advisory_lock's blocking wait is otherwise silent (no
+ // lock_timeout applies to advisory locks), so a peer stalled mid-DDL
+ // (e.g. the large-table index build documented above) would look like a
+ // hung boot with zero log output.
+ console.log('🗄️ Database schema DDL lock held by another process — waiting…');
+ await client.query('SELECT pg_advisory_lock($1)', [SCHEMA_DDL_ADVISORY_LOCK_KEY]);
+ }
+
+ const upgrades = buildUpgradeDdl();
+ for (const sql of upgrades) {
+ await client.query(sql);
+ }
- // Catalog block: every statement below is idempotent (CREATE IF NOT EXISTS
- // / CREATE OR REPLACE FUNCTION / DROP TRIGGER IF EXISTS + CREATE TRIGGER),
- // so we run the whole list on every boot rather than gating on table
- // presence. A previous probe that early-returned on "all four tables exist"
- // would skip the indexes / functions / triggers if the prior boot crashed
- // between the table CREATEs and the artifact CREATEs — leaving the schema
- // marked ready while update triggers and HNSW indexes were never installed.
- // Cost on a fully-applied install is ~30 Postgres no-op parses (<10ms).
+ // Catalog block: every statement below is idempotent (CREATE IF NOT EXISTS
+ // / CREATE OR REPLACE FUNCTION / DROP TRIGGER IF EXISTS + CREATE TRIGGER),
+ // so we run the whole list on every boot rather than gating on table
+ // presence. A previous probe that early-returned on "all four tables exist"
+ // would skip the indexes / functions / triggers if the prior boot crashed
+ // between the table CREATEs and the artifact CREATEs — leaving the schema
+ // marked ready while update triggers and HNSW indexes were never installed.
+ // Cost on a fully-applied install is ~30 Postgres no-op parses (<10ms).
- const catalogDDL = buildCatalogDdl();
+ const catalogDDL = buildCatalogDdl();
- for (const sql of catalogDDL) {
- await pool.query(sql);
- }
- if (!schemaUpgradeLogged) {
- console.log('🗄️ Database schema upgrades applied');
- schemaUpgradeLogged = true;
+ for (const sql of catalogDDL) {
+ await client.query(sql);
+ }
+ if (!schemaUpgradeLogged) {
+ console.log('🗄️ Database schema upgrades applied');
+ schemaUpgradeLogged = true;
+ }
+ } finally {
+ // A session-level advisory lock is tied to the CONNECTION, not the
+ // checkout — release(false) alone would return a still-locked connection
+ // to the pool, and every later ensureSchema() call (in this process AND
+ // every other process, since the lock is cluster-wide) would then block
+ // forever waiting on a lock nobody will ever release. If the unlock
+ // itself fails, destroy the connection instead: closing it releases the
+ // lock automatically, same as a hard kill mid-boot.
+ const unlocked = await client.query('SELECT pg_advisory_unlock($1)', [SCHEMA_DDL_ADVISORY_LOCK_KEY]).then(() => true, () => false);
+ client.release(!unlocked);
}
}
diff --git a/server/lib/db.test.js b/server/lib/db.test.js
new file mode 100644
index 0000000000..5371d50d85
--- /dev/null
+++ b/server/lib/db.test.js
@@ -0,0 +1,113 @@
+/**
+ * Postgres-backed regression coverage for the boot-schema-DDL race (#5977):
+ * two processes calling `ensureSchema()` at once used to interleave their
+ * `DROP TRIGGER IF EXISTS` / `CREATE TRIGGER` pairs and throw "already
+ * exists". `ensureSchemaImpl()` now wraps the whole DDL block in a
+ * session-level `pg_advisory_lock`, held on a dedicated client for the
+ * duration of the block and released in `finally`.
+ *
+ * These tests hold/probe the SAME advisory lock key from a second, raw `pg`
+ * client to prove the lock is actually cross-session (not just the existing
+ * in-process `ensureSchemaInFlight` dedup, which a second process doesn't
+ * share) and that it is released on both the success and throw path.
+ *
+ * `*.db.test.js`-style suite (named `db.test.js`, matched by the
+ * `**\/db.test.js` glob in `vitest.config.db.js`) → runs ONLY via
+ * `npm run test:db` against `portos_test`, never the real `portos` DB (the
+ * db.js runner guard + the skip below enforce this).
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import pg from 'pg';
+import { requireDbOrSkip } from './dbTestGate.js';
+
+const injectionState = vi.hoisted(() => ({ badUpgradeDdl: false }));
+
+vi.mock('./db/schema/index.js', async () => {
+ const actual = await vi.importActual('./db/schema/index.js');
+ return {
+ ...actual,
+ buildUpgradeDdl: () =>
+ injectionState.badUpgradeDdl
+ ? ['SELECT * FROM this_table_does_not_exist_5977']
+ : actual.buildUpgradeDdl(),
+ };
+});
+
+const { checkHealth, ensureSchema, close, POOL_CONFIG, SCHEMA_DDL_ADVISORY_LOCK_KEY } = await import('./db.js');
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ dbReady = true;
+ }
+}
+const runDb = requireDbOrSkip('lib/db.test', dbReady, skipReason);
+
+// A second, independent connection to the same database — reuses db.js's own
+// POOL_CONFIG so it can never drift from what the pool under test connects to.
+function makeRawClient() {
+ return new pg.Client(POOL_CONFIG);
+}
+
+// Always unlock-and-close the holder client, even when an assertion in
+// `run` throws — an unreleased holder leaves the advisory lock held forever,
+// which would hang every later ensureSchema() call (including afterAll's
+// close()) rather than just failing this one test.
+async function withLockHolder(run) {
+ const holder = makeRawClient();
+ await holder.connect();
+ try {
+ return await run(holder);
+ } finally {
+ await holder.query('SELECT pg_advisory_unlock($1)', [SCHEMA_DDL_ADVISORY_LOCK_KEY]).catch(() => {});
+ await holder.end();
+ }
+}
+
+afterAll(async () => {
+ if (dbReady) await close();
+});
+
+describe.skipIf(!runDb)('ensureSchema() boot DDL advisory lock (#5977)', () => {
+ beforeAll(async () => {
+ // Baseline: schema already applied once so later assertions aren't
+ // measuring first-install DDL cost.
+ await ensureSchema();
+ });
+
+ it('blocks behind a lock held by another session, then completes once it frees', async () => {
+ let resolved = false;
+ let schemaPromise;
+
+ await withLockHolder(async (holder) => {
+ await holder.query('SELECT pg_advisory_lock($1)', [SCHEMA_DDL_ADVISORY_LOCK_KEY]);
+
+ schemaPromise = ensureSchema().then(() => { resolved = true; });
+
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(resolved).toBe(false);
+ });
+
+ await schemaPromise;
+ expect(resolved).toBe(true);
+ });
+
+ it('releases the lock (and rejects) when the DDL block throws', async () => {
+ injectionState.badUpgradeDdl = true;
+ await expect(ensureSchema()).rejects.toThrow();
+ injectionState.badUpgradeDdl = false;
+
+ await withLockHolder(async (holder) => {
+ const { rows } = await holder.query('SELECT pg_try_advisory_lock($1) AS locked', [SCHEMA_DDL_ADVISORY_LOCK_KEY]);
+ expect(rows[0].locked).toBe(true);
+ });
+
+ // The DDL block still runs on every call — a genuine schema error on one
+ // call must not leave a later, valid call permanently blocked or skipped.
+ await expect(ensureSchema()).resolves.toBeUndefined();
+ });
+});