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: surface backup failures when status persistence fails (#8628)

[._.]/ Adam Eivy95c166845308
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 641b9f9d6e..41a3fafe82 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -60,6 +60,20 @@ describe('backup routes', () => {
});
});
+ it('serves a process-local persistence failure without hiding the last successful snapshot', async () => {
+ const state = {
+ status: 'error', lastSnapshotId: 'previous-snapshot',
+ lastRun: '2026-01-02T00:00:00.000Z', pgBackup: null,
+ error: 'Backup failed; status persistence failed (EACCES). See server logs.',
+ };
+ backup.getState.mockResolvedValue(state);
+ backup.getNextRunTime.mockReturnValue(null);
+ getSettings.mockResolvedValue({ backup: { destPath: '/backup/target' } });
+ const res = await request(buildApp()).get('/api/backup/status');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject(state);
+ });
+
it('returns null destPath when backup is not configured', async () => {
backup.getState.mockResolvedValue({});
backup.getNextRunTime.mockReturnValue(null);
diff --git a/server/services/backup.js b/server/services/backup.js
index 3ed88cc51a..eede97f0bf 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -28,6 +28,7 @@ import { noteSystemActivity } from './systemActivityNotify.js';
// Module-level state
let isRunning = false;
+let failedStateProjection = null;
// The in-process lock is the activity signal the updater reads. Note the edge
// in the same assignment so a client cannot keep a stale "backup running"
@@ -543,7 +544,12 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
if (failureRecorded) await clearInProgressMarkers();
releaseActiveSnapshot();
setBackupRunning(false, 'failure');
- await saveState({ lastRun: new Date().toISOString(), status: 'error', error: err.message, pgBackup: null }).catch(() => {});
+ const failureState = { lastRun: new Date().toISOString(), status: 'error', error: err.message, pgBackup: null };
+ await saveState(failureState, (cause) => {
+ const code = ['EACCES', 'EPERM', 'EIO', 'ENOSPC', 'EROFS', 'ENOENT', 'EMFILE', 'ENFILE'].includes(cause.code) ? cause.code : 'UNKNOWN';
+ failedStateProjection = { ...failureState, error: `Backup failed; status persistence failed (${code}). See server logs.` };
+ console.error(`❌ Backup status persistence failed: transition=error snapshot=${snapshotId ?? 'none'} code=${code}`);
+ });
dashboardEvents.emit('backup:changed');
if (io) io.emit('backup:failed', { snapshotId, error: err.message });
throw err;
@@ -1584,25 +1590,33 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true, sou
}
/**
- * Get persisted backup state with the current in-process run status.
+ * Get backup state with process-local failure and running projections.
*/
export async function getState() {
const state = await readJSONFile(STATE_PATH, DEFAULT_STATE, { strict: true });
- return isRunning ? { ...state, status: 'running' } : state;
+ const projected = failedStateProjection ? { ...state, ...failedStateProjection } : state;
+ return isRunning ? { ...projected, status: 'running' } : projected;
}
/**
* Merge patch into current backup state and persist.
* @param {object} patch - Fields to merge into state
+ * @param {Function} [onFailure] - Handle a rejected write inside the serialized queue
*/
-export async function saveState(patch) {
- return queueStateWrite(async () => {
+export async function saveState(patch, onFailure) {
+ return queueStateWrite(() => (async () => {
await ensureDir(join(PATHS.data, 'backup'));
const current = await getState();
const updated = { ...current, ...patch };
await atomicWrite(STATE_PATH, updated);
+ failedStateProjection = null;
return updated;
- });
+ })().catch((error) => {
+ // Handle the failed transition inside the queue: a later successful write
+ // must clear it, never race with an out-of-queue failure handler.
+ if (onFailure) return onFailure(error);
+ throw error;
+ }));
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index ea534e4f8d..e5932675c9 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -36,8 +36,10 @@ function testDataRoot() {
if (!TEST_DATA_ROOT) TEST_DATA_ROOT = mkdtempSync(joinPath(tmpdir(), 'portos-backup-data-'));
return TEST_DATA_ROOT;
}
-vi.mock('../lib/fileUtils.js', async (importOriginal) =>
- makePathsProxy(await importOriginal(), { dataRoot: testDataRoot }));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: testDataRoot, overrides: { atomicWrite: vi.fn(actual.atomicWrite) } });
+});
afterAll(() => {
if (TEST_DATA_ROOT) rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
@@ -2078,8 +2080,10 @@ describe('getState and saveState', () => {
// data/ tree — and `runBackup lifecycle` below then rewrote the
// developer's genuine data/backup/state.json on every run (#6176; the
// runtime write guard is what surfaced it).
- vi.doMock('../lib/fileUtils.js', async (importOriginal) =>
- makePathsProxy(await importOriginal(), { dataRoot: testDataRoot }));
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: testDataRoot, overrides: { atomicWrite: vi.fn(actual.atomicWrite) } });
+ });
vi.resetModules();
const { rm } = await import('fs/promises');
if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true });
@@ -2939,6 +2943,40 @@ describe('runBackup lifecycle', () => {
await expect(retry).resolves.toMatchObject({ status: 'ok' });
});
+ it('projects a failed scheduled attempt when state persistence fails, then recovers', async () => {
+ const { saveState, getState, listSnapshots } = await import('./backup.js');
+ const { atomicWrite } = await import('../lib/fileUtils.js');
+ await saveState({ lastSnapshotId: 'previous-snapshot', status: 'ok', error: null });
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = runBackup(destRoot).catch(error => error);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotId = basename(await findSnapshotDir());
+ const persistedBefore = await readJson(joinPath(dataRoot, 'backup', 'state.json'));
+ const diagnostic = vi.spyOn(console, 'error').mockImplementation(() => {});
+ atomicWrite.mockRejectedValueOnce(Object.assign(new Error('private path and credential'), { code: 'EACCES' }));
+ proc.emit('close', 23);
+ expect(await pending).toMatchObject({ message: expect.stringContaining('rsync exited with code 23') });
+ expect(isBackupInProgress()).toBe(false);
+ expect(diagnostic).toHaveBeenCalledWith(`❌ Backup status persistence failed: transition=error snapshot=${snapshotId} code=EACCES`);
+ expect(await readJson(joinPath(dataRoot, 'backup', 'state.json'))).toEqual(persistedBefore);
+ expect(await getState()).toMatchObject({
+ status: 'error', lastSnapshotId: 'previous-snapshot', pgBackup: null,
+ error: 'Backup failed; status persistence failed (EACCES). See server logs.',
+ });
+ expect((await listSnapshots(destRoot))[0].failed).toBe(true);
+ // A rejected subsequent write must not clear the process-local projection.
+ atomicWrite.mockRejectedValueOnce(new Error('still unavailable'));
+ await expect(saveState({ status: 'ok' })).rejects.toThrow('still unavailable');
+ expect((await getState()).status).toBe('error');
+ await saveState({ status: 'ok', error: null });
+ expect(await getState()).toMatchObject({ status: 'ok', error: null, lastSnapshotId: 'previous-snapshot' });
+ // Prove the overlay is gone, rather than merely masked by matching values.
+ const fsp = await actualFs();
+ await fsp.writeFile(joinPath(dataRoot, 'backup', 'state.json'), JSON.stringify({ status: 'ok', lastSnapshotId: 'recovered-snapshot' }));
+ expect(await getState()).toEqual({ status: 'ok', lastSnapshotId: 'recovered-snapshot' });
+ });
+
it.each(['ENOENT', 'EACCES', 'EIO'])('persists a failed preflight (%s) over prior success and permits repair', async (code) => {
const { saveState, getState } = await import('./backup.js');
const priorRun = '2026-01-01T00:00:00.000Z';