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: stream pg_dump verification so backups can't exhaust server heap (#9119)
Adam Eivy0e1cce0a869c
diff --git a/server/services/backup.js b/server/services/backup.jsindex e8e3b5eb51..439187303b 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -9,7 +9,7 @@import { dashboardEvents } from './dashboardEvents.js';import { spawn } from '../lib/childProcess.js';import { killWithEscalation } from '../lib/killWithEscalation.js';-import { access, lstat, mkdtemp, readdir, readFile, rm, stat, unlink, writeFile } from 'fs/promises';+import { access, lstat, mkdtemp, readdir, rm, stat, unlink, writeFile } from 'fs/promises';import { PassThrough } from 'node:stream';import { hostname, tmpdir } from 'os';import { basename, join, resolve, relative, isAbsolute } from 'path';@@ -660,7 +660,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl* escape hatch from "PG required but dump failed" (data at risk):* { status: 'ok', sizeBytes, tableCount }* { status: 'skipped', reason: 'not_configured' } (explicit file escape hatch only)- * { status: 'failed', reason: 'pg_unreachable'|'pg_dump_missing'|'version_mismatch'|'dump_error'|'empty_dump'|'timeout', error }+ * { status: 'failed', reason: 'pg_unreachable'|'pg_dump_missing'|'version_mismatch'|'dump_error'|'empty_dump'|'inspect_error'|'timeout', error }* (pg_unreachable fires whenever Postgres is required — i.e. not the file* escape hatch — but the DB is down at backup time; version_mismatch means* no installed pg_dump is new enough for the running server)@@ -765,8 +765,18 @@ export async function dumpPostgres(outputPath) {resolvePromise({ status: 'failed', reason: 'empty_dump', error: 'dump file missing or 0 bytes' });return;}- const sql = await readFile(outputPath, 'utf-8').catch(() => '');- const tableCount = (sql.match(/^CREATE TABLE /gm) || []).length;+ // Stream the dump for its table count — reading it whole would scale+ // server heap with database size. Own the rejection here: this is an+ // event callback, so a throw would leave the outer Promise unsettled.+ const inspected = await inspectDatabaseDump(outputPath).catch((err) => {+ console.warn(`⚠️ pg_dump inspection failed: ${err.code || err.message}`);+ return null;+ });+ if (!inspected) {+ resolvePromise({ status: 'failed', reason: 'inspect_error', error: 'dump could not be read for verification' });+ return;+ }+ const tableCount = inspected.tableCount;console.log(`💾 pg_dump complete: ${Math.round(info.size / 1024)}KB, ${tableCount} tables`);// Don't return the absolute dump path: this result is persisted into// state.pgBackup and surfaced to the client via GET /api/backup/status,diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 8582f40438..46fa984c0c 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -1060,7 +1060,7 @@ describe('dumpPostgres status classification', () => {checkHealth.mockResolvedValue({ connected: true, hasSchema: true });let dumpSize = 0;vi.spyOn(fs, 'stat').mockImplementation(async () => ({ size: dumpSize }));- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE memories (...);\n');+ createReadStream.mockImplementation(() => Readable.from([Buffer.from('CREATE TABLE memories (...);\n')]));const proc = fakeProc();spawn.mockReturnValue(proc);@@ -1093,21 +1093,35 @@ describe('dumpPostgres status classification', () => {expect(result.reason).toBe('empty_dump');});- it('returns ok with sizeBytes and tableCount on a good dump', async () => {+ it('returns ok with streamed sizeBytes and tableCount on a good dump', async () => {checkHealth.mockResolvedValue({ connected: true, hasSchema: true });vi.spyOn(fs, 'stat').mockResolvedValue({ size: 2048 });- vi.spyOn(fs, 'readFile').mockResolvedValue(- 'CREATE TABLE memories (...);\nCREATE TABLE memory_links (...);\n'- );+ const readFileSpy = vi.spyOn(fs, 'readFile');+ createReadStream.mockImplementation(() => Readable.from([Buffer.from(+ 'CREATE TABLE public.memories (\n id uuid\n);\nCREATE TABLE public.memory_links (\n id uuid\n);\n'+ )]));const proc = fakeProc();spawn.mockReturnValue(proc);const p = dumpPostgres('/tmp/x.sql');await flush();proc.emit('close', 0);const result = await p;- expect(result.status).toBe('ok');- expect(result.sizeBytes).toBe(2048);- expect(result.tableCount).toBe(2);+ expect(result).toMatchObject({ status: 'ok', sizeBytes: 2048, tableCount: 2 });+ expect(readFileSpy).not.toHaveBeenCalled();+ });++ it('settles failed/inspect_error when streaming the dump fails', async () => {+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ vi.spyOn(fs, 'stat').mockResolvedValue({ size: 2048 });+ createReadStream.mockImplementation(() => new Readable({+ read() { this.destroy(Object.assign(new Error('boom'), { code: 'EIO' })); }+ }));+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const p = dumpPostgres('/tmp/x.sql');+ await flush();+ proc.emit('close', 0);+ await expect(p).resolves.toMatchObject({ status: 'failed', reason: 'inspect_error' });});});