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 newer-client snapshots to older PostgreSQL servers (#9925)

Adam Eivyfab5cea2b814
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index c76c4c2959..3a5e9b6380 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -165,7 +165,9 @@ After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. Restore
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.
+**Client/server compatibility (#9925).** Preview and execution check the target PostgreSQL major version. A PG17-client dump made from PG16 can be replayed to PG16: the private replay copy omits only the exact top-level `SET transaction_timeout = 0;` header, which [PostgreSQL 17 introduced](https://www.postgresql.org/docs/17/release-17.html). PG17+ targets retain it. COPY rows, quoted functions/strings, comments, and psql `\restrict` / `\unrestrict` commands remain intact. Source bytes, manifest hashes and recovery receipts are unchanged; extension normalization and transactional rollback remain in effect. An unresolvable target major returns `restore_compatibility` with a connectivity/version-check instruction before mutation. This narrow compatibility fix does not make arbitrary newer SQL features portable to older servers.
+
+**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 perform reset preflight or mutations, 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 |
|---|---|
@@ -176,6 +178,7 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ 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_compatibility', error }` | Target PostgreSQL major cannot be established — repair the version check and retry preview before execution |
| `{ status: 'failed', reason: 'restore_journal', error }` | The recovery journal could not be written — refused before any reset |
| `{ status: 'failed', reason: 'restore_error' \| 'timeout', error }` | `psql` replay failed (stderr captured) and was **proven rolled back** from its receipt (below) |
| `{ status: 'failed', reason: 'restore_commit_unknown', error, recovery }` | `psql` did not report success and the receipt could not settle whether the replay committed — recovery pending |
diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.js
index f17ad2f8f1..d43b66bd3b 100644
--- a/server/services/backup.db.test.js
+++ b/server/services/backup.db.test.js
@@ -169,6 +169,23 @@ describe.skipIf(!ready)('restore older database schema', () => {
expect(await runDbMigrations()).toBe(0);
});
+ // #9925: replay a complete real dump with the exact newer-client header
+ // against the guarded test target. On PG16 this previously rolled back.
+ it('restores a newer-client transaction_timeout header without changing its source or receipt identity', async () => {
+ const dir = join(dest, 'snapshots', 'fixture-source', 'newer-client');
+ await mkdir(dir);
+ const original = await readFile(dumpPath, 'utf8');
+ const sql = original.includes('SET transaction_timeout = 0;')
+ ? original : original.replace('SET statement_timeout = 0;', 'SET statement_timeout = 0;\nSET transaction_timeout = 0;');
+ const path = join(dir, 'portos-db.sql');
+ await writeFile(path, sql);
+ await query("UPDATE tribe_people SET name = 'Changed after newer-client backup' WHERE id = $1", [personId]);
+ expect(await restore(true, 'newer-client')).toMatchObject({ status: 'ok', dryRun: true });
+ expect(await restore(false, 'newer-client')).toMatchObject({ status: 'ok', dryRun: false });
+ expect((await query('SELECT name FROM tribe_people WHERE id = $1', [personId])).rows).toEqual([{ name: 'Snapshot person' }]);
+ expect(await readFile(path, 'utf8')).toBe(sql);
+ });
+
// #9725: a committed replay whose repair fails keeps ordinary work fenced
// with its receipt and ORIGINAL floors, and recovery repairs without replay.
it('fences a committed replay whose migrations fail, then recovers from the receipt and original floors', async () => {
diff --git a/server/services/backup.js b/server/services/backup.js
index 9abd7d0936..19559c84ef 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1548,7 +1548,7 @@ const DUMP_UNREADABLE = Object.freeze({ status: 'failed', reason: 'dump_unreadab
* { 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'|'dump_unreadable'|'dump_incomplete'|'restore_preflight'|'restore_journal'|'restore_error'|'timeout', error? }
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'dump_unreadable'|'dump_incomplete'|'restore_compatibility'|'restore_preflight'|'restore_journal'|'restore_error'|'timeout', error? }
* (nothing changed; a failed replay is reported only once proven rolled back)
* { status: 'failed', reason: 'restore_recovery_pending'|'restore_commit_unknown'|'restore_schema_reconciliation'|'restore_sync_resync'|'restore_recovery_release', error, recovery }
* (a restore awaits recovery: ordinary database work stays fenced until
@@ -1614,7 +1614,8 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
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) => {
+ const targetServerMajor = await getServerMajorVersion().catch(() => null);
+ const dump = await inspectDatabaseDump(sqlPath, { spoolTo: spoolPath, targetServerMajor }).catch((err) => {
console.error(`❌ restore: dump unreadable for snapshot ${snapshotId}: ${err.message}`);
return null;
});
@@ -1637,9 +1638,19 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
return { status: 'failed', reason: 'dump_incomplete', error: `The snapshot database dump is incomplete (missing ${missing}). Restore was refused without changing data.` };
}
const { tableCount } = dump;
+ const health = await checkHealth();
+ if (!health.connected) return { status: 'skipped', reason: 'not_configured' };
+ if (!Number.isInteger(targetServerMajor) || targetServerMajor <= 0) {
+ return {
+ status: 'failed',
+ reason: 'restore_compatibility',
+ error: 'Cannot establish the target PostgreSQL major version. Check database connectivity and permission to SHOW server_version_num, then retry preview before restoring. No data was changed.',
+ };
+ }
// Admission checks above always cover the original bytes. Only the private
// replay copy omits extension comments and clean-dump extension drops,
- // whose ownership may belong to a provisioning role.
+ // whose ownership may belong to a provisioning role, plus the exact PG17
+ // transaction_timeout header when replaying to an older target.
const replayPath = dryRun ? null : await prepareDatabaseReplay(spoolPath, dump.extensionMetadata).catch(err => {
console.error(`❌ restore: cannot normalize admitted dump for snapshot ${snapshotId}: ${err.message}`);
return null;
@@ -1648,8 +1659,6 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
// 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' };
const { getDatabaseResetPlan } = await import('./backupDatabaseReset.js');
const { preflight, reset } = await getDatabaseResetPlan();
const preflightError = await query(preflight).then(() => null, error => error);
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 91455c7aec..4d350a89c1 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1224,9 +1224,24 @@ describe('restorePostgres', () => {
rmSync(RECOVERY_JOURNAL(), { force: true });
query.mockReset().mockImplementation(restoreDbAnswer());
checkHealth.mockResolvedValue({ connected: true });
+ getServerMajorVersion.mockResolvedValue(16);
({ restorePostgres } = await import('./backup.js'));
});
+ it.each([null, 0, NaN])('refuses an unknown target major %s equally in preview and execution before mutation', async major => {
+ getServerMajorVersion.mockResolvedValue(major);
+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
+ mockLegacyDumpRead();
+ for (const dryRun of [true, false]) {
+ expect(await restorePostgres('/dest', 'snap-1', { dryRun }))
+ .toMatchObject({ status: 'failed', reason: 'restore_compatibility', error: expect.stringContaining('SHOW server_version_num') });
+ }
+ expect(query).not.toHaveBeenCalled();
+ expect(withDatabaseMaintenance).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
+ expect(readRecoveryJournal()).toBeNull();
+ });
+
it('rejects a path-traversal snapshotId', async () => {
await expect(restorePostgres('/dest', '../../etc', { dryRun: true }))
.rejects.toThrow(/Invalid snapshotId/);
@@ -1628,10 +1643,11 @@ describe('restorePostgres', () => {
// 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('verifies original integrity and receipts while replaying only extension-comment normalization', async () => {
+ it('verifies original integrity and receipts while normalizing extension metadata and the PG17 header', async () => {
const comment = "COMMENT ON EXTENSION vector IS 'provisioned extension';";
const extensionDrop = 'DROP EXTENSION IF EXISTS vector;';
- const sql = DUMP_HEADER + extensionDrop + '\n' + comment + '\n' + DUMP_TABLES + DUMP_TRAILER;
+ const sql = DUMP_HEADER + 'SET transaction_timeout = 0;\n'
+ + extensionDrop + '\n' + comment + '\n' + DUMP_TABLES + DUMP_TRAILER;
const originalHash = createHash('sha256').update(sql).digest('hex');
vi.spyOn(fs, 'readFile').mockImplementation(async path => {
if (String(path).endsWith('manifest.json')) return JSON.stringify({ files: { '../portos-db.sql': originalHash } });
@@ -1651,7 +1667,7 @@ describe('restorePostgres', () => {
await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());
proc.emit('close', 0);
expect(await pending).toMatchObject({ status: 'ok', dryRun: false });
- expect(replayed.sql).toBe(sql.replace(comment, '').replace(extensionDrop, ''));
+ expect(replayed.sql).toBe(sql.replace(comment, '').replace(extensionDrop, '').replace('SET transaction_timeout = 0;\n', ''));
expect(existsSync(replayed.path)).toBe(false);
});
diff --git a/server/services/backupDatabaseDump.js b/server/services/backupDatabaseDump.js
index e50892bfe1..6ccb2b28fd 100644
--- a/server/services/backupDatabaseDump.js
+++ b/server/services/backupDatabaseDump.js
@@ -40,10 +40,10 @@ const MAX_SCANNED_LINE = 64 * 1024;
* (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, omitVersionDirectives?: boolean }} [options]
+ * @param {{ spoolTo?: string, omitVersionDirectives?: boolean, targetServerMajor?: number }} [options]
* @returns {Promise<{ sizeBytes: number, sha256: string, tableCount: number, complete: boolean, missingTables: string[], extensionMetadata?: {start: number, end: number}[] }>}
*/
-export function inspectDatabaseDump(path, { spoolTo, omitVersionDirectives = false } = {}) {
+export function inspectDatabaseDump(path, { spoolTo, omitVersionDirectives = false, targetServerMajor } = {}) {
return new Promise((resolvePromise, reject) => {
const hash = createHash('sha256');
// Latin-1 preserves byte offsets and dumps in non-UTF-8 client encodings.
@@ -74,7 +74,11 @@ export function inspectDatabaseDump(path, { spoolTo, omitVersionDirectives = fal
return;
}
if (!statement && !quote && !dollarQuote && !blockDepth) {
- if (omitVersionDirectives && (/^\\(?:un)?restrict /.test(line) || /^SET transaction_timeout = 0;\r?\n?$/.test(line))) {
+ // Snapshot replay retains psql restrictions. Only the exact pg_dump
+ // header unsupported before PG17 is removable, never stored SQL text.
+ const timeoutHeader = /^SET transaction_timeout = 0;\r?\n?$/.test(line);
+ if ((omitVersionDirectives && (/^\\(?:un)?restrict /.test(line) || timeoutHeader))
+ || (Number.isInteger(targetServerMajor) && targetServerMajor > 0 && targetServerMajor < 17 && timeoutHeader)) {
extensionMetadata.push({ start: lineStart, end: scannedBytes });
return;
}
@@ -211,7 +215,7 @@ export function inspectDatabaseDump(path, { spoolTo, omitVersionDirectives = fal
/**
* Omit admitted extension comments and clean-dump extension drops from the
- * private replay copy. The snapshot, checksum, completion proof and recovery
+ * private replay copy, along with admitted incompatible version headers. The snapshot, checksum, completion proof and recovery
* receipt retain the original bytes.
* All other bytes pass through unchanged, including non-UTF-8 COPY data.
*/
diff --git a/server/services/backupDatabaseDump.test.js b/server/services/backupDatabaseDump.test.js
index 9c668d050a..78b9cac818 100644
--- a/server/services/backupDatabaseDump.test.js
+++ b/server/services/backupDatabaseDump.test.js
@@ -91,6 +91,32 @@ describe('inspectDatabaseDump', () => {
if (process.platform !== 'win32') expect(statSync(replayPath).mode & 0o777).toBe(0o600);
});
+ // #9925: version normalization must never rewrite stored SQL-looking data.
+ it.each([16, 17, 18])('normalizes only the exact top-level PG17 header for target %s', async targetServerMajor => {
+ const header = 'SET transaction_timeout = 0;\r\n';
+ const stored = [
+ '-- SET transaction_timeout = 0;\r\n',
+ '/*\r\nSET transaction_timeout = 0;\r\n*/\r\n',
+ "COMMENT ON TABLE public.memories IS '\r\nSET transaction_timeout = 0;\r\n';\r\n",
+ 'CREATE FUNCTION public.example() RETURNS text AS $body$\r\nSET transaction_timeout = 0;\r\n$body$ LANGUAGE sql;\r\n',
+ 'COPY public.memories (id) FROM stdin;\r\nSET transaction_timeout = 0;\r\n\\.\r\n',
+ 'SET transaction_timeout = 1;\r\n',
+ 'SET transaction_timeout = 0; SELECT 42;\r\n',
+ ].join('');
+ const sql = Buffer.from('\\restrict fixturekey\r\n' + header
+ + 'CREATE TABLE public.memories (\r\n);\r\nCREATE TABLE public.memory_links (\r\n);\r\n'
+ + stored + TRAILER.replaceAll('\n', '\r\n') + '\\unrestrict fixturekey\r\n');
+ const original = write(`target-${targetServerMajor}.sql`, sql);
+ const spoolTo = join(dir, `target-${targetServerMajor}-spool.sql`);
+ const dump = await inspectDatabaseDump(original, { spoolTo, targetServerMajor });
+ expect(dump).toMatchObject({ complete: true, missingTables: [], sha256: createHash('sha256').update(sql).digest('hex') });
+ const replayPath = await prepareDatabaseReplay(spoolTo, dump.extensionMetadata);
+ expect(readFileSync(original)).toEqual(sql);
+ expect(readFileSync(spoolTo)).toEqual(sql);
+ const expected = targetServerMajor < 17 ? Buffer.from(sql.toString().replace(header, '')) : sql;
+ expect(readFileSync(replayPath)).toEqual(expected);
+ });
+
it('retains an oversized statement prefix so invalid SQL still reaches transactional replay', async () => {
const sql = "CREATE TABLE public.memories (\n);\nCREATE TABLE public.memory_links (\n);\n"
+ `COMMENT ON EXTENSION vector IS NULL${' \n'.repeat(CHUNK)}INVALID SQL;\n` + TRAILER;