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: avoid repeating schema upgrades for each store startup

[._.]/ Adam Eivy13c2d71d1a33
diff --git a/server/lib/db.js b/server/lib/db.js
index 080aa87b64..5c770a1372 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -302,8 +302,8 @@ export async function checkHealth() {
// idempotent DDL list concurrently can intermittently error or deadlock on
// Postgres system catalogs (concurrent CREATE TABLE/INDEX IF NOT EXISTS contend
// 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).
+// retained as successful readiness after it settles so sequential store warms
+// do not repeat the full DDL block.
//
// 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`,
@@ -318,12 +318,13 @@ export async function checkHealth() {
// kill mid-boot can never strand a later boot waiting forever.
export const SCHEMA_DDL_ADVISORY_LOCK_KEY = 5977001;
let ensureSchemaInFlight = null;
+let schemaEnsured = false;
// Every DB-backed store self-runs ensureSchema() when it warms its backend at
// boot (memory, creative-director, media index, catalog, universe/story/writers
// stores, pipeline series/issues, plus the boot DB gate). Those warm
-// sequentially, so the in-flight dedup above can't collapse them — each re-runs
-// the idempotent DDL (cheap no-ops) and would otherwise re-log the same line.
-// Log it once per process so the boot output isn't a wall of identical lines.
+// sequentially, so in-flight dedup alone cannot collapse them. Successful
+// readiness lasts for this process; a restart still applies that version's
+// complete upgrade list. Failed attempts remain retryable.
let schemaUpgradeLogged = false;
/**
@@ -331,11 +332,15 @@ let schemaUpgradeLogged = false;
* Each statement uses IF NOT EXISTS so it's safe to run on every startup.
* Add new ALTER TABLE statements here when the schema evolves.
*
- * Concurrent calls share a single in-flight execution (see ensureSchemaInFlight).
+ * Concurrent calls share an execution; later calls reuse successful readiness.
+ * `force` explicitly reapplies the current process's DDL for repair tooling.
*/
-export async function ensureSchema() {
+export async function ensureSchema({ force = false } = {}) {
if (ensureSchemaInFlight) return ensureSchemaInFlight;
- ensureSchemaInFlight = ensureSchemaImpl().finally(() => { ensureSchemaInFlight = null; });
+ if (schemaEnsured && !force) return;
+ schemaEnsured = false;
+ ensureSchemaInFlight = ensureSchemaImpl().then(() => { schemaEnsured = true; })
+ .finally(() => { ensureSchemaInFlight = null; });
return ensureSchemaInFlight;
}
@@ -400,7 +405,7 @@ async function ensureSchemaImpl() {
// 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
+ // so we run the whole list once per process 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
diff --git a/server/lib/db.schemaLifecycle.test.js b/server/lib/db.schemaLifecycle.test.js
new file mode 100644
index 0000000000..122b516ee2
--- /dev/null
+++ b/server/lib/db.schemaLifecycle.test.js
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({
+ query: vi.fn(), release: vi.fn(), connect: vi.fn(),
+}));
+vi.mock('pg', () => ({ default: { Pool: class {
+ on() {}
+ connect = state.connect;
+} } }));
+vi.mock('./db/schema/index.js', () => ({
+ buildUpgradeDdl: () => ['upgrade schema'],
+ buildCatalogDdl: () => ['repair catalog'],
+}));
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ state.query.mockImplementation(async () => ({ rows: [{ locked: true }] }));
+ state.connect.mockResolvedValue({ query: state.query, release: state.release });
+});
+
+describe('schema readiness across store startup', () => {
+ it('shares concurrent initialization and skips DDL for later store warms', async () => {
+ const { ensureSchema } = await import('./db.js');
+ await Promise.all([ensureSchema(), ensureSchema()]);
+ await ensureSchema();
+ expect(state.connect).toHaveBeenCalledTimes(1);
+ expect(state.query.mock.calls.map(([sql]) => sql)).toEqual([
+ 'SELECT pg_try_advisory_lock($1) AS locked', 'upgrade schema',
+ 'repair catalog', 'SELECT pg_advisory_unlock($1)',
+ ]);
+ expect(state.release).toHaveBeenCalledWith(false);
+ });
+
+ it('allows forced repair and retries after its failure without caching partial work', async () => {
+ const { ensureSchema } = await import('./db.js');
+ await ensureSchema();
+ state.query.mockImplementation(async sql => {
+ if (sql === 'repair catalog') throw new Error('catalog repair failed');
+ return { rows: [{ locked: true }] };
+ });
+ await expect(ensureSchema({ force: true })).rejects.toThrow('catalog repair failed');
+ expect(state.query).toHaveBeenLastCalledWith('SELECT pg_advisory_unlock($1)', expect.any(Array));
+ state.query.mockImplementation(async () => ({ rows: [{ locked: true }] }));
+ await ensureSchema();
+ await ensureSchema();
+ expect(state.connect).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/server/lib/db.test.js b/server/lib/db.test.js
index 5371d50d85..151de495c1 100644
--- a/server/lib/db.test.js
+++ b/server/lib/db.test.js
@@ -86,7 +86,7 @@ describe.skipIf(!runDb)('ensureSchema() boot DDL advisory lock (#5977)', () => {
await withLockHolder(async (holder) => {
await holder.query('SELECT pg_advisory_lock($1)', [SCHEMA_DDL_ADVISORY_LOCK_KEY]);
- schemaPromise = ensureSchema().then(() => { resolved = true; });
+ schemaPromise = ensureSchema({ force: true }).then(() => { resolved = true; });
await new Promise((resolve) => setTimeout(resolve, 300));
expect(resolved).toBe(false);
@@ -98,7 +98,7 @@ describe.skipIf(!runDb)('ensureSchema() boot DDL advisory lock (#5977)', () => {
it('releases the lock (and rejects) when the DDL block throws', async () => {
injectionState.badUpgradeDdl = true;
- await expect(ensureSchema()).rejects.toThrow();
+ await expect(ensureSchema({ force: true })).rejects.toThrow();
injectionState.badUpgradeDdl = false;
await withLockHolder(async (holder) => {
@@ -106,8 +106,7 @@ describe.skipIf(!runDb)('ensureSchema() boot DDL advisory lock (#5977)', () => {
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.
+ // A failed forced repair clears readiness, so a later valid call retries.
await expect(ensureSchema()).resolves.toBeUndefined();
});
});