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: refuse incomplete legacy database dumps before resetting live tables (#8782)

[._.]/ Adam Eivy892b6fc9f857
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 2fcbc617ad..4828266fc4 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -37,6 +37,13 @@ const asArray = (v) => Array.isArray(v) ? v : [];
// Backup form. Drop those on load instead: the spelling of the survivors is left
// untouched (anchoring is a read-time concern), so the form is not dirty.
const asExcludeArray = (v) => asArray(v).filter(isSafeExcludePattern);
+// restorePostgres refusals that left the database untouched (preview or execution).
+const DB_RESTORE_REFUSALS = {
+ manifest_mismatch: 'Snapshot dump failed integrity verification',
+ manifest_unreadable: 'Snapshot verification metadata could not be read. Choose another snapshot or repair the backup media before retrying.',
+ dump_unreadable: 'The snapshot database dump could not be read or staged for restore. Nothing was changed; check the backup media and free temp space, then retry.',
+ dump_incomplete: 'The snapshot database dump is incomplete (truncated or damaged). Nothing was changed; choose another snapshot.',
+};
const snapshotIdentity = (snapshot) =>
snapshot.selectionKey || `${snapshot.source || 'current'}/${snapshot.id}`;
const snapshotSourceLabel = (snapshot) =>
@@ -323,12 +330,7 @@ export function BackupTab() {
return;
}
if (preview.status !== 'ok') {
- const message = preview.reason === 'manifest_mismatch'
- ? 'Snapshot dump failed integrity verification'
- : preview.reason === 'manifest_unreadable'
- ? 'Snapshot verification metadata could not be read. Choose another snapshot or repair the backup media before retrying.'
- : `DB restore unavailable: ${preview.reason || 'unknown'}`;
- toast.error(message);
+ toast.error(DB_RESTORE_REFUSALS[preview.reason] || `DB restore unavailable: ${preview.reason || 'unknown'}`);
return;
}
setRestorePreview(preview);
@@ -342,6 +344,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 (DB_RESTORE_REFUSALS[result.reason]) {
+ toast.error(DB_RESTORE_REFUSALS[result.reason]);
} 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 if (result.reason === 'restore_sync_resync') {
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index 01bc4ebd81..4b8f1d13a0 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -415,6 +415,22 @@ describe('BackupTab', () => {
);
expect(screen.queryByText(/Restore database\?/i)).toBeNull();
});
+
+ // #8782: an incomplete legacy dump is refused at preview, so the operator
+ // learns nothing changed instead of seeing an opaque reason code.
+ it('explains an incomplete dump and does not open confirmation', async () => {
+ withSnapshot();
+ restoreDatabase.mockResolvedValue({ status: 'failed', reason: 'dump_incomplete' });
+ await renderTab();
+
+ await act(async () => {
+ fireEvent.click(await screen.findByRole('button', { name: /Restore DB/i }));
+ });
+
+ expect(restoreDatabase).toHaveBeenCalledTimes(1);
+ expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/incomplete.*Nothing was changed/));
+ expect(screen.queryByText(/Restore database\?/i)).toBeNull();
+ });
});
describe('snapshot deletion (#8334)', () => {
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 9a909254bd..7d3f17f8cc 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -96,7 +96,9 @@ After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. Restore
### Database — `restorePostgres()`
-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 and peer sync is repaired (below); dry-run performs neither replay nor schema changes.
+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.
+
+**Dump admission (#8782).** Because the replay starts by resetting every application table, a dump that parses but stops early would commit an empty database — `ON_ERROR_STOP` cannot see a file that simply ends between complete statements, and historical snapshots carry no checksum to catch it. Before preview or execution touch the database, PortOS streams the dump once and requires the plain `pg_dump` envelope: the terminal `-- PostgreSQL database dump complete` block as the last content (only the `\unrestrict` line newer `pg_dump` writes may follow it) and the `CREATE TABLE` definitions for `memories` and `memory_links`, which every PortOS dump has contained. Tables introduced later are not required, and a complete dump of empty tables is valid. A header-only or truncated dump is refused as `dump_incomplete`, and a read failure as `dump_unreadable` — never as an empty successful restore. The same streamed read supplies the manifest checksum. For execution it also writes the bytes it checked to an owner-only copy in a fresh `portos-restore-*` directory under the OS temp dir, and `psql` replays that copy rather than the snapshot path, so a dump that changes on the backup media after admission cannot be what gets restored. The copy is removed when the restore finishes, whatever the outcome; staging it needs free temp space about the size of the dump. 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 and peer sync is repaired (below); dry-run performs neither replay nor schema changes.
| Result | Meaning |
|---|---|
@@ -105,6 +107,8 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ status: 'skipped', reason: 'not_configured' }` | Real restore requested but Postgres is unreachable — refuses to half-restore |
| `{ 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: 'dump_unreadable', error }` | `portos-db.sql` could not be read, or its private restore copy could not be written — refused before any reset |
+| `{ status: 'failed', reason: 'dump_incomplete', error }` | The dump lacks the `pg_dump` completion marker or a core PortOS table (header-only or truncated) — refused before any reset |
| `{ 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** |
| `{ status: 'failed', reason: 'restore_sync_resync', error }` | The dump committed and the schema recovered, but peer sync could not be repaired (below) |
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index 7b260db68f..fd389432e7 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -2,7 +2,7 @@
import { afterAll, describe, expect, it, vi } from 'vitest';
import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { checkHealth, ensureSchema, query, close, getServerMajorVersion, POOL_CONFIG } from '../lib/db.js';
import { requireDbOrSkip } from '../lib/dbTestGate.js';
@@ -32,6 +32,7 @@ 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 };
+const DUMP_COMPLETE = '\n--\n-- PostgreSQL database dump complete';
afterAll(async () => {
if (ready) {
@@ -111,7 +112,10 @@ describe.skipIf(!ready)('restore older database schema', () => {
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`);
+ // Inside the complete envelope, so admission passes and psql itself fails.
+ const dumpSql = await readFile(dumpPath, 'utf8');
+ const trailerAt = dumpSql.lastIndexOf(DUMP_COMPLETE);
+ await writeFile(join(invalidDir, 'portos-db.sql'), `${dumpSql.slice(0, trailerAt)}\nTHIS IS INVALID SQL;\n${dumpSql.slice(trailerAt)}`);
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;
const rewindsBefore = rewindPostgresSyncCursors.mock.calls.length;
@@ -123,6 +127,25 @@ describe.skipIf(!ready)('restore older database schema', () => {
await query("UPDATE tribe_people SET name = 'After failed restore' WHERE id = $1", [personId]);
});
+ // #8782: a legacy dump without a checksum that parses cleanly but stops early
+ // must be refused before the full reset, or it commits an empty database.
+ it.each([
+ ['header-only', sql => sql.slice(0, sql.indexOf('SET '))],
+ ['truncated between complete statements', sql => sql.slice(0, sql.indexOf('\nCOPY ') + 1)],
+ ])('refuses a %s legacy dump in preview and execution and keeps existing rows', async (name, truncate) => {
+ const dir = join(dest, 'snapshots', 'fixture-source', `truncated-${name.split(' ')[0]}`);
+ await mkdir(dir);
+ await writeFile(join(dir, 'portos-db.sql'), truncate(await readFile(dumpPath, 'utf8')));
+ await query("UPDATE tribe_people SET name = 'Must survive refusal' WHERE id = $1", [personId]);
+ const rewindsBefore = rewindPostgresSyncCursors.mock.calls.length;
+ for (const dryRun of [true, false]) {
+ expect(await restore(dryRun, basename(dir))).toMatchObject({ status: 'failed', reason: 'dump_incomplete' });
+ }
+ expect(rewindPostgresSyncCursors).toHaveBeenCalledTimes(rewindsBefore);
+ expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Must survive refusal' }]);
+ expect((await query('SELECT 1 FROM writers_room_folders WHERE id = $1', [folderId])).rowCount).toBe(1);
+ });
+
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)');
diff --git a/server/services/backup.js b/server/services/backup.js
index 4b9645fc26..d519e3874d 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -9,9 +9,9 @@
import { dashboardEvents } from './dashboardEvents.js';
import { spawn } from '../lib/childProcess.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
-import { access, lstat, readdir, readFile, rm, stat, unlink, writeFile } from 'fs/promises';
+import { access, lstat, mkdtemp, readdir, readFile, rm, stat, unlink, writeFile } from 'fs/promises';
import { PassThrough } from 'node:stream';
-import { hostname } from 'os';
+import { hostname, tmpdir } from 'os';
import { basename, join, resolve, relative, isAbsolute } from 'path';
import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
@@ -19,6 +19,7 @@ import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
import { checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
+import { inspectDatabaseDump } from './backupDatabaseDump.js';
import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
@@ -1486,7 +1487,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_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation'|'restore_sync_resync', error? }
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'dump_unreadable'|'dump_incomplete'|'restore_preflight'|'restore_error'|'timeout'|'restore_schema_reconciliation'|'restore_sync_resync', error? }
* A successful real restore also carries `syncCursorsRewound` (peer count);
* see resyncFederationAfterRestore.
* @param {string} destPath - Backup destination root
@@ -1523,18 +1524,47 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
console.error(`❌ restore: integrity manifest unreadable for snapshot ${snapshotId}`);
return { status: 'failed', reason: 'manifest_unreadable' };
}
- const manifest = manifestRead.value;
- const expectedHash = manifest?.files?.['../portos-db.sql'];
- if (expectedHash) {
- const actualHash = await sha256File(sqlPath);
- if (actualHash !== expectedHash) {
- console.error(`❌ restore: manifest hash mismatch for snapshot ${snapshotId} (expected ${expectedHash}, got ${actualHash})`);
- return { status: 'failed', reason: 'manifest_mismatch' };
+ const expectedHash = manifestRead.value?.files?.['../portos-db.sql'];
+ // Execution replays a private copy written by the same read that admits the
+ // dump, so the bytes checked are exactly the bytes psql replays even if the
+ // snapshot changes afterwards (#8782). Preview only inspects.
+ const spoolDir = dryRun ? null : await mkdtemp(join(tmpdir(), 'portos-restore-'));
+ try {
+ return await restoreAdmittedDump({ sqlPath, spoolPath: spoolDir && join(spoolDir, 'dump.sql'), expectedHash, snapshotId, dryRun, sizeBytes: info.size });
+ } finally {
+ if (spoolDir) {
+ await rm(spoolDir, { recursive: true, force: true })
+ .catch(err => console.error(`❌ restore: failed to remove dump spool ${spoolDir}: ${err.message}`));
}
}
+}
- const sql = await readFile(sqlPath, 'utf-8').catch(() => '');
- const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;
+async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotId, dryRun, sizeBytes }) {
+ // One streamed read supplies the checksum and the completeness proof. A read
+ // failure is refused here — never mistaken for an empty dump.
+ const dump = await inspectDatabaseDump(sqlPath, { spoolTo: spoolPath }).catch((err) => {
+ console.error(`❌ restore: dump unreadable for snapshot ${snapshotId}: ${err.message}`);
+ return null;
+ });
+ if (!dump) {
+ return { status: 'failed', reason: 'dump_unreadable', error: 'The snapshot database dump could not be read or staged for restore. Restore was refused without changing data.' };
+ }
+ if (expectedHash && dump.sha256 !== expectedHash) {
+ console.error(`❌ restore: manifest hash mismatch for snapshot ${snapshotId} (expected ${expectedHash}, got ${dump.sha256})`);
+ return { status: 'failed', reason: 'manifest_mismatch' };
+ }
+ // The restore resets every application table first, so a dump that parses
+ // but stops early (header-only, or truncated between statements) would
+ // commit an empty database. ON_ERROR_STOP cannot see that; the envelope can.
+ if (!dump.complete || dump.missingTables.length) {
+ const missing = [
+ ...(dump.complete ? [] : ['the pg_dump completion marker']),
+ ...dump.missingTables.map(name => `table ${name}`),
+ ].join(', ');
+ console.error(`❌ restore: incomplete dump for snapshot ${snapshotId} (missing ${missing})`);
+ return { status: 'failed', reason: 'dump_incomplete', error: `The snapshot database dump is incomplete (missing ${missing}). Restore was refused without changing data.` };
+ }
+ const { tableCount } = dump;
// Preview remains read-only. Recheck inside the replay transaction as well,
// so a changed catalog cannot turn a previously safe preview into a cascade.
@@ -1546,7 +1576,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
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 };
+ if (dryRun) return { status: 'ok', dryRun: true, sizeBytes, tableCount };
return withDatabaseMaintenance(async () => {
// Read before the replay rewinds them to the dump's values.
@@ -1562,12 +1592,13 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
// 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.)
+ // recreates all commit or roll back as one unit.) psql reads the admitted
+ // spool copy, never the snapshot path.
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
+ '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', spoolPath
], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
let stderr = '';
@@ -1591,7 +1622,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
}
if (code === 0) {
console.log(`💾 psql restore complete from snapshot ${snapshotId}: ${tableCount} tables`);
- resolveP({ status: 'ok', dryRun: false, sizeBytes: info.size, tableCount });
+ resolveP({ status: 'ok', dryRun: false, sizeBytes, tableCount });
} else {
console.warn(`⚠️ psql restore failed (code ${code}): ${stderr.trim()}`);
resolveP({ status: 'failed', reason: 'restore_error', error: stderr.trim() });
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 360e50ce6b..0b5d4d80f0 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -24,7 +24,7 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
-import { mkdtempSync, rmSync } from 'fs';
+import { createReadStream, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { basename, join as joinPath } from 'path';
import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -80,7 +80,7 @@ vi.mock('./memoryBackend.js', () => ({
import { EventEmitter } from 'events';
import { createHash } from 'crypto';
import { hostname } from 'os';
-import { PassThrough } from 'node:stream';
+import { PassThrough, Readable } from 'node:stream';
import { spawn as spawnChild, spawnSync } from 'node:child_process';
import { spawn } from '../lib/childProcess.js';
// Partial mock: only override spawn. Preserve execFile et al. because
@@ -93,6 +93,12 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => ({
// Mock fs/promises so stat/readFile are spyable in ESM (the real namespace
// is non-configurable). Spread the original first so every other fs helper
// used by backup.js + fileUtils.js keeps its real implementation.
+// createReadStream is spyable for the streamed database-dump admission
+// (#8782); every other caller keeps the real implementation.
+vi.mock('fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, createReadStream: vi.fn(actual.createReadStream) };
+});
vi.mock('fs/promises', async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -1050,16 +1056,40 @@ describe('dumpPostgres status classification', () => {
});
});
+// A complete plain pg_dump envelope as pg_dump 17.6+ writes it. Only the two
+// tables every PortOS dump has ever contained — newer tables are optional.
+const DUMP_HEADER = '--\n-- PostgreSQL database dump\n--\n\n\\restrict k3y\n\nSET statement_timeout = 0;\n';
+const DUMP_TABLES = 'CREATE TABLE public.memories (\n id uuid NOT NULL\n);\n\nCREATE TABLE public.memory_links (\n source_id uuid NOT NULL\n);\n\nCOPY public.memories (id) FROM stdin;\n\\.\n\n';
+const DUMP_TRAILER = '\n--\n-- PostgreSQL database dump complete\n--\n\n\\unrestrict k3y\n\n';
+const COMPLETE_DUMP = DUMP_HEADER + DUMP_TABLES + DUMP_TRAILER;
+
+// Serve the dump bytes from the mocked stream. Each entry answers one read of
+// the snapshot dump in order; the last repeats. An Error entry fails that read.
+const realFsSync = await vi.importActual('fs');
+function mockDumpStream(...reads) {
+ const queue = reads.length ? reads : [COMPLETE_DUMP];
+ createReadStream.mockImplementation((path, ...rest) => {
+ if (!String(path).endsWith('portos-db.sql')) return realFsSync.createReadStream(path, ...rest);
+ const next = queue.length > 1 ? queue.shift() : queue[0];
+ if (next instanceof Error) {
+ return new Readable({ read() { this.destroy(next); } });
+ }
+ return Readable.from([Buffer.from(next)]);
+ });
+}
+
describe('restorePostgres', () => {
let restorePostgres;
- const mockLegacyDumpRead = (sql = 'CREATE TABLE a (...);\n') => {
+ const mockLegacyDumpRead = (...reads) => {
vi.spyOn(fs, 'readFile').mockImplementation(async (path) => {
if (String(path).endsWith('manifest.json')) {
throw Object.assign(new Error('missing'), { code: 'ENOENT' });
}
- return sql;
+ throw new Error(`unexpected readFile ${path}`);
});
+ mockDumpStream(...reads);
};
+ afterAll(() => createReadStream.mockImplementation(realFsSync.createReadStream));
beforeEach(async () => {
vi.clearAllMocks();
// listSnapshots installs a persistent readdir spy that returns Dirents.
@@ -1109,7 +1139,7 @@ describe('restorePostgres', () => {
expect(result.status).toBe('ok');
expect(result.dryRun).toBe(true);
expect(result.sizeBytes).toBe(4096);
- expect(result.tableCount).toBe(1);
+ expect(result.tableCount).toBe(2);
expect(spawn).not.toHaveBeenCalled();
expect(ensureSchema).not.toHaveBeenCalled();
expect(runDbMigrations).not.toHaveBeenCalled();
@@ -1173,7 +1203,7 @@ describe('restorePostgres', () => {
});
try {
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });
- expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 1, syncCursorsRewound: 2 });
+ expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 2, syncCursorsRewound: 2 });
const [bin, args, opts] = spawn.mock.calls[0];
expect(bin).toBe('psql');
expect(args).toEqual(expect.arrayContaining(['-v', 'ON_ERROR_STOP=1', '--single-transaction', '--echo-all', '-f']));
@@ -1278,7 +1308,7 @@ describe('restorePostgres', () => {
it('floors feed sequences at their pre-replay value and rewinds peer cursors after reconciliation', async () => {
const result = await runRestore();
- expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 1, syncCursorsRewound: 2 });
+ expect(result).toEqual({ status: 'ok', dryRun: false, sizeBytes: 4096, tableCount: 2, syncCursorsRewound: 2 });
// Captured inside maintenance, before psql replays the dump.
expect(captureCalls()).toHaveLength(1);
expect(captureCalls()[0][1][0]).toContain('catalog_ingredients_sync_feed_seq');
@@ -1309,15 +1339,82 @@ describe('restorePostgres', () => {
});
});
+ // Dump completeness admission (#8782). Historical snapshots carry no hash, so
+ // a truncated-but-parseable dump must be caught from its own envelope before
+ // the full reset — ON_ERROR_STOP cannot see a file that simply stops early.
+ describe('dump admission', () => {
+ beforeEach(() => {
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ });
+ const expectRefusedBeforeReset = () => {
+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();
+ expect(query).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(rewindPostgresSyncCursors).not.toHaveBeenCalled();
+ };
+
+ it.each([
+ ['a header-only legacy dump', DUMP_HEADER, /completion marker.*memories.*memory_links/],
+ ['a dump truncated between complete statements', DUMP_HEADER + DUMP_TABLES, /completion marker/],
+ ['a complete envelope without the core PortOS tables', DUMP_HEADER + DUMP_TRAILER, /table memories, table memory_links/],
+ ['content after the completion marker', `${COMPLETE_DUMP}DROP TABLE public.memories;\n`, /completion marker/],
+ ])('refuses %s in preview and execution before any reset', async (_case, sql, missing) => {
+ mockLegacyDumpRead(sql);
+ for (const dryRun of [true, false]) {
+ const result = await restorePostgres('/dest', 'snap-1', { dryRun });
+ expect(result).toMatchObject({ status: 'failed', reason: 'dump_incomplete' });
+ expect(result.error).toMatch(missing);
+ }
+ expectRefusedBeforeReset();
+ });
+
+ it('refuses an unreadable dump instead of treating it as empty', async () => {
+ mockLegacyDumpRead(Object.assign(new Error('media I/O failure'), { code: 'EIO' }));
+ for (const dryRun of [true, false]) {
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun }))
+ .toMatchObject({ status: 'failed', reason: 'dump_unreadable' });
+ }
+ expectRefusedBeforeReset();
+ });
+
+ it('admits a complete legacy dump of empty tables written by an older pg_dump', async () => {
+ // No \\restrict/\\unrestrict, CRLF-free, empty COPY blocks, no newer tables.
+ mockLegacyDumpRead(`--\n-- PostgreSQL database dump\n--\n\n${DUMP_TABLES}--\n-- PostgreSQL database dump complete\n--\n\n`);
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun: true }))
+ .toEqual({ status: 'ok', dryRun: true, sizeBytes: 4096, tableCount: 2 });
+ });
+
+ // A later swap on the backup media must not reach psql: it replays the
+ // private copy the admission read wrote, and the copy is removed afterwards.
+ it('replays exactly the admitted bytes from a private spool, never the snapshot path', async () => {
+ mockLegacyDumpRead(COMPLETE_DUMP, `${DUMP_HEADER}COMMIT;\n${DUMP_TRAILER}`);
+ const proc = fakeProc();
+ let replayed;
+ spawn.mockImplementation((_bin, args) => {
+ const spoolPath = args[args.indexOf('-f') + 1];
+ replayed = { spoolPath, sql: readFileSync(spoolPath, 'utf8'), mode: statSync(spoolPath).mode & 0o777 };
+ return proc;
+ });
+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });
+ await flush();
+ proc.emit('close', 0);
+ expect(await pending).toMatchObject({ status: 'ok', dryRun: false, tableCount: 2 });
+ expect(replayed.sql).toBe(COMPLETE_DUMP);
+ expect(replayed.spoolPath).not.toContain('snap-1');
+ expect(createReadStream.mock.calls.filter(([path]) => String(path).endsWith('portos-db.sql'))).toHaveLength(1);
+ if (process.platform !== 'win32') expect(replayed.mode).toBe(0o600);
+ expect(existsSync(replayed.spoolPath)).toBe(false);
+ });
+ });
+
// Manifest SHA-256 verification (#980). The dump is hashed in generateManifest
// under the parent-relative key '../portos-db.sql' — these tests assert the
// exact key, the mismatch refusal, and the backward-compat skip paths.
//
- // sha256File reads the dump via fs.readFile (small-file path). We mock
- // readFile path-aware: manifest.json returns the manifest JSON, the dump path
- // returns the SQL bytes that sha256File hashes. The dump content here is the
- // small string 'CREATE TABLE a;' — its real sha256 is the constant below.
- const DUMP_SQL = 'CREATE TABLE a;';
+ // The dump is hashed from the same stream admission reads (#8782). readFile
+ // is mocked path-aware for manifest.json; the dump bytes come from the
+ // mocked stream, and their real sha256 is the constant below.
+ const DUMP_SQL = COMPLETE_DUMP;
// Compute the genuine hash so the "match" test verifies real bytes, not a
// hard-coded string that could drift from sha256File's implementation.
const REAL_DUMP_SHA256 = createHash('sha256').update(Buffer.from(DUMP_SQL)).digest('hex');
@@ -1334,8 +1431,9 @@ describe('restorePostgres', () => {
}
return JSON.stringify(manifestObj);
}
- return DUMP_SQL;
+ throw new Error(`unexpected readFile ${path}`);
});
+ mockDumpStream(DUMP_SQL);
}
it('proceeds when the dump hash matches the manifest (match)', async () => {
@@ -1343,7 +1441,7 @@ describe('restorePostgres', () => {
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
expect(result.status).toBe('ok');
expect(result.dryRun).toBe(true);
- expect(result.tableCount).toBe(1);
+ expect(result.tableCount).toBe(2);
});
it('refuses with manifest_mismatch when the dump hash differs (mismatch)', async () => {
@@ -1358,14 +1456,14 @@ describe('restorePostgres', () => {
mockDumpAndManifest(null);
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
expect(result.status).toBe('ok');
- expect(result.tableCount).toBe(1);
+ expect(result.tableCount).toBe(2);
});
it('skips verification when the manifest lacks the dump key (pre-#976 manifest)', async () => {
mockDumpAndManifest({ files: { 'instances.json': 'abc123' } });
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
expect(result.status).toBe('ok');
- expect(result.tableCount).toBe(1);
+ expect(result.tableCount).toBe(2);
});
it.each([
@@ -1374,10 +1472,11 @@ describe('restorePostgres', () => {
])('refuses dry-run and real restore when manifest.json has %s', async (_case, manifestResult) => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: DUMP_SQL.length, isFile: () => true });
vi.spyOn(fs, 'readFile').mockImplementation(async (p) => {
- if (!String(p).endsWith('manifest.json')) return DUMP_SQL;
+ if (!String(p).endsWith('manifest.json')) throw new Error(`unexpected readFile ${p}`);
if (manifestResult instanceof Error) throw manifestResult;
return manifestResult;
});
+ mockDumpStream(DUMP_SQL);
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
await expect(restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true }))
@@ -1448,7 +1547,7 @@ describe('restorePostgres', () => {
await vi.advanceTimersByTimeAsync(9 * 60 * 1000);
expect(proc.kill).not.toHaveBeenCalled();
- proc.emit('close', 0);
+ proc.emit('close', 0);
await expect(pending).resolves.toMatchObject({ status: 'ok' });
} finally {
vi.useRealTimers();
diff --git a/server/services/backupDatabaseDump.js b/server/services/backupDatabaseDump.js
new file mode 100644
index 0000000000..32808d8fc4
--- /dev/null
+++ b/server/services/backupDatabaseDump.js
@@ -0,0 +1,108 @@
+/**
+ * Admission of a snapshot's plain-format pg_dump before a full restore (#8782).
+ *
+ * A full restore resets every application table before replaying the dump, so
+ * a dump that merely parses is not enough: a truncated file that ends between
+ * complete statements (or holds only its header comments) would commit the
+ * reset and leave empty tables behind. Historical snapshots carry no checksum
+ * to catch that, so completeness is proven from the dump's own envelope.
+ */
+import { createReadStream, createWriteStream } from 'fs';
+import { createHash } from 'crypto';
+import { StringDecoder } from 'string_decoder';
+
+// Present in every PortOS database since the first pg_dump backup. Tables added
+// later are deliberately NOT required: an old dump legitimately predates them,
+// and schema reconciliation recreates them after replay.
+export const REQUIRED_DUMP_TABLES = ['memories', 'memory_links'];
+
+// pg_dump writes this comment block last. Newer pg_dump (17.6/16.10/15.14+)
+// follows it with `\unrestrict <key>`; nothing else may come after it.
+const COMPLETE_TRAILER = /\n--\r?\n-- PostgreSQL database dump complete\r?\n--\r?\n(?:\s*\\unrestrict [^\r\n]*)?\s*$/;
+const CREATE_TABLE_LINE = /^CREATE TABLE (?:public\.)?"?([A-Za-z_][A-Za-z0-9_]*)"? \(/gm;
+const TAIL_BYTES = 4096;
+// A CREATE TABLE header is short. Past this, a line is data (a COPY row, or a
+// file that is not SQL at all) and is skipped rather than buffered whole.
+const MAX_SCANNED_LINE = 64 * 1024;
+
+/**
+ * Stream the dump once. Read failures reject — they are never an empty dump.
+ * With `spoolTo`, the exact bytes inspected are also written to that new file
+ * (created exclusively, owner-only), so a restore can replay what it checked
+ * even if the snapshot changes afterwards; a spool write failure rejects too.
+ * @param {string} path
+ * @param {{ spoolTo?: string }} [options]
+ * @returns {Promise<{ sizeBytes: number, sha256: string, tableCount: number, complete: boolean, missingTables: string[] }>}
+ */
+export function inspectDatabaseDump(path, { spoolTo } = {}) {
+ return new Promise((resolvePromise, reject) => {
+ const hash = createHash('sha256');
+ const decoder = new StringDecoder('utf8');
+ const tables = new Set();
+ let tableCount = 0;
+ let sizeBytes = 0;
+ let tail = Buffer.alloc(0);
+ let carry = '';
+ let skippingLine = false;
+ const scan = (text) => {
+ for (const [, name] of text.matchAll(CREATE_TABLE_LINE)) {
+ tableCount += 1;
+ tables.add(name);
+ }
+ };
+
+ const stream = createReadStream(path);
+ const spool = spoolTo ? createWriteStream(spoolTo, { flags: 'wx', mode: 0o600 }) : null;
+ let failed = false;
+ const fail = (err) => {
+ if (failed) return;
+ failed = true;
+ stream.destroy();
+ spool?.destroy();
+ reject(err);
+ };
+ stream.on('error', fail);
+ // pipe() ends the spool after the last chunk; the result waits until it is on disk.
+ const spooled = spool
+ ? new Promise((resolveSpool) => spool.on('finish', resolveSpool))
+ : Promise.resolve();
+ spool?.on('error', fail);
+ if (spool) stream.pipe(spool);
+ stream.on('data', (chunk) => {
+ hash.update(chunk);
+ sizeBytes += chunk.length;
+ tail = chunk.length >= TAIL_BYTES
+ ? chunk.subarray(chunk.length - TAIL_BYTES)
+ : Buffer.concat([tail, chunk]).subarray(-TAIL_BYTES);
+
+ let text = decoder.write(chunk);
+ if (skippingLine) {
+ const newline = text.indexOf('\n');
+ if (newline === -1) return;
+ text = text.slice(newline + 1);
+ skippingLine = false;
+ }
+ text = carry + text;
+ const lineEnd = text.lastIndexOf('\n') + 1;
+ scan(text.slice(0, lineEnd));
+ carry = text.slice(lineEnd);
+ if (carry.length > MAX_SCANNED_LINE) {
+ scan(carry);
+ carry = '';
+ skippingLine = true;
+ }
+ });
+ stream.on('end', () => {
+ if (!skippingLine) scan(carry + decoder.end());
+ const result = {
+ sizeBytes,
+ sha256: hash.digest('hex'),
+ tableCount,
+ complete: COMPLETE_TRAILER.test(tail.toString('latin1')),
+ missingTables: REQUIRED_DUMP_TABLES.filter(name => !tables.has(name)),
+ };
+ spooled.then(() => { if (!failed) resolvePromise(result); });
+ });
+ });
+}
+
diff --git a/server/services/backupDatabaseDump.test.js b/server/services/backupDatabaseDump.test.js
new file mode 100644
index 0000000000..fe5411c3d0
--- /dev/null
+++ b/server/services/backupDatabaseDump.test.js
@@ -0,0 +1,57 @@
+/**
+ * The streamed dump scanner must see table headers and the terminal marker
+ * wherever the 64 KiB read chunks happen to split a real file (#8782). The
+ * restore-level contracts live in backup.test.js / backup.db.test.js.
+ */
+import { afterAll, describe, expect, it } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { createHash } from 'crypto';
+import { inspectDatabaseDump } from './backupDatabaseDump.js';
+
+const dir = mkdtempSync(join(tmpdir(), 'portos-dump-inspect-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const CHUNK = 64 * 1024;
+const TRAILER = '\n--\n-- PostgreSQL database dump complete\n--\n\n';
+const write = (name, text) => {
+ const path = join(dir, name);
+ writeFileSync(path, text);
+ return path;
+};
+
+describe('inspectDatabaseDump', () => {
+ it('counts a table header split across a read boundary and skips an oversized COPY row', async () => {
+ const lead = '-- PostgreSQL database dump\n';
+ // Place `CREATE TABLE public.memories (` so the chunk boundary cuts it.
+ const pad = `--${'x'.repeat(CHUNK - lead.length - 10 - 3)}\n`;
+ const longRow = `COPY public.memories (id) FROM stdin;\n${'a'.repeat(3 * CHUNK)}\tCREATE TABLE public.fake (\n\\.\n`;
+ const sql = `${lead}${pad}CREATE TABLE public.memories (\n);\n${longRow}CREATE TABLE public.memory_links (\n);\n${TRAILER}`;
+ expect(sql.indexOf('CREATE TABLE public.memories')).toBeLessThan(CHUNK);
+ expect(sql.indexOf('memories (')).toBeGreaterThan(CHUNK);
+ const result = await inspectDatabaseDump(write('split.sql', sql));
+ expect(result).toEqual({
+ sizeBytes: Buffer.byteLength(sql),
+ sha256: createHash('sha256').update(sql).digest('hex'),
+ tableCount: 2,
+ complete: true,
+ missingTables: [],
+ });
+ });
+
+ it.each([
+ ['legacy trailer without \\unrestrict', TRAILER, true],
+ ['CRLF trailer', TRAILER.replaceAll('\n', '\r\n'), true],
+ ['\\unrestrict trailer', `${TRAILER}\\unrestrict k3y\n\n`, true],
+ ['statement after the marker', `${TRAILER}SELECT 1;\n`, false],
+ ['no marker', '\n', false],
+ ])('judges completeness from the %s', async (_case, tail, complete) => {
+ const sql = `CREATE TABLE public.memories (\n);\nCREATE TABLE public.memory_links (\n);\n${tail}`;
+ expect((await inspectDatabaseDump(write('tail.sql', sql))).complete).toBe(complete);
+ });
+
+ it('rejects a read failure rather than reporting an empty dump', async () => {
+ await expect(inspectDatabaseDump(join(dir, 'missing.sql'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});