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: restore older database backups across new foreign keys (#8623)

[._.]/ Adam Eivy107bdc2e7d81
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index ca320462d8..786f019523 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -770,7 +770,7 @@ export function BackupTab() {
This replays <code>portos-db.sql</code> from snapshot <code className="text-gray-300">{restoreTarget?.request.snapshotId}</code>
{' '}on <span className="text-gray-300">{restoreTarget?.sourceLabel}</span>
{restorePreview && <> ({formatBytes(restorePreview.sizeBytes || 0)} · {restorePreview.tableCount} tables)</>}
- {' '}into the live PostgreSQL database. Existing rows may be overwritten.
+ {' '}as a full replacement of the live PostgreSQL database. All current application tables and rows are replaced, including tables added after this snapshot. Newer tables are recreated empty and current migrations run afterward.
</p>
<div className="flex justify-end gap-2">
<button onClick={() => { setRestoreTarget(null); setRestorePreview(null); }} className="px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors">Cancel</button>
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 7ada7abdc9..3e36a355a2 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -151,3 +151,20 @@ This is **read-time resolution only**: nothing on disk changes, sparse configura
- [Storage Classification Contract](./STORAGE.md) — which data lives in Postgres vs files (and therefore which half of a snapshot captures it).
- [`docs/superpowers/specs/2026-06-05-verified-pg-backup-design.md`](./superpowers/specs/2026-06-05-verified-pg-backup-design.md) — design rationale for verified, restorable DB backups.
+
+### Restoring an older database snapshot
+
+Database restore is a **full replacement**, not a merge. It removes current
+PortOS tables, functions and sequence state before replaying the snapshot,
+including tables introduced after the backup. Current schema upgrades and
+ordered migrations then recreate newer tables consistently without retaining
+post-snapshot records. The public namespace's owner and permissions are retained.
+
+Preview performs read-only ownership/object/dependency checks. Unknown objects
+or external dependencies refuse the restore; the reset uses `RESTRICT`, never
+an unrestricted cascade. Reset and dump replay share one PostgreSQL transaction
+with `ON_ERROR_STOP`: a replay failure restores the previous rows and constraints.
+Schema reconciliation follows the commit; a reconciliation failure explicitly
+reports that replay committed and recovery still needs attention. Application
+database operations drain before reset; new operations receive a temporary
+maintenance error until replay and reconciliation finish (including failures).
diff --git a/server/lib/README.md b/server/lib/README.md
index e29c435657..9cb0a02cd9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -600,7 +600,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. |
| `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` / cached `getCudaComputeCapability()` are a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH` and SGLang provider filtering; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |
| `systemCapabilities.js` | Machine-local capability snapshot plus the shared three-state hardware requirement evaluator. Captures coarse platform, architecture, Apple Silicon, memory, CPU, and cached CUDA facts; derives requirements for media models, local-LLM catalog entries, and provider runtimes; hides only known-incompatible choices while preserving `unknown` probe results. |
-| `db.js` | PostgreSQL connection pool. |
+| `db.js` | PostgreSQL connection pool and `withDatabaseMaintenance(fn)` admission/drain gate for atomic restore and reconciliation. |
| `db/` | Boot DDL for the PostgreSQL schema, split per domain (#2832). `db/schema/index.js` re-exports each module's statement array and composes the two ordered lists `ensureSchemaImpl()` runs on every boot (`buildUpgradeDdl()` then `buildCatalogDdl()`). **Statement order is load-bearing** — append inside the domain module and leave the composer order alone. See `db/schema/README.md` for the module catalog. |
| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |
| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 12ed2ec4a2..51e373d553 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -6,6 +6,7 @@
*/
import pg from 'pg';
+import { AsyncLocalStorage } from 'node:async_hooks';
import { isTestRunner } from './runtimeEnv.js';
const { Pool } = pg;
@@ -198,6 +199,47 @@ const GUARDED_CLIENT_HANDLER = {
},
};
+// Admission is synchronous, before any pool checkout. A maintenance operation
+// closes admission and drains existing operations (including whole transactions)
+// before touching the schema. Only its async context can run reconciliation.
+const databaseContext = new AsyncLocalStorage();
+const activeOperations = new Set();
+let maintenanceActive = false;
+
+function maintenanceError() {
+ return Object.assign(new Error('Database restore in progress; retry after it finishes.'), {
+ status: 503, code: 'DATABASE_MAINTENANCE',
+ });
+}
+
+async function databaseOperation(fn) {
+ if (databaseContext.getStore()?.active) return fn();
+ if (maintenanceActive) throw maintenanceError();
+ const context = { active: true };
+ const pending = databaseContext.run(context, async () => fn());
+ activeOperations.add(pending);
+ try {
+ return await pending;
+ } finally {
+ context.active = false;
+ activeOperations.delete(pending);
+ }
+}
+
+/** Drain admitted database work and reject new work until restore completes. */
+export async function withDatabaseMaintenance(fn) {
+ if (maintenanceActive || databaseContext.getStore()?.active) throw maintenanceError();
+ maintenanceActive = true;
+ const context = { active: true };
+ try {
+ await Promise.allSettled([...activeOperations]);
+ return await databaseContext.run(context, fn);
+ } finally {
+ context.active = false;
+ maintenanceActive = false;
+ }
+}
+
/**
* Execute a query against the connection pool.
* @param {string} text - SQL query text with $1, $2, etc. placeholders
@@ -210,7 +252,7 @@ export async function query(text, params) {
// author calls query('INSERT …') directly, or a backend selector mis-chose
// Postgres because NODE_ENV wasn't 'test').
assertWriteAllowed(text);
- return pool.query(text, params);
+ return databaseOperation(() => pool.query(text, params));
}
/**
@@ -238,6 +280,10 @@ export async function getServerMajorVersion() {
* @returns {Promise<T>}
*/
export async function withTransaction(fn) {
+ return databaseOperation(() => runTransaction(fn));
+}
+
+async function runTransaction(fn) {
const client = await pool.connect();
// Guard the client's row writes with the same backstop as query(). The raw
// pg client bypasses query() entirely, so without this wrapper a test-runner
@@ -350,7 +396,11 @@ let schemaUpgradeLogged = false;
* 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({ force = false } = {}) {
+export async function ensureSchema(options = {}) {
+ return databaseOperation(() => ensureSchemaReady(options));
+}
+
+async function ensureSchemaReady({ force = false } = {}) {
if (ensureSchemaInFlight) return ensureSchemaInFlight;
if (schemaEnsured && !force) return;
schemaEnsured = false;
diff --git a/server/lib/db.transaction.test.js b/server/lib/db.transaction.test.js
index 157262b1e7..b6d275cb41 100644
--- a/server/lib/db.transaction.test.js
+++ b/server/lib/db.transaction.test.js
@@ -14,7 +14,7 @@ vi.mock('pg', () => ({
},
}));
-import { withTransaction } from './db.js';
+import { withTransaction, query, withDatabaseMaintenance } from './db.js';
function makeClient(query) {
return {
@@ -109,3 +109,40 @@ describe('withTransaction', () => {
expect(client.release).toHaveBeenCalledWith(dropError);
});
});
+
+
+describe('database restore admission', () => {
+ it('drains whole transactions, rejects new work, permits recovery, and releases after failure', async () => {
+ pool.client = makeClient(vi.fn().mockResolvedValue({}));
+ let finishTransaction;
+ let enteredTransaction;
+ const entered = new Promise(resolve => { enteredTransaction = resolve; });
+ const transaction = withTransaction(async client => {
+ enteredTransaction();
+ await new Promise(resolve => { finishTransaction = resolve; });
+ await client.query('SELECT 1');
+ });
+ await entered;
+ let enteredMaintenance = false;
+ let finishMaintenance;
+ const maintenance = withDatabaseMaintenance(async () => {
+ enteredMaintenance = true;
+ await query('SELECT 2');
+ await withTransaction(client => client.query('SELECT 3'));
+ await new Promise(resolve => { finishMaintenance = resolve; });
+ throw new Error('replay failed');
+ });
+ const rejected = expect(maintenance).rejects.toThrow('replay failed');
+ await expect(query('SELECT 4')).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE', status: 503 });
+ await expect(withTransaction(() => {})).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });
+ await expect(withDatabaseMaintenance(() => {})).rejects.toMatchObject({ code: 'DATABASE_MAINTENANCE' });
+ expect(enteredMaintenance).toBe(false);
+ finishTransaction();
+ await transaction;
+ await vi.waitFor(() => expect(finishMaintenance).toBeTypeOf('function'));
+ finishMaintenance();
+ await rejected;
+ await expect(query('SELECT 5')).resolves.toBeUndefined();
+ await expect(withDatabaseMaintenance(async () => 'recovered')).resolves.toBe('recovered');
+ });
+});
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 41a3fafe82..7ed1a13036 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -338,6 +338,18 @@ describe('backup routes', () => {
);
});
+ it('reports a refused preflight and a concurrent maintenance request without success', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.restorePostgres.mockResolvedValueOnce({ status: 'failed', reason: 'restore_preflight' });
+ const refused = await request(buildApp()).post('/api/backup/restore-db').send({ snapshotId: 'snap-1' });
+ expect(refused.body).toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ backup.restorePostgres.mockRejectedValueOnce(Object.assign(new Error('Restore in progress'), {
+ status: 503, code: 'DATABASE_MAINTENANCE',
+ }));
+ const busy = await request(buildApp()).post('/api/backup/restore-db').send({ snapshotId: 'snap-1', dryRun: false });
+ expect(busy.status).toBe(503);
+ });
+
it('forwards source with database restore preview and execution requests', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
backup.restorePostgres.mockResolvedValue({ status: 'ok', dryRun: true });
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index 7509f3554a..79d7b3b009 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -1,14 +1,12 @@
-/**
- * Real psql regression for restoring a pre-federation folder schema.
- * Runs only via test:db against a guarded test database, never live records.
- */
+/** Real clean-dump restore regressions. Only guarded test databases. */
import { afterAll, describe, expect, it } from 'vitest';
-import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises';
+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
-import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+import { checkHealth, ensureSchema, query, close, getServerMajorVersion, POOL_CONFIG } from '../lib/db.js';
import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { runDbMigrations } from '../scripts/run-db-migrations.js';
import { listFolders } from './writersRoom/db.js';
@@ -17,23 +15,36 @@ const ready = requireDbOrSkip('services/backup.db.test',
health.connected && spawnSync('psql', ['--version']).status === 0,
'test database or PostgreSQL client tools unavailable');
let dest;
+let dumpPath;
const folderId = 'restore-schema-folder-probe';
const issueId = 'restore-schema-issue-probe';
+const personId = '00000000-0000-4000-8000-000000000862';
const pendingMigration = '007-storyboard-scene-durable-ids.js';
+const connectionArgs = ['-h', POOL_CONFIG.host, '-p', String(POOL_CONFIG.port), '-U', POOL_CONFIG.user, '-d', POOL_CONFIG.database];
+const childEnv = { ...process.env, PGPASSWORD: POOL_CONFIG.password };
afterAll(async () => {
if (ready) {
+ await query('DROP SCHEMA IF EXISTS restore_external CASCADE');
+ await query('DROP TABLE IF EXISTS public.unexpected_restore_record');
await ensureSchema({ force: true });
await query('DELETE FROM writers_room_folders WHERE id = $1', [folderId]);
await query('DELETE FROM pipeline_issues WHERE id = $1', [issueId]);
+ await query("DELETE FROM tribe_people WHERE id = $1 OR id = '00000000-0000-4000-8000-000000000863'", [personId]);
+ await query("DELETE FROM app_quality_measurements WHERE app_id = 'restore-probe'");
await runDbMigrations();
}
await close();
if (dest) await rm(dest, { recursive: true, force: true });
});
+async function restore(dryRun = false, snapshotId = 'old-schema') {
+ const { restorePostgres } = await import('./backup.js');
+ return restorePostgres(dest, snapshotId, { source: 'fixture-source', dryRun });
+}
+
describe.skipIf(!ready)('restore older database schema', () => {
- it('repairs cached schema readiness and migrates the restored ledger while preserving rows', async () => {
+ it('restores a real pre-FK dump, discards newer rows, and runs schema repair and ordered migrations', async () => {
await ensureSchema({ force: true });
await runDbMigrations();
const appliedBefore = await query('SELECT id, applied_at FROM schema_migrations WHERE id <> $1 ORDER BY id', [pendingMigration]);
@@ -42,41 +53,69 @@ describe.skipIf(!ready)('restore older database schema', () => {
await query("INSERT INTO pipeline_issues (id, series_id, data) VALUES ($1, 'restore-schema-series', $2)", [
issueId, { stages: { storyboards: { scenes: [{ description: 'Synthetic scene' }] } } },
]);
-
+ await query("INSERT INTO tribe_people (id, name) VALUES ($1, 'Snapshot person')", [personId]);
+ // The snapshot predates this table and its inbound FK to tribe_people.
+ await query('DROP TABLE beeper_participants, app_quality_measurements');
+ await query('ALTER TABLE writers_room_folders DROP COLUMN deleted, DROP COLUMN deleted_at');
+ await query('DELETE FROM schema_migrations WHERE id = $1', [pendingMigration]);
dest = await mkdtemp(join(tmpdir(), 'portos-restore-schema-'));
const snapshotDir = join(dest, 'snapshots', 'fixture-source', 'old-schema');
await mkdir(snapshotDir, { recursive: true });
- // Synthetic clean dump from before folder tombstones and migration 007.
- // Avoid requiring pg_dump to match the test server's major version: CI's
- // psql client can replay this SQL across versions, unlike an older pg_dump.
- const ledgerRows = appliedBefore.rows.map(row =>
- `('${row.id.replaceAll("'", "''")}', '${row.applied_at.toISOString()}')`,
- ).join(', ');
- await writeFile(join(snapshotDir, 'portos-db.sql'), `
- DROP TABLE IF EXISTS writers_room_folders;
- CREATE TABLE writers_room_folders (
- id TEXT PRIMARY KEY, parent_id TEXT, name TEXT NOT NULL,
- sort_order INTEGER DEFAULT 0, data JSONB NOT NULL DEFAULT '{}',
- created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW()
- );
- INSERT INTO writers_room_folders (id, name, data)
- VALUES ('${folderId}', 'Recovered folder', '${JSON.stringify(folder)}');
- DROP TABLE IF EXISTS schema_migrations;
- CREATE TABLE schema_migrations (id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ DEFAULT NOW());
- INSERT INTO schema_migrations (id, applied_at) VALUES ${ledgerRows};
- `);
+ dumpPath = join(snapshotDir, 'portos-db.sql');
+ const { binary } = await resolvePgDumpBinary(await getServerMajorVersion());
+ const dump = spawnSync(binary, [...connectionArgs, '--no-owner', '--no-acl', '--clean', '--if-exists', '-f', dumpPath], { env: childEnv, encoding: 'utf8' });
+ expect(dump.status, dump.stderr).toBe(0);
- // Readiness and the migration ledger both reflect the current version.
- // Replay must replace the ledger and rerun 007 against the synthetic issue.
- await query('UPDATE writers_room_folders SET data = $2 WHERE id = $1', [folderId, { id: folderId, name: 'After backup' }]);
- const { restorePostgres } = await import('./backup.js');
- const result = await restorePostgres(dest, 'old-schema', { source: 'fixture-source', dryRun: false });
- expect(result).toMatchObject({ status: 'ok', dryRun: false });
+ // Boot current schema, including its new inbound foreign key. An empty
+ // newer table is sufficient to break the old direct-replay implementation.
+ await ensureSchema({ force: true });
+ await runDbMigrations();
+ await query("UPDATE tribe_people SET name = 'After backup' WHERE id = $1", [personId]);
+ await query("INSERT INTO tribe_people (id, name) VALUES ('00000000-0000-4000-8000-000000000863', 'Post-snapshot person')");
+ // A simpler approved additive table holds post-snapshot rows to prove a
+ // full replacement, independently of Beeper's account/conversation graph.
+ await query("INSERT INTO app_quality_measurements VALUES ('restore-probe', 'test', 'agent', NOW(), '{}')");
+ expect(await restore()).toMatchObject({ status: 'ok', dryRun: false });
expect(await listFolders()).toContainEqual(folder);
+ expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Snapshot person' }]);
+ expect((await query("SELECT id FROM tribe_people WHERE id = '00000000-0000-4000-8000-000000000863'")).rowCount).toBe(0);
+ expect((await query("SELECT * FROM app_quality_measurements WHERE app_id = 'restore-probe'")).rowCount).toBe(0);
+ expect((await query('SELECT * FROM beeper_participants')).rowCount).toBe(0);
+ expect((await query("SELECT 1 FROM pg_constraint WHERE conrelid = 'beeper_participants'::regclass AND confrelid = 'tribe_people'::regclass")).rowCount).toBe(1);
const issue = await query('SELECT data FROM pipeline_issues WHERE id = $1', [issueId]);
expect(issue.rows[0].data.stages.storyboards.scenes[0].id).toBeTruthy();
- const retained = await query('SELECT id, applied_at FROM schema_migrations WHERE id <> $1 ORDER BY id', [pendingMigration]);
- expect(retained.rows).toEqual(appliedBefore.rows);
+ expect((await query('SELECT id, applied_at FROM schema_migrations WHERE id <> $1 ORDER BY id', [pendingMigration])).rows).toEqual(appliedBefore.rows);
expect(await runDbMigrations()).toBe(0);
});
+
+ it('rolls back the reset and preserves rows and constraints when replay fails', async () => {
+ const invalidDir = join(dest, 'snapshots', 'fixture-source', 'invalid-sql');
+ await mkdir(invalidDir);
+ await writeFile(join(invalidDir, 'portos-db.sql'), `${await readFile(dumpPath, 'utf8')}\nTHIS IS INVALID SQL;\n`);
+ await query("UPDATE tribe_people SET name = 'Must survive failure' WHERE id = $1", [personId]);
+ const before = (await query("SELECT oid FROM pg_constraint WHERE conrelid = 'beeper_participants'::regclass ORDER BY oid")).rows;
+ expect(await restore(false, 'invalid-sql')).toMatchObject({ status: 'failed', reason: 'restore_error' });
+ expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Must survive failure' }]);
+ expect((await query("SELECT oid FROM pg_constraint WHERE conrelid = 'beeper_participants'::regclass ORDER BY oid")).rows).toEqual(before);
+ // The maintenance gate must have released on the replay error.
+ await query("UPDATE tribe_people SET name = 'After failed restore' WHERE id = $1", [personId]);
+ });
+
+ it('preflights unknown objects and external dependencies without mutations, including preview', async () => {
+ await query('CREATE TABLE public.unexpected_restore_record (id integer PRIMARY KEY)');
+ await query('INSERT INTO public.unexpected_restore_record VALUES (42)');
+ expect(await restore()).toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ expect((await query('SELECT * FROM public.unexpected_restore_record')).rows).toEqual([{ id: 42 }]);
+ await query('DROP TABLE public.unexpected_restore_record');
+ await query('CREATE SCHEMA restore_external');
+ await query('CREATE TABLE restore_external.link (person_id uuid REFERENCES public.tribe_people(id))');
+ await query('INSERT INTO restore_external.link VALUES ($1)', [personId]);
+ expect(await restore(true)).toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ expect(await restore()).toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ expect((await query('SELECT * FROM restore_external.link')).rows).toEqual([{ person_id: personId }]);
+ await query('DROP SCHEMA restore_external CASCADE');
+ const before = (await query('SELECT tableoid, xmin, name FROM tribe_people WHERE id = $1', [personId])).rows;
+ expect(await restore(true)).toMatchObject({ status: 'ok', dryRun: true });
+ expect((await query('SELECT tableoid, xmin, name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual(before);
+ });
});
diff --git a/server/services/backup.js b/server/services/backup.js
index 78f4db1738..47d22ef207 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -17,7 +17,7 @@ import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
-import { checkHealth, ensureSchema, getServerMajorVersion } from '../lib/db.js';
+import { checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
@@ -1459,7 +1459,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
* { status: 'ok', dryRun, sizeBytes, tableCount } (dry-run or applied)
* { status: 'skipped', reason: 'no_dump' } (no sql file in snapshot)
* { status: 'skipped', reason: 'not_configured' } (real restore, PG unreachable)
- * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_error'|'timeout'|'restore_schema_reconciliation', error? }
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation', error? }
* @param {string} destPath - Backup destination root
* @param {string} snapshotId
* @param {{dryRun?: boolean}} [options]
@@ -1507,86 +1507,90 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
const sql = await readFile(sqlPath, 'utf-8').catch(() => '');
const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;
- if (dryRun) {
- return { status: 'ok', dryRun: true, sizeBytes: info.size, tableCount };
- }
-
- // Never half-restore: require a reachable DB before replaying.
+ // Preview remains read-only. Recheck inside the replay transaction as well,
+ // so a changed catalog cannot turn a previously safe preview into a cascade.
const health = await checkHealth();
- if (!health.connected) {
- return { status: 'skipped', reason: 'not_configured' };
+ if (!health.connected) return { status: 'skipped', reason: 'not_configured' };
+ const { getDatabaseResetPlan } = await import('./backupDatabaseReset.js');
+ const { preflight, reset } = await getDatabaseResetPlan();
+ const preflightError = await query(preflight).then(() => null, error => error);
+ if (preflightError) {
+ return { status: 'failed', reason: 'restore_preflight', error: 'Database contains unexpected objects, ownership, or dependencies. Restore was refused without changing data.' };
}
+ if (dryRun) return { status: 'ok', dryRun: true, sizeBytes: info.size, tableCount };
+
+ return withDatabaseMaintenance(async () => {
+ const pgHost = process.env.PGHOST || 'localhost';
+ const pgPort = process.env.PGPORT || '5432';
+ const pgDb = process.env.PGDATABASE || 'portos';
+ const pgUser = process.env.PGUSER || 'portos';
+
+ const replay = await new Promise((resolveP) => {
+ // ON_ERROR_STOP=1 aborts on the first failed statement; --single-transaction
+ // wraps the whole replay in one transaction so that abort ROLLs BACK every
+ // prior statement. Together they make the restore atomic: it either fully
+ // applies or leaves the live DB untouched — never a mixed snapshot/current
+ // state. (The dump is written with --clean --if-exists, so the DROPs and
+ // recreates all commit or roll back as one unit.)
+ const proc = spawn('psql', [
+ '-X', '-v', 'ON_ERROR_STOP=1',
+ '--single-transaction',
+ '--echo-all',
+ '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', sqlPath
+ ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
+
+ let stderr = '';
+ const watchdog = watchBackupProcess(proc, { label: 'PostgreSQL restore' });
+ // `--echo-all` echoes input as psql consumes it, including rows within a
+ // long COPY. The output is never retained, but it must be drained: unread
+ // piped output can backpressure and deadlock a verbose restore. Each chunk
+ // is also the progress signal that keeps an active long restore alive.
+ proc.stdout.on('data', watchdog.markActivity);
+ proc.stderr.on('data', (chunk) => {
+ watchdog.markActivity();
+ stderr += chunk.toString();
+ });
- const pgHost = process.env.PGHOST || 'localhost';
- const pgPort = process.env.PGPORT || '5432';
- const pgDb = process.env.PGDATABASE || 'portos';
- const pgUser = process.env.PGUSER || 'portos';
-
- const replay = await new Promise((resolveP) => {
- // ON_ERROR_STOP=1 aborts on the first failed statement; --single-transaction
- // wraps the whole replay in one transaction so that abort ROLLs BACK every
- // prior statement. Together they make the restore atomic: it either fully
- // applies or leaves the live DB untouched — never a mixed snapshot/current
- // state. (The dump is written with --clean --if-exists, so the DROPs and
- // recreates all commit or roll back as one unit.)
- const proc = spawn('psql', [
- '-v', 'ON_ERROR_STOP=1',
- '--single-transaction',
- '--echo-all',
- '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-f', sqlPath
- ], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
-
- let stderr = '';
- const watchdog = watchBackupProcess(proc, { label: 'PostgreSQL restore' });
- // `--echo-all` echoes input as psql consumes it, including rows within a
- // long COPY. The output is never retained, but it must be drained: unread
- // piped output can backpressure and deadlock a verbose restore. Each chunk
- // is also the progress signal that keeps an active long restore alive.
- proc.stdout.on('data', watchdog.markActivity);
- proc.stderr.on('data', (chunk) => {
- watchdog.markActivity();
- stderr += chunk.toString();
- });
-
- proc.on('close', (code) => {
- if (!watchdog.finish()) return;
- const timeoutError = watchdog.getTimeoutError();
- if (timeoutError) {
- resolveP({ status: 'failed', reason: 'timeout', error: timeoutError.message });
- return;
- }
- if (code === 0) {
- console.log(`💾 psql restore complete from snapshot ${snapshotId}: ${tableCount} tables`);
- resolveP({ status: 'ok', dryRun: false, sizeBytes: info.size, tableCount });
- } else {
- console.warn(`⚠️ psql restore failed (code ${code}): ${stderr.trim()}`);
- resolveP({ status: 'failed', reason: 'restore_error', error: stderr.trim() });
- }
- });
- proc.on('error', (err) => {
- if (watchdog.getTimeoutError() || !watchdog.finish()) return;
- console.warn(`⚠️ psql not available: ${err.message}`);
- resolveP({ status: 'failed', reason: 'restore_error', error: err.message });
+ proc.on('close', (code) => {
+ if (!watchdog.finish()) return;
+ const timeoutError = watchdog.getTimeoutError();
+ if (timeoutError) {
+ resolveP({ status: 'failed', reason: 'timeout', error: timeoutError.message });
+ return;
+ }
+ if (code === 0) {
+ console.log(`💾 psql restore complete from snapshot ${snapshotId}: ${tableCount} tables`);
+ resolveP({ status: 'ok', dryRun: false, sizeBytes: info.size, tableCount });
+ } else {
+ console.warn(`⚠️ psql restore failed (code ${code}): ${stderr.trim()}`);
+ resolveP({ status: 'failed', reason: 'restore_error', error: stderr.trim() });
+ }
+ });
+ proc.on('error', (err) => {
+ if (watchdog.getTimeoutError() || !watchdog.finish()) return;
+ console.warn(`⚠️ psql not available: ${err.message}`);
+ resolveP({ status: 'failed', reason: 'restore_error', error: err.message });
+ });
});
+ if (replay.status !== 'ok') return replay;
+
+ // Replay has committed. Reapply this version's upgrades even when readiness
+ // was cached before the restore, then honor the restored migration ledger.
+ const reconciliationError = await (async () => {
+ await ensureSchema({ force: true });
+ const { runDbMigrations } = await import('../scripts/run-db-migrations.js');
+ await runDbMigrations();
+ })().then(() => null, (err) => err);
+ if (reconciliationError) {
+ console.error(`❌ DB restore schema reconciliation failed: ${reconciliationError.message}`);
+ return {
+ status: 'failed',
+ reason: 'restore_schema_reconciliation',
+ error: 'The database dump was applied, but schema recovery is incomplete. The restore was not rolled back. Restart PortOS to retry schema recovery; if it still fails, inspect the server logs and repair the database before continuing.',
+ };
+ }
+ return replay;
});
- if (replay.status !== 'ok') return replay;
-
- // Replay has committed. Reapply this version's upgrades even when readiness
- // was cached before the restore, then honor the restored migration ledger.
- const reconciliationError = await (async () => {
- await ensureSchema({ force: true });
- const { runDbMigrations } = await import('../scripts/run-db-migrations.js');
- await runDbMigrations();
- })().then(() => null, (err) => err);
- if (reconciliationError) {
- console.error(`❌ DB restore schema reconciliation failed: ${reconciliationError.message}`);
- return {
- status: 'failed',
- reason: 'restore_schema_reconciliation',
- error: 'The database dump was applied, but schema recovery is incomplete. The restore was not rolled back. Restart PortOS to retry schema recovery; if it still fails, inspect the server logs and repair the database before continuing.',
- };
- }
- return replay;
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 1a4abb0800..1018975ffd 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -49,6 +49,8 @@ afterAll(() => {
// Mock the DB health check and child_process.spawn before importing backup.js
vi.mock('../lib/db.js', () => ({
checkHealth: vi.fn(),
+ query: vi.fn().mockResolvedValue({ rows: [] }),
+ withDatabaseMaintenance: vi.fn(fn => fn()),
ensureSchema: vi.fn().mockResolvedValue(undefined),
// Default to null (version unknown) so dumpPostgres keeps the bare-`pg_dump`
// path and the existing status tests don't trigger live binary discovery.
@@ -58,7 +60,10 @@ vi.mock('../lib/db.js', () => ({
vi.mock('../scripts/run-db-migrations.js', () => ({
runDbMigrations: vi.fn().mockResolvedValue(0),
}));
-import { ensureSchema } from '../lib/db.js';
+import { ensureSchema, query, withDatabaseMaintenance } from '../lib/db.js';
+vi.mock('./backupDatabaseReset.js', () => ({
+ getDatabaseResetPlan: async () => ({ preflight: 'SELECT 1', reset: 'RESET_APPROVED_SCHEMA' }),
+}));
import { runDbMigrations } from '../scripts/run-db-migrations.js';
// Mock the memory-backend resolver so dumpPostgres can tell whether Postgres is
@@ -1020,6 +1025,7 @@ describe('restorePostgres', () => {
// clearAllMocks does not undo stubEnv — a PGPASSWORD stub from a failed
// (thrown) test would otherwise leak into every test after it.
vi.unstubAllEnvs();
+ checkHealth.mockResolvedValue({ connected: true });
({ restorePostgres } = await import('./backup.js'));
});
@@ -1062,6 +1068,16 @@ describe('restorePostgres', () => {
expect(runDbMigrations).not.toHaveBeenCalled();
});
+ it('refuses unexpected schema objects before entering maintenance or spawning replay', async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+ query.mockRejectedValueOnce(new Error('unexpected object'));
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun: false }))
+ .toMatchObject({ status: 'failed', reason: 'restore_preflight' });
+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
it('reads a previous-machine dump from the explicitly selected namespace', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
mockLegacyDumpRead();
@@ -1116,6 +1132,9 @@ describe('restorePostgres', () => {
expect(args).toEqual(expect.arrayContaining(['-v', 'ON_ERROR_STOP=1', '--single-transaction', '--echo-all', '-f']));
expect(opts.shell).toBe(false);
expect(opts.stdio).toEqual(['ignore', 'pipe', 'pipe']);
+ expect(args.indexOf('-c')).toBeLessThan(args.indexOf('-f'));
+ expect(args).toContain('RESET_APPROVED_SCHEMA');
+ expect(args).toContain('-X');
expect(child.stdin).toBeNull();
expect(child.stdout).not.toBeNull();
} finally {
diff --git a/server/services/backupDatabaseReset.js b/server/services/backupDatabaseReset.js
new file mode 100644
index 0000000000..e2be72a709
--- /dev/null
+++ b/server/services/backupDatabaseReset.js
@@ -0,0 +1,98 @@
+/** Full restore resets known application objects, never arbitrary CASCADE targets. */
+import { readFile } from 'node:fs/promises';
+
+let resetPlan;
+
+export async function getDatabaseResetPlan() {
+ if (resetPlan) return resetPlan;
+ const { buildUpgradeDdl, buildCatalogDdl } = await import('../lib/db/schema/index.js');
+ const base = await readFile(new URL('../scripts/init-db.sql', import.meta.url), 'utf8');
+ const ddl = [base, ...buildUpgradeDdl(), ...buildCatalogDdl()].join('\n');
+ // These are trusted, shipped DDL declarations, never names from a backup or
+ // the live database. Fail closed on objects not declared by this version.
+ const names = (pattern) => [...new Set([...ddl.matchAll(pattern)].map(match => match[1]))];
+ const tables = names(/CREATE TABLE IF NOT EXISTS ([a-z_][a-z_0-9]*)/g);
+ const functions = names(/CREATE OR REPLACE FUNCTION ([a-z_][a-z_0-9]*)\(\)/g);
+ const sequences = names(/CREATE SEQUENCE IF NOT EXISTS ([a-z_][a-z_0-9]*)/g);
+ const literals = values => values.map(value => `'${value}'`).join(', ');
+ const preflight = `DO $portos_restore$
+ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM pg_namespace n WHERE n.nspname = 'public'
+ AND NOT (n.nspowner = (SELECT oid FROM pg_roles WHERE rolname = current_user)
+ OR (pg_get_userbyid(n.nspowner) = 'pg_database_owner' AND
+ (SELECT datdba FROM pg_database WHERE datname = current_database()) =
+ (SELECT oid FROM pg_roles WHERE rolname = current_user)))
+ ) THEN RAISE EXCEPTION 'Restore preflight: application schema is not owned by the database user'; END IF;
+
+ IF EXISTS (
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind NOT IN ('i', 'I', 't')
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass
+ AND d.objid = c.oid AND d.deptype = 'e')
+ AND (c.relowner <> (SELECT oid FROM pg_roles WHERE rolname = current_user)
+ OR NOT ((c.relkind = 'r' AND c.relname IN (${literals(tables)}))
+ OR (c.relkind = 'S' AND (c.relname IN (${literals(sequences)}) OR EXISTS (
+ SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid
+ WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid
+ AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i')
+ AND t.relnamespace = n.oid AND t.relname IN (${literals(tables)})
+ )))))
+ ) THEN RAISE EXCEPTION 'Restore preflight: unexpected application-schema relation or owner'; END IF;
+
+ IF EXISTS (
+ SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
+ WHERE n.nspname = 'public'
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass
+ AND d.objid = p.oid AND d.deptype = 'e')
+ AND (p.proname NOT IN (${literals(functions)}) OR p.pronargs <> 0
+ OR p.proowner <> (SELECT oid FROM pg_roles WHERE rolname = current_user))
+ ) THEN RAISE EXCEPTION 'Restore preflight: unexpected application-schema function or owner'; END IF;
+
+ IF EXISTS (
+ SELECT 1 FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
+ WHERE n.nspname = 'public' AND t.typrelid = 0 AND t.typelem = 0
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_type'::regclass
+ AND d.objid = t.oid AND d.deptype = 'e')
+ ) OR EXISTS (
+ SELECT 1 FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace
+ WHERE n.nspname = 'public' AND e.extname NOT IN ('vector', 'pgcrypto')
+ ) OR EXISTS (
+ SELECT 1 FROM pg_depend d JOIN pg_namespace n ON n.oid = d.refobjid
+ WHERE d.refclassid = 'pg_namespace'::regclass AND n.nspname = 'public'
+ AND d.classid NOT IN ('pg_class'::regclass, 'pg_proc'::regclass, 'pg_type'::regclass, 'pg_extension'::regclass)
+ AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = d.classid
+ AND e.objid = d.objid AND e.deptype = 'e')
+ ) THEN RAISE EXCEPTION 'Restore preflight: unexpected application-schema object'; END IF;
+
+ IF EXISTS (
+ SELECT 1 FROM pg_constraint c JOIN pg_class parent ON parent.oid = c.confrelid
+ JOIN pg_namespace pn ON pn.oid = parent.relnamespace
+ JOIN pg_class child ON child.oid = c.conrelid
+ JOIN pg_namespace cn ON cn.oid = child.relnamespace
+ WHERE c.contype = 'f' AND pn.nspname = 'public' AND cn.nspname <> 'public'
+ ) OR EXISTS (
+ SELECT 1 FROM pg_depend d JOIN pg_rewrite r ON r.oid = d.objid
+ JOIN pg_class v ON v.oid = r.ev_class JOIN pg_namespace vn ON vn.oid = v.relnamespace
+ JOIN pg_class t ON t.oid = d.refobjid JOIN pg_namespace tn ON tn.oid = t.relnamespace
+ WHERE d.classid = 'pg_rewrite'::regclass AND d.refclassid = 'pg_class'::regclass
+ AND tn.nspname = 'public' AND vn.nspname <> 'public'
+ ) THEN RAISE EXCEPTION 'Restore preflight: non-PortOS dependency on application schema'; END IF;
+ END $portos_restore$;`;
+
+ // A single DROP list permits dependencies BETWEEN approved tables. RESTRICT
+ // remains the database-enforced backstop for every unanticipated dependency,
+ // including changes between preflight and replay. Never use CASCADE here.
+ const reset = `${preflight}
+ DROP TABLE IF EXISTS ${tables.map(name => `public.${name}`).join(', ')} RESTRICT;
+ DROP FUNCTION IF EXISTS ${functions.map(name => `public.${name}()`).join(', ')} RESTRICT;
+ DROP SEQUENCE IF EXISTS ${sequences.map(name => `public.${name}`).join(', ')} RESTRICT;
+ CREATE SCHEMA IF NOT EXISTS public;
+ CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA public;
+ CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;`;
+ // Keep the namespace (including its owner/ACLs) and installed extensions.
+ // pg_dump's own clean statements can recreate extensions before their types
+ // are consumed. All application tables, functions and sequence state reset.
+ resetPlan = { preflight, reset };
+ return resetPlan;
+}