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

address review (codex): degrade backup when auto-detected Postgres is down

[._.]/ Adam Eivy8484755ac4a5
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index d85d176d6a..b5d70d0f3c 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -122,8 +122,16 @@ export function BackupTab() {
} else {
setPgBackup(result?.pgBackup ?? null);
setBackupStatus(result?.status ?? 'ok');
- const dbNote = result?.pgBackup?.status === 'failed' ? ' (DB dump FAILED)' : '';
- toast.success(`Backup complete — ${result?.filesChanged ?? 0} files changed${dbNote}`, { icon: '💾' });
+ const filesChanged = result?.filesChanged ?? 0;
+ if (result?.pgBackup?.status === 'failed') {
+ // Degraded run: the file backup succeeded but the DB dump didn't. Don't
+ // dress it up as a success — and don't double-announce the DB failure,
+ // which the BACKUP_DB_DUMP_FAILED socket error toast already surfaces
+ // (useErrorNotifications). This toast just acknowledges the file portion.
+ toast(`Backup complete — ${filesChanged} files changed; database dump failed`, { icon: '⚠️' });
+ } else {
+ toast.success(`Backup complete — ${filesChanged} files changed`, { icon: '💾' });
+ }
getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch(() => {});
}
return result;
diff --git a/server/services/backup.js b/server/services/backup.js
index ab4d89a454..2a08456be5 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -13,6 +13,7 @@ import { join, resolve, relative, isAbsolute } from 'path';
import { PATHS, ensureDir, readJSONFile, sha256File } from '../lib/fileUtils.js';
import { getEvent } from './eventScheduler.js';
import { checkHealth } from '../lib/db.js';
+import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
import { getIo } from './socket.js';
@@ -231,21 +232,29 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
* Run pg_dump to create a PostgreSQL backup alongside the rsync snapshot.
* Returns an explicit status so the caller can distinguish "no PG configured"
* (benign, file mode) from "PG configured but dump failed" (data at risk):
- * { status: 'ok', sizeBytes, tableCount, path }
- * { status: 'skipped', reason: 'not_configured' } (file/auto mode, no PG)
+ * { status: 'ok', sizeBytes, tableCount }
+ * { status: 'skipped', reason: 'not_configured' } (PG not the active backend)
* { status: 'failed', reason: 'pg_unreachable'|'pg_dump_missing'|'dump_error'|'empty_dump', error }
+ * (pg_unreachable fires when Postgres is the active backend — explicit or
+ * auto-detected — but the DB is down at backup time)
* @param {string} outputPath - Path to write the SQL dump file
*/
export async function dumpPostgres(outputPath) {
const health = await checkHealth();
if (!health.connected || !health.hasSchema) {
- // PG unreachable or uninitialized. In file/auto mode this is the expected,
- // benign case (the install legitimately runs without Postgres). But when the
- // install EXPLICITLY requires Postgres (MEMORY_BACKEND=postgres), an
- // unreachable DB is a real backup failure — data that lives only in PG won't
- // be captured — so degrade the backup and alert rather than silently skip.
- if (process.env.MEMORY_BACKEND === 'postgres') {
- return { status: 'failed', reason: 'pg_unreachable', error: health.error || 'PostgreSQL required (MEMORY_BACKEND=postgres) but not reachable' };
+ // PG unreachable or uninitialized. When the install legitimately runs
+ // without Postgres this is the expected, benign case. But when Postgres is
+ // the ACTIVE memory backend, an unreachable DB is a real backup failure —
+ // data that lives only in PG won't be captured — so degrade the backup and
+ // alert rather than silently skip. Postgres is active when it's required
+ // explicitly (MEMORY_BACKEND=postgres) OR when it was auto-detected at
+ // startup (MEMORY_BACKEND unset and the resolved backend is 'postgres').
+ // The auto-detect case is the common default install, so gating only on the
+ // env var would let a real DB outage read as a green "not configured" run.
+ const env = process.env.MEMORY_BACKEND;
+ const postgresIsActive = env === 'postgres' || (env !== 'file' && getBackendName() === 'postgres');
+ if (postgresIsActive) {
+ return { status: 'failed', reason: 'pg_unreachable', error: health.error || 'PostgreSQL is the active memory backend but is not reachable' };
}
return { status: 'skipped', reason: 'not_configured' };
}
@@ -302,7 +311,12 @@ export async function dumpPostgres(outputPath) {
const sql = await readFile(outputPath, 'utf-8').catch(() => '');
const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;
console.log(`💾 pg_dump complete: ${Math.round(info.size / 1024)}KB, ${tableCount} tables`);
- resolve({ status: 'ok', sizeBytes: info.size, tableCount, path: outputPath });
+ // Don't return the absolute dump path: this result is persisted into
+ // state.pgBackup and surfaced to the client via GET /api/backup/status,
+ // the backup:completed socket event, and the /run response. No client
+ // reads it (restorePostgres recomputes its own sqlPath), so leaking an
+ // internal FS path serves no purpose.
+ resolve({ status: 'ok', sizeBytes: info.size, tableCount });
});
proc.on('error', (err) => {
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index b3637da4ab..974439c89a 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -18,6 +18,12 @@ vi.mock('../lib/db.js', () => ({
checkHealth: vi.fn(),
}));
+// Mock the memory-backend resolver so dumpPostgres can tell whether Postgres is
+// the ACTIVE backend (explicit or auto-detected) when the DB is unreachable.
+vi.mock('./memoryBackend.js', () => ({
+ getBackendName: vi.fn(() => null),
+}));
+
import { EventEmitter } from 'events';
import { spawn } from 'child_process';
// Partial mock: only override spawn. Preserve execFile et al. because
@@ -36,6 +42,7 @@ vi.mock('fs/promises', async (importOriginal) => {
});
import { checkHealth } from '../lib/db.js';
+import { getBackendName } from './memoryBackend.js';
import * as fs from 'fs/promises';
import { DEFAULT_EXCLUDES, computeEffectiveExcludes } from './backup.js';
@@ -154,13 +161,15 @@ describe('dumpPostgres status classification', () => {
({ dumpPostgres } = await import('./backup.js'));
});
- it('returns skipped/not_configured when PG is not connected (file/auto mode)', async () => {
+ it('returns skipped/not_configured when PG is not connected and not the active backend', async () => {
const prev = process.env.MEMORY_BACKEND;
delete process.env.MEMORY_BACKEND;
+ getBackendName.mockReturnValue('file'); // auto-detect resolved to file
checkHealth.mockResolvedValue({ connected: false, hasSchema: false });
const result = await dumpPostgres('/tmp/x.sql');
expect(result).toEqual({ status: 'skipped', reason: 'not_configured' });
expect(spawn).not.toHaveBeenCalled();
+ getBackendName.mockReturnValue(null);
if (prev === undefined) delete process.env.MEMORY_BACKEND; else process.env.MEMORY_BACKEND = prev;
});
@@ -175,6 +184,35 @@ describe('dumpPostgres status classification', () => {
if (prev === undefined) delete process.env.MEMORY_BACKEND; else process.env.MEMORY_BACKEND = prev;
});
+ it('returns failed/pg_unreachable when PG was auto-detected (MEMORY_BACKEND unset) but is down at backup time', async () => {
+ // Regression: in the common default config PortOS auto-detects Postgres as
+ // the active backend at startup. A later DB outage must degrade the backup,
+ // not read as a benign "not configured" skip — otherwise a green backup
+ // silently omits everything that lives in Postgres.
+ const prev = process.env.MEMORY_BACKEND;
+ delete process.env.MEMORY_BACKEND;
+ getBackendName.mockReturnValue('postgres'); // resolved backend at startup
+ checkHealth.mockResolvedValue({ connected: false, hasSchema: false, error: 'ECONNREFUSED' });
+ const result = await dumpPostgres('/tmp/x.sql');
+ expect(result.status).toBe('failed');
+ expect(result.reason).toBe('pg_unreachable');
+ expect(spawn).not.toHaveBeenCalled();
+ getBackendName.mockReturnValue(null);
+ if (prev === undefined) delete process.env.MEMORY_BACKEND; else process.env.MEMORY_BACKEND = prev;
+ });
+
+ it('returns skipped/not_configured in explicit file mode even if a stale backend name says postgres', async () => {
+ const prev = process.env.MEMORY_BACKEND;
+ process.env.MEMORY_BACKEND = 'file';
+ getBackendName.mockReturnValue('postgres'); // must be ignored — file is explicit
+ checkHealth.mockResolvedValue({ connected: false, hasSchema: false });
+ const result = await dumpPostgres('/tmp/x.sql');
+ expect(result).toEqual({ status: 'skipped', reason: 'not_configured' });
+ expect(spawn).not.toHaveBeenCalled();
+ getBackendName.mockReturnValue(null);
+ if (prev === undefined) delete process.env.MEMORY_BACKEND; else process.env.MEMORY_BACKEND = prev;
+ });
+
it('returns skipped/not_configured when connected but no schema', async () => {
checkHealth.mockResolvedValue({ connected: true, hasSchema: false });
const result = await dumpPostgres('/tmp/x.sql');