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: refresh state after partial file restores (#7165)

[._.]/ Adam Eivycd6dcee3ce21
diff --git a/server/services/backup.js b/server/services/backup.js
index a9af7f9089..e5b88ae7a3 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -878,6 +878,28 @@ export async function openSnapshotStream(destPath, snapshotId) {
return archive;
}
+async function reconcileLiveFileRestore(subdirFilter) {
+ const refreshes = [
+ ...(!subdirFilter || subdirFilter === 'brain' || subdirFilter.startsWith('brain/')
+ ? [{ label: 'Brain cache invalidation', run: invalidateBrainCaches }]
+ : []),
+ { label: 'settings reload', run: reloadSettings },
+ ];
+ const results = await Promise.allSettled(
+ refreshes.map(({ run }) => Promise.resolve().then(run)),
+ );
+ const failures = results.flatMap((result, index) => result.status === 'rejected'
+ ? [`${refreshes[index].label}: ${result.reason?.message ?? String(result.reason)}`]
+ : []);
+
+ if (failures.length > 0) {
+ throw new Error(
+ `Live restore cache reconciliation failed (${failures.join('; ')}). Restart PortOS before relying on restored settings or Brain data.`,
+ { cause: results.find(result => result.status === 'rejected').reason },
+ );
+ }
+}
+
/**
* Restore a snapshot back to PATHS.data using rsync.
* @param {string} destPath - Path to external drive backup root
@@ -908,32 +930,28 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
flags.push('--exclude=*');
}
- let changedFiles;
- try {
- changedFiles = await runRsync(srcDir, PATHS.data, flags);
- } catch (err) {
- if (!dryRun) {
- const partialRestoreError = new Error(
- `${err.message}. Some files may already have been overwritten because file restore is not transactional.`,
- { cause: err },
- );
- if (err?.code) partialRestoreError.code = err.code;
- throw partialRestoreError;
- }
- throw err;
+ // Rsync may overwrite live files before reporting failure. Settle the
+ // transfer so every live attempt reaches reconciliation before it rejects.
+ const [transfer] = await Promise.allSettled([runRsync(srcDir, PATHS.data, flags)]);
+ const reconciliationError = !dryRun
+ ? await reconcileLiveFileRestore(subdirFilter).then(
+ () => null,
+ error => error,
+ )
+ : null;
+
+ if (transfer.status === 'rejected') {
+ if (dryRun) throw transfer.reason;
+ const partialRestoreError = new Error(
+ `${transfer.reason.message}. Some files may already have been overwritten because file restore is not transactional.${reconciliationError ? ` ${reconciliationError.message}` : ''}`,
+ { cause: transfer.reason },
+ );
+ if (transfer.reason?.code) partialRestoreError.code = transfer.reason.code;
+ throw partialRestoreError;
}
- if (!dryRun) {
- // A live restore writes outside normal service mutation paths. Re-sync the
- // caches whose backing files may have changed instead of serving the
- // pre-restore projection until each record is next mutated or the process
- // restarts. Selective restores may target either `brain` itself or a nested
- // path such as `brain/inbox`.
- if (!subdirFilter || subdirFilter === 'brain' || subdirFilter.startsWith('brain/')) {
- invalidateBrainCaches();
- }
- await reloadSettings();
- }
- return { dryRun, snapshotId, subdirFilter, changedFiles };
+ if (reconciliationError) throw reconciliationError;
+
+ return { dryRun, snapshotId, subdirFilter, changedFiles: transfer.value };
}
/**
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 4931e71b3e..c5293d8d60 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1237,7 +1237,8 @@ describe('restoreSnapshot subdirFilter guard', () => {
proc.emit('close', null, 'SIGTERM');
await expect(pending).rejects.toThrow(/files may already have been overwritten/i);
- expect(reloadSettings).not.toHaveBeenCalled();
+ expect(reloadSettings).toHaveBeenCalledTimes(1);
+ expect(invalidateBrainCaches).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
@@ -1543,7 +1544,20 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
expect(reloadSettings).not.toHaveBeenCalled();
});
- it('does not reload settings when rsync fails a live restore', async () => {
+ it('leaves caches untouched when a dry-run rsync fails', async () => {
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: true });
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ proc.stderr.emit('data', Buffer.from('preview failed'));
+ proc.emit('close', 1);
+
+ await expect(pending).rejects.toThrow(/^rsync exited with code 1/);
+ expect(reloadSettings).not.toHaveBeenCalled();
+ expect(invalidateBrainCaches).not.toHaveBeenCalled();
+ });
+
+ it('reconciles settings and Brain state when rsync fails a live restore', async () => {
const proc = fakeProc();
spawn.mockReturnValue(proc);
const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false });
@@ -1552,7 +1566,28 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
proc.emit('close', 1);
await expect(pending).rejects.toThrow(/rsync exited with code 1.*files may already have been overwritten/i);
- expect(reloadSettings).not.toHaveBeenCalled();
+ expect(reloadSettings).toHaveBeenCalledTimes(1);
+ expect(invalidateBrainCaches).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports reconciliation failures without hiding the primary rsync failure', async () => {
+ invalidateBrainCaches.mockImplementationOnce(() => {
+ throw new Error('Brain cache reset failed');
+ });
+ reloadSettings.mockRejectedValueOnce(new Error('settings reload failed'));
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = restoreSnapshot('/dest', 'snap-1', { dryRun: false });
+ await vi.waitFor(() => expect(spawn).toHaveBeenCalled());
+ proc.stderr.emit('data', Buffer.from('transfer failed'));
+ proc.emit('close', 1);
+
+ await expect(pending).rejects.toMatchObject({
+ message: expect.stringMatching(/rsync exited with code 1.*Live restore cache reconciliation failed.*Brain cache reset failed.*settings reload failed.*Restart PortOS/i),
+ cause: expect.objectContaining({ message: expect.stringMatching(/rsync exited with code 1/) }),
+ });
+ expect(reloadSettings).toHaveBeenCalledTimes(1);
+ expect(invalidateBrainCaches).toHaveBeenCalledTimes(1);
});
});
});