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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: add retry logic for Postgres connection at boot (#8455)
[._.]/ Adam Eivy0cbad6377769
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 3d3bea9e21..9d6b91660d 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -240,7 +240,14 @@ module.exports = {// force-exit so the app always controls its own exit. (The graceful path now// completes in ~1s — the double-close hang it used to stall on is fixed in// server/index.js's shutdown() — so this ceiling is a backstop, not the norm.)- kill_timeout: 12000+ kill_timeout: 12000,+ // Exponential backoff restart delay when the server exits repeatedly (e.g.+ // when Postgres is slow to start on boot). PM2 starts at 1s, doubles after+ // each restart, and resets on a stable run (stays up longer than min_uptime,+ // default 1s). This prevents a crash loop that monopolizes the CPU and starves+ // slow database startup. The DB gate (gateOnDatabase) retries for ~120s before+ // exiting, so this delay kicks in only after that window is exhausted.+ exp_backoff_restart_delay: 1000// NOTE: do NOT set `treekill: false` here to protect long media jobs from// restart-SIGINT. Tried 2026-06-14: pm2 then fails to reap the old node// process on restart, so it lingers holding :5555 and the new instancediff --git a/server/services/bootstrapSequence.js b/server/services/bootstrapSequence.jsindex 5789b4dd58..bf2b4331b7 100644--- a/server/services/bootstrapSequence.js+++ b/server/services/bootstrapSequence.js@@ -156,17 +156,45 @@ export const armCommissionScheduler = ({* the creative-catalog schema are required — the catalog has no file-backed* equivalent.*+ * When the DB is unreachable (health.connected === false), retry with capped+ * exponential backoff (1 s → 2 s → 4 s … capped at 10 s) for up to 120 s before+ * giving up. This handles transient DB delays on host reboot or slow Postgres+ * startup. The schema-missing path (connected but incomplete schema) still fails+ * immediately — that is a setup error, not a transient one.+ ** `escapeHatch` (MEMORY_BACKEND=file / NODE_ENV=test, dev+test only) downgrades- * the fail-fast to a warning. `onUnbootable` defaults to exiting the process;- * it is injected so the gate can be exercised without killing the test runner.+ * the fail-fast to a warning and skips retry. `onUnbootable` defaults to exiting+ * the process; it is injected so the gate can be exercised without killing the+ * test runner. `sleep`, `now`, and `retryWindowMs` are injected for testing.*/export const gateOnDatabase = async ({checkHealth,ensureSchema,escapeHatch,- onUnbootable = () => process.exit(1)+ onUnbootable = () => process.exit(1),+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+ now = () => Date.now(),+ retryWindowMs = 120000}) => {let health = await checkHealth();++ // Retry if unreachable. Keep schema-missing path fail-fast (it's a setup error).+ if (!health.connected && !escapeHatch) {+ const deadline = now() + retryWindowMs;+ let delayMs = 1000;+ let attempt = 1;+ while (now() < deadline) {+ console.log(`⏳ PostgreSQL unreachable — retrying in ${Math.floor(delayMs / 1000)}s (attempt ${attempt})`);+ await sleep(delayMs);+ health = await checkHealth();+ if (health.connected) break;+ // Exponential backoff, capped at 10s.+ delayMs = Math.min(delayMs * 2, 10000);+ attempt += 1;+ }+ }++ // If connected, try to upgrade an incomplete schema.if (health.connected && (!health.hasSchema || !health.hasCatalogSchema)) {// try/catch is appropriate here: this runs outside the request lifecycle, so// an uncaught throw would crash boot. A truly uninitialized DB (base tables@@ -178,6 +206,7 @@ export const gateOnDatabase = async ({console.error(`🗄️ Schema upgrade on boot failed: ${err.message}`);}}+const dbReady = Boolean(health.connected && health.hasSchema && health.hasCatalogSchema);if (!escapeHatch && !dbReady) {const reason = health.connected ? 'required schema missing' : `unreachable (${health.error || 'connection failed'})`;diff --git a/server/services/bootstrapSequence.test.js b/server/services/bootstrapSequence.test.jsindex 1a0f677702..6426e57253 100644--- a/server/services/bootstrapSequence.test.js+++ b/server/services/bootstrapSequence.test.js@@ -304,16 +304,30 @@ describe('gateOnDatabase', () => {});it('refuses to start when the DB is unreachable and no escape hatch is set', async () => {- const onUnbootable = vi.fn();- const result = await gateOnDatabase({- checkHealth: vi.fn(async () => ({ connected: false, error: 'ECONNREFUSED' })),- ensureSchema: vi.fn(),- escapeHatch: false,- onUnbootable- });- expect(result).toEqual({ dbReady: false });- expect(onUnbootable).toHaveBeenCalledTimes(1);- expect(console.error).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL is required but unreachable'));+ vi.useFakeTimers();+ try {+ let timeMs = 0;+ const sleep = vi.fn(async (ms) => {+ timeMs += ms;+ vi.advanceTimersByTime(ms);+ });+ const now = () => timeMs;+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: false, error: 'ECONNREFUSED' })),+ ensureSchema: vi.fn(),+ escapeHatch: false,+ onUnbootable,+ sleep,+ now,+ retryWindowMs: 120000+ });+ expect(result).toEqual({ dbReady: false });+ expect(onUnbootable).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL is required but unreachable'));+ } finally {+ vi.useRealTimers();+ }});it('falls through the failed upgrade of an uninitialized DB to the fail-fast', async () => {@@ -342,6 +356,134 @@ describe('gateOnDatabase', () => {expect(onUnbootable).not.toHaveBeenCalled();expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('booting via escape hatch'));});++ it('retries with exponential backoff when DB is unreachable, succeeds on 3rd attempt', async () => {+ vi.useFakeTimers();+ try {+ const { calls, step } = createRecorder();+ const healthy = { connected: true, hasSchema: true, hasCatalogSchema: true };+ // Unreachable on probes 1 & 2, healthy on probe 3.+ const probes = [+ { connected: false, error: 'ECONNREFUSED' },+ { connected: false, error: 'ECONNREFUSED' },+ healthy+ ];+ let timeMs = 0;+ const sleep = vi.fn(async (ms) => {+ timeMs += ms;+ vi.advanceTimersByTime(ms);+ });+ const now = () => timeMs;++ const result = await gateOnDatabase({+ checkHealth: step('checkHealth', async () => Promise.resolve(probes.shift())),+ ensureSchema: step('ensureSchema', () => Promise.resolve()),+ escapeHatch: false,+ onUnbootable: vi.fn(),+ sleep,+ now,+ retryWindowMs: 120000+ });++ expect(result).toEqual({ dbReady: true });+ expect(calls).toEqual(['checkHealth', 'checkHealth', 'checkHealth']);+ // Logged two retry attempts (before probes 2 and 3).+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL unreachable — retrying in 1s'));+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL unreachable — retrying in 2s'));+ // Total elapsed time: 1s + 2s = 3s.+ expect(timeMs).toBe(3000);+ } finally {+ vi.useRealTimers();+ }+ });++ it('exits after retrying for the full window when DB stays unreachable', async () => {+ vi.useFakeTimers();+ try {+ let timeMs = 0;+ const sleep = vi.fn(async (ms) => {+ timeMs += ms;+ vi.advanceTimersByTime(ms);+ });+ const now = () => timeMs;+ const onUnbootable = vi.fn();++ await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: false, error: 'ECONNREFUSED' })),+ ensureSchema: vi.fn(),+ escapeHatch: false,+ onUnbootable,+ sleep,+ now,+ retryWindowMs: 6000 // Small window for testing: 1s + 2s + 4s = 7s > 6s, so it stops at 6s.+ });++ expect(onUnbootable).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('PostgreSQL is required but unreachable'));+ // Elapsed time should be close to the window (6s), plus the final check after window expiry.+ expect(timeMs).toBeGreaterThanOrEqual(6000);+ } finally {+ vi.useRealTimers();+ }+ });++ it('skips retry and fails immediately when DB is unreachable and escape hatch is set', async () => {+ vi.useFakeTimers();+ try {+ const sleep = vi.fn();+ const onUnbootable = vi.fn();+ const result = await gateOnDatabase({+ checkHealth: vi.fn(async () => ({ connected: false, error: 'ECONNREFUSED' })),+ ensureSchema: vi.fn(),+ escapeHatch: true,+ onUnbootable,+ sleep+ });++ expect(result).toEqual({ dbReady: false });+ expect(sleep).not.toHaveBeenCalled();+ expect(onUnbootable).not.toHaveBeenCalled();+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('booting via escape hatch'));+ } finally {+ vi.useRealTimers();+ }+ });++ it('still fails fast when DB is reachable but schema is missing, even after retry attempts', async () => {+ vi.useFakeTimers();+ try {+ const { calls, step } = createRecorder();+ let timeMs = 0;+ const sleep = vi.fn(async (ms) => {+ timeMs += ms;+ vi.advanceTimersByTime(ms);+ });+ const now = () => timeMs;+ const onUnbootable = vi.fn();++ await gateOnDatabase({+ checkHealth: step('checkHealth', async () =>+ Promise.resolve({ connected: true, hasSchema: false, hasCatalogSchema: false })+ ),+ ensureSchema: step('ensureSchema', async () => {+ throw new Error('base tables missing');+ }),+ escapeHatch: false,+ onUnbootable,+ sleep,+ now,+ retryWindowMs: 120000+ });++ // Only one probe (no retry because DB is connected). No re-check after ensureSchema fails.+ expect(calls).toEqual(['checkHealth', 'ensureSchema']);+ expect(sleep).not.toHaveBeenCalled();+ expect(onUnbootable).toHaveBeenCalledTimes(1);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('Schema upgrade on boot failed'));+ } finally {+ vi.useRealTimers();+ }+ });});describe('runDbAndCatalogMigrations', () => {