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: preserve restorable backups when pg dump fails (#8413)
[._.]/ Adam Eivy6a9ca6551671
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 50b16a61ef..7ada7abdc9 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -118,11 +118,11 @@ Separate from snapshot restore: `server/routes/database.js` can copy data **betw## Retention & deletion-Left unbounded, `snapshots/<hostname>/` grows forever — every prior full DB dump stays reachable, so a record deleted from the live database (including `privacy_vault_records`, `privacy_consents`, and `privacy_broker_cases`) remains restorable from an old snapshot indefinitely. `server/lib/backupConfig.js` resolves a per-source `retentionCount`, and `runBackup()` prunes with it after every successful run (`pruneOldSnapshots()` in `backup.js`).+Left unbounded, `snapshots/<hostname>/` grows forever — every prior full DB dump stays reachable, so a record deleted from the live database (including `privacy_vault_records`, `privacy_consents`, and `privacy_broker_cases`) remains restorable from an old snapshot indefinitely. `server/lib/backupConfig.js` resolves a per-source `retentionCount`, and `runBackup()` prunes with it after a successful database dump, or when the explicit file-backend escape hatch skips the dump (`pruneOldSnapshots()` in `backup.js`). A degraded run whose database dump failed skips pruning and logs a warning, preserving older snapshots until a later dump succeeds.- **New installs default to 30 completed snapshots per source.** The default ships as `backup.retentionCount: 30` in `data.reference/settings.json`, copied only into an install that has no `data/settings.json` yet — see the comment on `resolveRetentionCount()` for why this, not a migration, is what keeps an existing install from silently losing its archive. Operators choose 1–365, or Unlimited, from the Backup settings tab.- **`retentionCount` absent or explicitly `null` both mean unlimited** — no pruning runs. This is why an install that predates this setting keeps every snapshot until the operator saves a choice: it has no stored value, and absence resolves to unlimited, not to the new-install default.-- **Pruning runs only after a run reaches a completed snapshot** (rsync finished and a `pg_dump` was attempted, even if it degraded) — a run that fails before that point takes `runBackup()`'s `fail()` path and never prunes. A prune failure is logged and does not fail an otherwise-successful backup.+- **Pruning runs only after a run reaches a completed snapshot with a usable database dump** (`pg_dump` succeeded, or was explicitly skipped by the file-backend escape hatch). A degraded run whose database dump failed keeps older snapshots and reports zero pruned snapshots; retention resumes after a later successful dump. A run that fails before completion never prunes, and a prune failure is logged without failing an otherwise-successful backup.- **Pruning is scoped to the CURRENT machine's namespace** (`snapshots/<hostname>/`) and only ever deletes snapshots whose `snapshotState()` reports neither `incomplete` nor `failed`. It never touches another machine's namespace in a shared destination, the legacy pre-namespace root, or an in-progress/failed snapshot — those stay until the operator deletes them explicitly.- **`DELETE /api/backup/snapshots/:snapshotId?source=<source>`** (`backup.deleteSnapshot()`) permanently removes exactly the selected source/ID pair, immediately — there is no undo and it is never automatic. It shares `resolveSnapshotPath()`'s path-traversal and symlink guards with restore/download, and refuses a snapshot that is still being written (`SNAPSHOT_INCOMPLETE`); unlike restore, a `.failed` snapshot **is** deletable. The Backup settings tab's snapshot history exposes this as a per-row delete action behind a confirmation dialog.diff --git a/server/services/backup.js b/server/services/backup.jsindex 1a77c30487..57124be766 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -622,10 +622,15 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl// before this point takes the `fail()` path below and never reaches// here, so a failed or in-progress snapshot is never a prune candidate.// Retention failures must not fail an otherwise-successful backup.- const pruned = await pruneOldSnapshots(destPath, retentionCount).catch(err => {- console.error(`❌ Backup retention prune failed: ${err.message}`);- return { pruned: 0 };- });+ let pruned = { pruned: 0 };+ if (pgResult.status === 'failed') {+ console.warn(`⚠️ Backup retention skipped: DB dump ${pgResult.reason} — keeping older snapshots`);+ } else {+ pruned = await pruneOldSnapshots(destPath, retentionCount).catch(err => {+ console.error(`❌ Backup retention prune failed: ${err.message}`);+ return { pruned: 0 };+ });+ }return { ...result, prunedSnapshots: pruned.pruned };} catch (err) {diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex dfd882b110..1e65c76615 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -2953,7 +2953,7 @@ describe('runBackup lifecycle', () => {});// ------------------------------------------------------------------------ // Retention pruning (#8334) — after a successful run, the oldest COMPLETED+ // Retention pruning (#8334) — after a dump-successful run, the oldest COMPLETED// snapshots on THIS machine beyond retentionCount are deleted. Failed,// in-progress, and other-source snapshots must never be touched, and// retentionCount null/undefined must never prune anything (an existing@@ -2981,12 +2981,20 @@ describe('runBackup lifecycle', () => {const otherMachine = await seedSnapshot('previous-machine', '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });const io = { emit: vi.fn() };- const proc = fakeProc();- spawn.mockReturnValue(proc);+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ getBackendName.mockReturnValue('postgres');+ const rsync = fakeProc();+ const pgDump = fakeProc();+ spawn.mockReturnValueOnce(rsync).mockReturnValueOnce(pgDump);const pending = runBackup(destRoot, io, { retentionCount: 2 });await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');- proc.emit('close', 0);+ rsync.emit('close', 0);+ await waitFor(() => spawn.mock.calls.length === 2, 'pg_dump spawn');+ const dumpPath = spawn.mock.calls[1][1][spawn.mock.calls[1][1].indexOf('-f') + 1];+ await fsp.writeFile(dumpPath, 'CREATE TABLE example (id integer);');+ pgDump.emit('close', 0);const result = await pending;+ expect(result).toMatchObject({ status: 'ok', pgBackup: { status: 'ok' }, prunedSnapshots: 2 });// Keeps the newest 2 completed snapshots on this machine: the run just// created and old3. old1 and old2 are pruned.@@ -3002,6 +3010,46 @@ describe('runBackup lifecycle', () => {await expect(fsp.stat(otherMachine)).resolves.toBeDefined();});+ it('preserves older snapshots and reports zero pruned when the database dump fails', async () => {+ const fsp = await actualFs();+ const old1 = await seedSnapshot(machineHost, '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });+ const old2 = await seedSnapshot(machineHost, '2020-01-02T00-00-00', { generatedAt: '2020-01-02T00:00:00.000Z' });++ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });+ getBackendName.mockReturnValue('postgres');+ const rsync = fakeProc();+ const pgDump = fakeProc();+ spawn.mockReturnValueOnce(rsync).mockReturnValueOnce(pgDump);+ const { errorEvents } = await import('../lib/errorHandler.js');+ errorEvents.once('error', () => {});+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const pending = runBackup(destRoot, { emit: vi.fn() }, { retentionCount: 1 });+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');+ rsync.emit('close', 0);+ await waitFor(() => spawn.mock.calls.length === 2, 'pg_dump spawn');+ pgDump.emit('close', 1);++ const result = await pending;+ expect(result).toMatchObject({ status: 'degraded', pgBackup: { status: 'failed' }, prunedSnapshots: 0 });+ await expect(fsp.stat(old1)).resolves.toBeDefined();+ await expect(fsp.stat(old2)).resolves.toBeDefined();+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/^⚠️ Backup retention skipped: DB dump dump_error — keeping older snapshots$/));+ });++ it('still prunes when the explicit file-backend dump is skipped', async () => {+ const fsp = await actualFs();+ const old = await seedSnapshot(machineHost, '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });+ const rsync = fakeProc();+ spawn.mockReturnValue(rsync);+ const pending = runBackup(destRoot, { emit: vi.fn() }, { retentionCount: 1 });+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');+ rsync.emit('close', 0);++ const result = await pending;+ expect(result).toMatchObject({ status: 'ok', pgBackup: { status: 'skipped' }, prunedSnapshots: 1 });+ await expect(fsp.stat(old)).rejects.toThrow();+ });+it('does not prune anything when retentionCount is null (unlimited — the legacy/unset default)', async () => {const fsp = await actualFs();const old1 = await seedSnapshot(machineHost, '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });