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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: restore dumps with provisioner-owned extensions (#9887)
Adam Eivy61775cbd7e13
diff --git a/scripts/db.sh b/scripts/db.shindex 5bd92ba13c..c327a16f60 100755--- a/scripts/db.sh+++ b/scripts/db.sh@@ -633,7 +633,7 @@ cmd_export() {err "Could not create a temporary dump file in $DUMP_DIR" >&2return 1fi- if ! run_pg_dump --no-owner --no-privileges --if-exists --clean > "$tmpfile"; then+ if ! run_pg_dump --no-owner --no-privileges --no-comments --if-exists --clean > "$tmpfile"; thenrm -f "$tmpfile"err "pg_dump failed — no dump was written" >&2return 1diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.jsindex 231064066d..f17ad2f8f1 100644--- a/server/services/backup.db.test.js+++ b/server/services/backup.db.test.js@@ -66,19 +66,26 @@ afterAll(async () => {// Vitest timing out an assertion does not cancel the real restore. Drain it// before cleanup queries, which otherwise race its maintenance fence.await Promise.allSettled([...pendingRestores]);- 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();+ runDbMigrationsFault.next = null;+ try {+ 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();+ }+ } finally {+ // Resource release must survive an earlier replay/repair/cleanup failure.+ await Promise.all([+ close(),+ dest && rm(dest, { recursive: true, force: true }),+ dataRoot.path && rm(dataRoot.path, { recursive: true, force: true }),+ ]);}- await close();- if (dest) await rm(dest, { recursive: true, force: true });- if (dataRoot.path) await rm(dataRoot.path, { recursive: true, force: true });});async function restore(dryRun = false, snapshotId = 'old-schema') {@@ -100,6 +107,7 @@ describe.skipIf(!ready)('restore older database schema', () => {// query the shared database; a failed drain hook skips that case's body.beforeEach(async () => {await Promise.all([...pendingRestores]);+ runDbMigrationsFault.next = null;});// Prepare the shared snapshot in a hook so setup failures stop dependent@@ -124,6 +132,7 @@ describe.skipIf(!ready)('restore older database schema', () => {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);+ expect(await readFile(dumpPath, 'utf8')).toContain('COMMENT ON EXTENSION');// Boot current schema, including its new inbound foreign key. An empty// newer table is sufficient to break the old direct-replay implementation.diff --git a/server/services/backup.js b/server/services/backup.jsindex adb673f834..9abd7d0936 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -20,7 +20,7 @@ import { createLineReader } from '../lib/streamLines.js';import { getEvent } from './eventScheduler.js';import { POOL_CONFIG, checkHealth, databaseRestoreRecovery, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';import { withPgToolEnv, resolvePgDumpBinary } from '../lib/pgTools.js';-import { inspectDatabaseDump } from './backupDatabaseDump.js';+import { inspectDatabaseDump, prepareDatabaseReplay } from './backupDatabaseDump.js';import {captureSyncFeedPositions, pendingRecoveryResult, repairCommittedRestore, restoreApplicationName, restoreReceiptSql,restoreRecoveryRefusal, settleReplayOutcome,@@ -754,6 +754,7 @@ export async function dumpPostgres(outputPath) {'-d', pgDb,'--no-owner','--no-acl',+ '--no-comments','--clean','--if-exists',// Machine-local replay receipts (#9725) describe this install's past@@ -1593,7 +1594,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou}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+ // dump, so replay derives only from the checked bytes even if the// snapshot changes afterwards (#8782). Preview only inspects.const spoolDir = dryRun ? null : await mkdtemp(join(tmpdir(), 'portos-restore-')).catch((err) => {console.error(`❌ restore: cannot stage dump for snapshot ${snapshotId}: ${err.message}`);@@ -1636,6 +1637,14 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotIreturn { status: 'failed', reason: 'dump_incomplete', error: `The snapshot database dump is incomplete (missing ${missing}). Restore was refused without changing data.` };}const { tableCount } = dump;+ // 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.+ 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;+ });+ if (!dryRun && !replayPath) return DUMP_UNREADABLE;// Preview remains read-only. Recheck inside the replay transaction as well,// so a changed catalog cannot turn a previously safe preview into a cascade.@@ -1685,7 +1694,7 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI'-X', '-v', 'ON_ERROR_STOP=1','--single-transaction','--echo-all',- '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', spoolPath,+ '-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-c', reset, '-f', replayPath,'-c', restoreReceiptSql(record),], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...pgEnv, PGAPPNAME: restoreApplicationName(record.id) } });diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 793e3b74fa..91455c7aec 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -999,7 +999,7 @@ describe('dumpPostgres status classification', () => {await flush();proc.emit('close', 0);await p;- expect(spawn).toHaveBeenCalledWith('/custom/bin/pg_dump', expect.any(Array), expect.any(Object));+ expect(spawn).toHaveBeenCalledWith('/custom/bin/pg_dump', expect.arrayContaining(['--no-comments']), expect.any(Object));} finally {delete process.env.PORTOS_PGDUMP;// clearAllMocks() doesn't reset implementations — restore the null default@@ -1628,6 +1628,33 @@ 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 () => {+ 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 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 } });+ throw new Error('Unexpected read');+ });+ mockDumpStream(sql);+ const proc = fakeProc();+ let replayed;+ spawn.mockImplementation((_bin, args) => {+ const path = args[args.indexOf('-f') + 1];+ replayed = { path, sql: readFileSync(path, 'utf8') };+ expect(args.at(-1)).toContain(originalHash);+ expect(readRecoveryJournal().dumpSha256).toBe(originalHash);+ return proc;+ });+ const pending = restorePostgres('/dest', 'snap-1', { dryRun: false });+ 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(existsSync(replayed.path)).toBe(false);+ });+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();diff --git a/server/services/backupDatabaseDump.js b/server/services/backupDatabaseDump.jsindex 5dcf7736a1..349c7d5562 100644--- a/server/services/backupDatabaseDump.js+++ b/server/services/backupDatabaseDump.js@@ -10,6 +10,8 @@import { createReadStream, createWriteStream } from 'fs';import { createHash } from 'crypto';import { StringDecoder } from 'string_decoder';+import { Transform } from 'node:stream';+import { pipeline } from 'node:stream/promises';// Present in every PortOS database since the first pg_dump backup. Tables added// later are deliberately NOT required: an old dump legitimately predates them,@@ -20,6 +22,13 @@ export const REQUIRED_DUMP_TABLES = ['memories', 'memory_links'];// 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_STATEMENT = /^CREATE TABLE (?:public\.)?"?([A-Za-z_][A-Za-z0-9_]*)"? \(/;+// The scanner omits string contents, retaining only their opening quote.+// Match the complete scanned statement, not arbitrary SQL starting with COMMENT.+const EXTENSION_COMMENT = /^COMMENT ON EXTENSION (?:"(?:[^"]|"")*"|[A-Za-z_][A-Za-z0-9_$]*) IS (?:E?'|NULL)\s*$/;+// The reset deliberately retains installed extensions. pg_dump --clean still+// emits these drops, which require ownership even with --no-owner/--no-comments.+// Preserve that reset contract; never omit CASCADE or other DROP statements.+const EXTENSION_DROP = /^DROP EXTENSION IF EXISTS (?:"(?:[^"]|"")*"|[A-Za-z_][A-Za-z0-9_$]*)\s*$/;const TAIL_BYTES = 4096;// Bound the buffered line and statement prefix; oversized COPY rows are skipped.// Oversized SQL lines fail admission rather than losing lexical context.@@ -32,12 +41,16 @@ const MAX_SCANNED_LINE = 64 * 1024;* 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[] }>}+ * @returns {Promise<{ sizeBytes: number, sha256: string, tableCount: number, complete: boolean, missingTables: string[], extensionMetadata?: {start: number, end: number}[] }>}*/export function inspectDatabaseDump(path, { spoolTo } = {}) {return new Promise((resolvePromise, reject) => {const hash = createHash('sha256');- const decoder = new StringDecoder('utf8');+ // Latin-1 preserves byte offsets and dumps in non-UTF-8 client encodings.+ const decoder = new StringDecoder('latin1');+ const extensionMetadata = [];+ let scannedBytes = 0;+ let statementStart = null;const tables = new Set();let tableCount = 0;let sizeBytes = 0;@@ -53,6 +66,8 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {// Keep only the statement prefix: COPY rows and SQL values may be huge.// Count completed top-level statements, never SQL-looking stored content.const scanLine = (line) => {+ const lineStart = scannedBytes;+ scannedBytes += line.length;if (copyData) {if (line.replace(/\r?\n$/, '') === '\\.') copyData = false;return;@@ -83,13 +98,18 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {if (c === '-' && next === '-') break;if (c === '/' && next === '*') { blockDepth = 1; i += 1; continue; }if (c === ';') {+ if (spoolTo && (EXTENSION_COMMENT.test(statement) || EXTENSION_DROP.test(statement))) {+ extensionMetadata.push({ start: statementStart, end: lineStart + i + 1 });+ }const match = statement.match(CREATE_TABLE_STATEMENT);if (match) { tableCount += 1; tables.add(match[1]); }copyData = /^COPY\s/.test(statement) && / FROM stdin$/.test(statement);statement = '';+ statementStart = null;if (copyData) break;continue;}+ if (statementStart === null && !/\s/.test(c)) statementStart = lineStart + i;if (c === '$') {const delimiter = line.slice(i).match(/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)?.[0];if (delimiter) { dollarQuote = delimiter; i += delimiter.length - 1; }@@ -142,7 +162,8 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {let text = decoder.write(chunk);if (skippingLine) {const newline = text.indexOf('\n');- if (newline === -1) return;+ if (newline === -1) { scannedBytes += text.length; return; }+ scannedBytes += newline + 1;text = text.slice(newline + 1);skippingLine = false;}@@ -154,6 +175,7 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {// An oversized SQL line cannot be safely skipped while retaining its// lexical state. pg_dump data uses COPY, whose rows are safe to skip.if (!copyData) unscannable = true;+ scannedBytes += carry.length;carry = '';skippingLine = true;}@@ -167,9 +189,42 @@ export function inspectDatabaseDump(path, { spoolTo } = {}) {complete: !unscannable && !copyData && !quote && !dollarQuote && !blockDepth&& !statement.trim() && COMPLETE_TRAILER.test(tail.toString('latin1')),missingTables: REQUIRED_DUMP_TABLES.filter(name => !tables.has(name)),+ ...(spoolTo ? { extensionMetadata } : {}),};spooled.then(() => { if (!failed) resolvePromise(result); });});});}+/**+ * Omit admitted extension comments and clean-dump extension drops from the+ * private replay copy. The snapshot, checksum, completion proof and recovery+ * receipt retain the original bytes.+ * All other bytes pass through unchanged, including non-UTF-8 COPY data.+ */+export async function prepareDatabaseReplay(spoolPath, extensionMetadata) {+ if (!extensionMetadata.length) return spoolPath;+ const replayPath = `${spoolPath}.replay`;+ let offset = 0;+ let rangeIndex = 0;+ const omitMetadata = new Transform({+ transform(chunk, _encoding, callback) {+ const end = offset + chunk.length;+ let cursor = offset;+ while (rangeIndex < extensionMetadata.length) {+ const range = extensionMetadata[rangeIndex];+ if (range.start >= end) break;+ if (range.start > cursor) this.push(chunk.subarray(cursor - offset, range.start - offset));+ cursor = Math.max(cursor, Math.min(end, range.end));+ if (range.end > end) break;+ rangeIndex += 1;+ }+ if (cursor < end) this.push(chunk.subarray(cursor - offset));+ offset = end;+ callback();+ },+ });+ await pipeline(createReadStream(spoolPath), omitMetadata,+ createWriteStream(replayPath, { flags: 'wx', mode: 0o600 }));+ return replayPath;+}diff --git a/server/services/backupDatabaseDump.test.js b/server/services/backupDatabaseDump.test.jsindex 8966e1635f..567bca6c9f 100644--- a/server/services/backupDatabaseDump.test.js+++ b/server/services/backupDatabaseDump.test.js@@ -4,11 +4,11 @@* 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 { mkdtempSync, rmSync, writeFileSync, readFileSync, statSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { createHash } from 'crypto';-import { inspectDatabaseDump } from './backupDatabaseDump.js';+import { inspectDatabaseDump, prepareDatabaseReplay } from './backupDatabaseDump.js';const dir = mkdtempSync(join(tmpdir(), 'portos-dump-inspect-'));afterAll(() => rmSync(dir, { recursive: true, force: true }));@@ -67,6 +67,30 @@ describe('inspectDatabaseDump', () => {expect((await inspectDatabaseDump(write('unterminated.sql', sql))).complete).toBe(false);});+ // #9887: only real top-level extension metadata can be omitted. Stored+ // SQL-looking data and ordinary comments must remain byte-for-byte intact.+ it('stages extension comments across chunks without changing data or original integrity', async () => {+ const ordinary = "COMMENT ON TABLE public.memories IS '\nCOMMENT ON EXTENSION vector IS ''stored'';\n';\n";+ const routine = "CREATE FUNCTION public.example() RETURNS text AS $body$\nCOMMENT ON EXTENSION vector IS 'function';\n$body$ LANGUAGE sql;\n";+ const copy = Buffer.concat([Buffer.from("COPY public.memories (id) FROM stdin;\nCOMMENT ON EXTENSION vector IS 'row';\n"),+ Buffer.alloc(3 * CHUNK, 0xe9), Buffer.from("\n\\.\n")]);+ const extension = `DROP EXTENSION IF EXISTS vector; COMMENT ON EXTENSION "example""name" IS 'first; ''quoted''\n${'x\n'.repeat(CHUNK)}last';`;+ const prefix = Buffer.concat([Buffer.from("CREATE TABLE public.memories (\n);\nCREATE TABLE public.memory_links (\n);\n" + ordinary + routine), copy]);+ const suffix = Buffer.from("\nDROP TABLE public.example; DROP EXTENSION vector CASCADE;\nCOMMENT ON EXTENSION vector IS NULL; SELECT 42;\n" + TRAILER);+ const sql = Buffer.concat([prefix, Buffer.from(extension), suffix]);+ const original = write('comments.sql', sql);+ const spoolTo = join(dir, 'comments-spool.sql');+ const dump = await inspectDatabaseDump(original, { spoolTo });+ expect(dump).toMatchObject({ complete: true, missingTables: [],+ sha256: createHash('sha256').update(sql).digest('hex'), sizeBytes: sql.length });+ expect(dump.extensionMetadata).toHaveLength(3);+ const replayPath = await prepareDatabaseReplay(spoolTo, dump.extensionMetadata);+ expect(readFileSync(original)).toEqual(sql);+ expect(readFileSync(spoolTo)).toEqual(sql);+ expect(readFileSync(replayPath)).toEqual(Buffer.concat([prefix, Buffer.from(" \nDROP TABLE public.example; DROP EXTENSION vector CASCADE;\n SELECT 42;\n" + TRAILER)]));+ if (process.platform !== 'win32') expect(statSync(replayPath).mode & 0o777).toBe(0o600);+ });+it('rejects a read failure rather than reporting an empty dump', async () => {await expect(inspectDatabaseDump(join(dir, 'missing.sql'))).rejects.toMatchObject({ code: 'ENOENT' });});diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.jsindex acd0f1d866..8b712f04e3 100644--- a/server/services/databaseMaintenanceTransfer.test.js+++ b/server/services/databaseMaintenanceTransfer.test.js@@ -140,7 +140,7 @@ describe.skipIf(process.platform === 'win32')('offline database transfer', () =>expect(alive(writer.pid)).toBe(false);const [dump] = stubs.invocations('pg_dump');const [load] = stubs.invocations('psql');- expect(dump).toBe(`pg_dump ${endpointArgs(source)} --no-owner --no-privileges --if-exists --clean`);+ expect(dump).toBe(`pg_dump ${endpointArgs(source)} --no-owner --no-privileges --no-comments --if-exists --clean`);expect(load).toBe(`psql ${endpointArgs(target)} -v ON_ERROR_STOP=1 --single-transaction`);// Inherited libpq endpoint/option variables never reach the client tools.expect(stubs.receivedVariables()).toEqual(['PGPASSWORD']);diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex ec67a38d71..fadad80891 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -736,7 +736,7 @@ async function exportDatabaseImpl(backend) {}const result = await runCmd(pgDumpBin, ['-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,- '--no-owner', '--no-privileges', '--if-exists', '--clean', '-f', dumpFile+ '--no-owner', '--no-privileges', '--no-comments', '--if-exists', '--clean', '-f', dumpFile], 120_000, env);if (result.exitCode !== 0) {throw new ServerError('Export failed', { status: 500, context: { details: result.stderr || result.stdout } });