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: reserve fresh backup snapshots without overwriting recovery points (#9452)
[._.]/ Adam Eivy84030b3a9b37
diff --git a/server/services/backup.js b/server/services/backup.jsindex ed139422e0..8c55164d71 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -9,7 +9,8 @@import { dashboardEvents } from './dashboardEvents.js';import { spawn } from '../lib/childProcess.js';import { killWithEscalation } from '../lib/killWithEscalation.js';-import { access, lstat, mkdtemp, readdir, rm, stat, unlink, writeFile } from 'fs/promises';+import { access, lstat, mkdir, mkdtemp, readdir, rm, stat, unlink, writeFile } from 'fs/promises';+import { randomUUID } from 'node:crypto';import { PassThrough } from 'node:stream';import { hostname, tmpdir } from 'os';import { basename, join, resolve, relative, isAbsolute } from 'path';@@ -575,20 +576,43 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disablerror.cause = cause;throw error;});- snapshotId = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');+ const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');const snapshotsRoot = join(destPath, 'snapshots', MACHINE_HOST);- snapshotDir = join(snapshotsRoot, snapshotId);- parentMarker = parentMarkerPath(snapshotDir, snapshotId);+ await ensureDir(snapshotsRoot);+ // Own the durable guard before exposing a directory. Never adopt an+ // existing tree, even when its timestamp matches this run's clock.+ for (let attempt = 0; attempt < 100; attempt += 1) {+ const candidateId = attempt === 0 ? timestamp : `${timestamp}-${randomUUID()}`;+ const candidateDir = join(snapshotsRoot, candidateId);+ const candidateMarker = parentMarkerPath(candidateDir, candidateId);+ const exists = await lstat(candidateDir).then(() => true, err => {+ if (err.code === 'ENOENT') return false;+ throw err;+ });+ if (exists) continue;+ const reserved = await writeFile(candidateMarker, '', { flag: 'wx' }).then(() => true, err => {+ if (err.code === 'EEXIST') return false;+ throw err;+ });+ if (!reserved) continue;+ const created = await mkdir(candidateDir).then(() => true, async err => {+ // Only our exclusive reservation can be released here. The directory+ // may belong to a competing writer and must remain untouched.+ await unlink(candidateMarker);+ if (err.code === 'EEXIST') return false;+ throw err;+ });+ if (!created) continue;+ snapshotId = candidateId;+ snapshotDir = candidateDir;+ parentMarker = candidateMarker;+ break;+ }+ if (!snapshotDir) throw new Error('Unable to reserve a fresh backup snapshot');const dataDestDir = join(snapshotDir, 'data');console.log(`💾 Backup starting: snapshot ${snapshotId} (excluding ${effectiveExcludes.length} paths)`);if (io) io.emit('backup:started', { snapshotId });-- // Establish the durable parent marker before exposing the snapshot- // directory. A crash during directory setup therefore cannot leave a- // snapshot that consumers mistake for a completed backup after restart.- await ensureDir(snapshotsRoot);- await writeFile(parentMarker, '');await ensureDir(dataDestDir);activeSnapshotId = snapshotId;await writeFile(markerPath(snapshotDir), '');diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 5f84872142..e1e7f80889 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -2752,8 +2752,8 @@ describe('runBackup lifecycle', () => {// rsync/pg_dump are stubbed, so backup work completes via real async I/O// rather than on a fixed number of microtasks. Poll instead of guessing.async function waitFor(predicate, label) {- const deadline = Date.now() + 5000;- while (Date.now() < deadline) {+ const deadline = performance.now() + 5000;+ while (performance.now() < deadline) {if (await predicate()) return;await new Promise((r) => setTimeout(r, 5));}@@ -2807,6 +2807,73 @@ describe('runBackup lifecycle', () => {rmSync(destRoot, { recursive: true, force: true });});+ it.each(['completed', 'failed', 'interrupted', 'reservation', 'directory race'])('preserves a colliding %s snapshot while a new run fails', async (state) => {+ const fsp = await actualFs();+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-01-02T03:04:05Z'));+ try {+ const oldId = '2026-01-02T03-04-05';+ const root = joinPath(destRoot, 'snapshots', machineHost);+ const oldDir = joinPath(root, oldId);+ const guard = joinPath(root, `.${oldId}.in-progress`);+ await fsp.mkdir(root, { recursive: true });+ if (state === 'reservation') {+ await fsp.writeFile(guard, 'other reservation');+ } else if (state === 'directory race') {+ vi.spyOn(fs, 'mkdir').mockImplementation(async (path, ...args) => {+ if (path === oldDir) {+ await fsp.mkdir(oldDir);+ await fsp.writeFile(joinPath(oldDir, 'portos-db.sql'), 'old dump');+ }+ return fsp.mkdir(path, ...args);+ });+ } else {+ await fsp.mkdir(oldDir);+ await fsp.writeFile(joinPath(oldDir, 'portos-db.sql'), 'old dump');+ if (state === 'failed') await fsp.writeFile(joinPath(oldDir, '.failed'), 'old failure');+ if (state === 'interrupted') await fsp.writeFile(guard, 'other reservation');+ }+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = runBackup(destRoot).catch(error => error);+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');+ const newDir = spawn.mock.calls[0][1].at(-1).replace(/\/data$/, '');+ expect(basename(newDir)).not.toBe(oldId);+ await expect(fsp.access(joinPath(root, `.${basename(newDir)}.in-progress`))).resolves.toBeUndefined();+ proc.emit('close', 1);+ expect(await pending).toBeInstanceOf(Error);+ if (state !== 'reservation') expect(await fsp.readFile(joinPath(oldDir, 'portos-db.sql'), 'utf8')).toBe('old dump');+ if (state === 'failed') expect(await fsp.readFile(joinPath(oldDir, '.failed'), 'utf8')).toBe('old failure');+ if (state === 'interrupted' || state === 'reservation') expect(await fsp.readFile(guard, 'utf8')).toBe('other reservation');+ else await expect(fsp.access(guard)).rejects.toThrow();+ } finally {+ vi.useRealTimers();+ }+ });++ it('allocates distinct completed snapshots within the same second', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-01-02T03:04:05Z'));+ try {+ const ids = [];+ for (let i = 0; i < 2; i += 1) {+ const proc = fakeProc();+ spawn.mockReturnValue(proc);+ const pending = runBackup(destRoot);+ await waitFor(() => spawn.mock.calls.length === i + 1, 'rsync spawn');+ proc.emit('close', 0);+ ids.push((await pending).snapshotId);+ }+ expect(new Set(ids).size).toBe(2);+ const { listSnapshots } = await import('./backup.js');+ const snapshots = await listSnapshots(destRoot);+ expect(snapshots.map(snapshot => snapshot.id).sort()).toEqual(ids.sort());+ expect(snapshots.every(snapshot => !snapshot.incomplete && !snapshot.failed)).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });+it.each([0, 1])('invalidates scheduled backups only after readable lifecycle transitions (exit %s)', async (exitCode) => {const { dashboardEvents } = await import('./dashboardEvents.js');const { getState, listSnapshots } = await import('./backup.js');