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: make older database restores ready for the current app (#7227)

[._.]/ Adam Eivy0435db62c75a
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 680ed7c368..072c4a1c79 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -236,6 +236,8 @@ export function BackupTab() {
.catch(() => ({ status: 'failed', reason: 'request_error' }));
if (result.status === 'ok') {
toast.success(`Database restored from ${target.request.snapshotId}`, { icon: '💾' });
+ } else if (result.reason === 'restore_schema_reconciliation') {
+ toast.error('The database dump was applied, but schema recovery is incomplete. It was not rolled back. Restart PortOS to retry recovery; if it still fails, check the server logs and repair the database before continuing.', { duration: Infinity });
} else {
toast.error(`DB restore failed: ${result.reason || 'unknown'}`);
}
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index 6bf2af0115..51ddb0fc70 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -209,6 +209,25 @@ describe('BackupTab', () => {
}, { silent: true });
});
+ it('explains that schema recovery failed after the dump committed', async () => {
+ withSnapshot();
+ restoreDatabase
+ .mockResolvedValueOnce({ status: 'ok', sizeBytes: 2048, tableCount: 12 })
+ .mockResolvedValueOnce({ status: 'failed', reason: 'restore_schema_reconciliation' });
+ await renderTab();
+ await act(async () => {
+ fireEvent.click(await screen.findByRole('button', { name: /Restore DB/i }));
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Restore$/i }));
+ });
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith(
+ expect.stringMatching(/dump was applied.*not rolled back.*Restart PortOS/),
+ { duration: Infinity },
+ );
+ });
+
it('toasts an error when the confirmed restore fails', async () => {
withSnapshot();
restoreDatabase
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 022f084c89..74a9b0eedf 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -76,7 +76,7 @@ After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. `dryRun:
### Database — `restorePostgres()`
-Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the restore is **atomic**: it either fully applies or rolls back, never leaving a mixed snapshot/current state.
+Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ERROR_STOP=1 --single-transaction`, so the **SQL replay is atomic**: a failed replay rolls back. After replay commits, PortOS forces the current additive schema upgrades and then runs ordered DB migrations using the restored `schema_migrations` ledger. Already-applied migrations are skipped. Success is returned only after both phases finish; dry-run performs neither replay nor schema changes.
| Result | Meaning |
|---|---|
@@ -86,6 +86,9 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ status: 'failed', reason: 'manifest_unreadable' }` | An existing `manifest.json` is corrupt or unreadable — choose another snapshot or repair the backup media before retrying |
| `{ status: 'failed', reason: 'manifest_mismatch' }` | Snapshot's `portos-db.sql` hash disagrees with `manifest.json` — dump considered untrustworthy |
| `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) |
+| `{ status: 'failed', reason: 'restore_schema_reconciliation', error }` | The dump committed, but current schema recovery failed; the restore was **not rolled back** |
+
+On schema-reconciliation failure, restart PortOS to retry its schema upgrades and pending migrations. If recovery still fails, inspect the server logs and repair the database before continuing to use affected features. Reconciliation can partially apply upgrades; it is separate from the completed replay transaction.
A non-dry-run restore requires a reachable DB first (`checkHealth()`), so a restore never half-applies against a down database.
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 9ecffb297a..9c123b389e 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -384,6 +384,7 @@ describe('backup routes', () => {
it.each([
['manifest_unreadable', { status: 'failed', reason: 'manifest_unreadable' }],
['manifest_mismatch', { status: 'failed', reason: 'manifest_mismatch' }],
+ ['restore_schema_reconciliation', { status: 'failed', reason: 'restore_schema_reconciliation', error: 'The database dump was applied, but schema recovery is incomplete. Restart PortOS.' }],
['restore_error', { status: 'failed', reason: 'restore_error', error: 'psql: exited 1' }],
['no_dump', { status: 'skipped', reason: 'no_dump' }],
['not_configured', { status: 'skipped', reason: 'not_configured' }]
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
new file mode 100644
index 0000000000..0bb47629bc
--- /dev/null
+++ b/server/services/backup.db.test.js
@@ -0,0 +1,74 @@
+/**
+ * Real psql/pg_dump regression for restoring a pre-federation folder schema.
+ * Runs only via test:db against a guarded test database, never live records.
+ */
+import { afterAll, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { checkHealth, ensureSchema, query, close, POOL_CONFIG } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { runDbMigrations } from '../scripts/run-db-migrations.js';
+import { restorePostgres } from './backup.js';
+import { listFolders } from './writersRoom/db.js';
+
+const health = await checkHealth();
+const ready = requireDbOrSkip('services/backup.db.test',
+ health.connected && spawnSync('psql', ['--version']).status === 0 &&
+ spawnSync('pg_dump', ['--version']).status === 0,
+ 'test database or PostgreSQL client tools unavailable');
+let dest;
+const folderId = 'restore-schema-folder-probe';
+const issueId = 'restore-schema-issue-probe';
+const pendingMigration = '007-storyboard-scene-durable-ids.js';
+
+afterAll(async () => {
+ if (ready) {
+ 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 runDbMigrations();
+ }
+ await close();
+ if (dest) await rm(dest, { recursive: true, force: true });
+});
+
+describe.skipIf(!ready)('restore older database schema', () => {
+ it('repairs cached schema readiness and migrates the restored ledger while preserving rows', 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]);
+ await query('DELETE FROM schema_migrations WHERE id = $1', [pendingMigration]);
+ const folder = { id: folderId, name: 'Recovered folder' };
+ await query('INSERT INTO writers_room_folders (id, name, data) VALUES ($1, $2, $3)', [folderId, folder.name, folder]);
+ 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('ALTER TABLE writers_room_folders DROP COLUMN deleted, DROP COLUMN deleted_at');
+
+ dest = await mkdtemp(join(tmpdir(), 'portos-restore-schema-'));
+ const snapshotDir = join(dest, 'snapshots', 'fixture-source', 'old-schema');
+ await mkdir(snapshotDir, { recursive: true });
+ execFileSync('pg_dump', [
+ '--no-owner', '--no-acl', '--clean', '--if-exists',
+ '-h', POOL_CONFIG.host, '-p', String(POOL_CONFIG.port),
+ '-U', POOL_CONFIG.user, '-d', POOL_CONFIG.database,
+ '--table=writers_room_folders', '--table=schema_migrations', '--table=pipeline_issues',
+ '-f', join(snapshotDir, 'portos-db.sql'),
+ ], { env: { ...process.env, PGPASSWORD: POOL_CONFIG.password } });
+
+ // The running version has cached successful readiness before restore.
+ await ensureSchema({ force: true });
+ await runDbMigrations();
+ await query('UPDATE writers_room_folders SET data = $2 WHERE id = $1', [folderId, { id: folderId, name: 'After backup' }]);
+ const result = await restorePostgres(dest, 'old-schema', { source: 'fixture-source', dryRun: false });
+ expect(result).toMatchObject({ status: 'ok', dryRun: false });
+ expect(await listFolders()).toContainEqual(folder);
+ 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 runDbMigrations()).toBe(0);
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index d199d79902..d5b2f3d328 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -16,7 +16,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, getServerMajorVersion } from '../lib/db.js';
+import { checkHealth, ensureSchema, getServerMajorVersion } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
@@ -1180,7 +1180,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', error? }
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_error'|'timeout'|'restore_schema_reconciliation', error? }
* @param {string} destPath - Backup destination root
* @param {string} snapshotId
* @param {{dryRun?: boolean}} [options]
@@ -1243,7 +1243,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
const pgDb = process.env.PGDATABASE || 'portos';
const pgUser = process.env.PGUSER || 'portos';
- return new Promise((resolveP) => {
+ 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
@@ -1290,6 +1290,24 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
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;
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index a9bf1b96de..8e4baa0814 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -47,11 +47,18 @@ afterAll(() => {
// Mock the DB health check and child_process.spawn before importing backup.js
vi.mock('../lib/db.js', () => ({
checkHealth: vi.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.
getServerMajorVersion: vi.fn(() => null),
}));
+vi.mock('../scripts/run-db-migrations.js', () => ({
+ runDbMigrations: vi.fn().mockResolvedValue(0),
+}));
+import { ensureSchema } from '../lib/db.js';
+import { runDbMigrations } from '../scripts/run-db-migrations.js';
+
// 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', () => ({
@@ -896,6 +903,8 @@ describe('restorePostgres', () => {
expect(result.sizeBytes).toBe(4096);
expect(result.tableCount).toBe(1);
expect(spawn).not.toHaveBeenCalled();
+ expect(ensureSchema).not.toHaveBeenCalled();
+ expect(runDbMigrations).not.toHaveBeenCalled();
});
it('reads a previous-machine dump from the explicitly selected namespace', async () => {
@@ -973,6 +982,54 @@ describe('restorePostgres', () => {
expect(result.status).toBe('failed');
expect(result.reason).toBe('restore_error');
expect(result.error).toContain('already exists');
+ expect(ensureSchema).not.toHaveBeenCalled();
+ expect(runDbMigrations).not.toHaveBeenCalled();
+ });
+
+ it('waits for forced schema repair and then migrations before reporting success', async () => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+ checkHealth.mockResolvedValue({ connected: true });
+ let finishSchema;
+ let finishMigrations;
+ ensureSchema.mockImplementationOnce(() => new Promise(resolve => { finishSchema = resolve; }));
+ runDbMigrations.mockImplementationOnce(() => new Promise(resolve => { finishMigrations = resolve; }));
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ let settled = false;
+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false }).then(result => {
+ settled = true;
+ return result;
+ });
+ await flush();
+ proc.emit('close', 0);
+ await flush();
+ expect(ensureSchema).toHaveBeenCalledWith({ force: true });
+ expect(runDbMigrations).not.toHaveBeenCalled();
+ expect(settled).toBe(false);
+ finishSchema();
+ await vi.waitFor(() => expect(runDbMigrations).toHaveBeenCalledOnce());
+ expect(settled).toBe(false);
+ finishMigrations(0);
+ await expect(pending).resolves.toMatchObject({ status: 'ok', dryRun: false });
+ });
+
+ it.each(['schema', 'migrations'])('reports committed replay when %s reconciliation fails', async (phase) => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+ checkHealth.mockResolvedValue({ connected: true });
+ (phase === 'schema' ? ensureSchema : runDbMigrations).mockRejectedValueOnce(new Error('upgrade failed'));
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });
+ await flush();
+ proc.emit('close', 0);
+ const result = await pending;
+ expect(result).toMatchObject({ status: 'failed', reason: 'restore_schema_reconciliation' });
+ expect(result.error).toContain('dump was applied');
+ expect(result.error).toContain('not rolled back');
+ expect(result.error).toContain('Restart PortOS');
+ if (phase === 'schema') expect(runDbMigrations).not.toHaveBeenCalled();
});
// Manifest SHA-256 verification (#980). The dump is hashed in generateManifest
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index f0ad00130b..eb8185a46e 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -18,6 +18,7 @@ export const DB_TEST_INCLUDE = [
'services/appQuality.db.test.js',
'**/db.test.js',
'services/dbAdmin.db.test.js',
+ 'services/backup.db.test.js',
'services/catalogDB.test.js',
'services/catalogDB.facets.db.test.js',
'services/humanActivity.db.test.js',