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: fail backups when manifest inventory cannot be read (#7133)

[._.]/ Adam Eivyccf6b054c32d
diff --git a/server/services/backup.js b/server/services/backup.js
index dc103410ef..b272c32c5e 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -456,7 +456,9 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
const pgDumpPath = join(snapshotDir, 'portos-db.sql');
const pgResult = await dumpPostgres(pgDumpPath);
- manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'), pgDumpPath);
+ manifest = await generateManifest(dataDestDir, join(snapshotDir, 'manifest.json'), pgDumpPath, {
+ allowMissingDump: pgResult.status === 'skipped' || pgResult.status === 'failed'
+ });
const status = backupStatusForPg(pgResult);
const lastRun = new Date().toISOString();
@@ -621,6 +623,12 @@ export async function dumpPostgres(outputPath) {
});
}
+// Filesystem messages contain private paths; only expose the operation and errno.
+function manifestReadFailure(operation, err) {
+ const code = /^E[A-Z0-9]+$/.test(err?.code) ? err.code : 'UNKNOWN';
+ return new Error(`Backup manifest ${operation} failed (${code})`);
+}
+
/**
* Generate a SHA-256 manifest for all files in snapshotDataDir, plus the
* sibling pg dump (which lives outside the data/ tree). Hashing the dump means
@@ -628,25 +636,37 @@ export async function dumpPostgres(outputPath) {
* @param {string} snapshotDataDir - Directory to hash
* @param {string} manifestPath - Path to write manifest.json
* @param {string|null} [pgDumpPath=null] - Sibling SQL dump to also hash
+ * @param {object} [options] - Dump inventory expectations
+ * @param {boolean} [options.allowMissingDump=false] - Only for skipped/failed dumps
*/
-export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath = null) {
- const entries = await readdir(snapshotDataDir, { recursive: true }).catch(() => []);
+export async function generateManifest(snapshotDataDir, manifestPath, pgDumpPath = null, { allowMissingDump = false } = {}) {
+ const entries = await readdir(snapshotDataDir, { recursive: true })
+ .catch(err => { throw manifestReadFailure('data readdir', err); });
const files = {};
for (const entry of entries) {
const filePath = join(snapshotDataDir, entry);
- const info = await stat(filePath).catch(() => null);
- if (!info || !info.isFile()) continue;
- files[entry] = await sha256File(filePath);
+ const info = await stat(filePath)
+ .catch(err => { throw manifestReadFailure('data stat', err); });
+ if (!info.isFile()) continue;
+ files[entry] = await sha256File(filePath)
+ .catch(err => { throw manifestReadFailure('data hash', err); });
}
if (pgDumpPath) {
- const dumpInfo = await stat(pgDumpPath).catch(() => null);
+ const dumpInfo = await stat(pgDumpPath).catch(err => {
+ if (allowMissingDump && err.code === 'ENOENT') return null;
+ throw manifestReadFailure('dump stat', err);
+ });
+ if (dumpInfo && !dumpInfo.isFile()) {
+ throw new Error('Backup manifest dump stat failed (not a regular file)');
+ }
if (dumpInfo?.isFile()) {
// Parent-relative key: the dump lives one level ABOVE snapshotDataDir
// (alongside it, not inside it). A future manifest-verify must not assume
// every key resolves under snapshotDataDir.
- files['../portos-db.sql'] = await sha256File(pgDumpPath);
+ files['../portos-db.sql'] = await sha256File(pgDumpPath)
+ .catch(err => { throw manifestReadFailure('dump hash', err); });
}
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 825cd4deef..7009627c86 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1699,6 +1699,112 @@ describe('runBackup lifecycle', () => {
]);
});
+ it.each([
+ ['data readdir', 'EIO'],
+ ['data readdir', 'EACCES'],
+ ['data stat', 'EIO'],
+ ['data stat', 'ENOENT'],
+ ['dump stat', 'EACCES'],
+ ['dump stat', 'EIO'],
+ ])('fails on %s %s and succeeds after repair', async (operation, code) => {
+ const fsp = await actualFs();
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotDir = await findSnapshotDir();
+ const dataDir = joinPath(snapshotDir, 'data');
+ const entryPath = joinPath(dataDir, 'example.json');
+ await fsp.writeFile(entryPath, '{}');
+ const fault = Object.assign(new Error('private filesystem details'), { code });
+ const expected = `Backup manifest ${operation} failed (${code})`;
+ const method = operation === 'data readdir' ? 'readdir' : 'stat';
+ const target = operation === 'data readdir' ? dataDir
+ : operation === 'data stat' ? entryPath : joinPath(snapshotDir, 'portos-db.sql');
+ const spy = vi.spyOn(fs, method).mockImplementation((path, ...args) =>
+ path === target ? Promise.reject(fault) : fsp[method](path, ...args));
+ const rejected = expect(pending).rejects.toThrow(expected);
+ proc.emit('close', 0);
+ await rejected;
+
+ expect(await readJson(joinPath(dataRoot, 'backup', 'state.json')))
+ .toMatchObject({ status: 'error', error: expected });
+ expect(io.emit.mock.calls.filter(([event]) => event === 'backup:completed')).toEqual([]);
+ expect(io.emit).toHaveBeenCalledWith('backup:failed', {
+ snapshotId: basename(snapshotDir), error: expected,
+ });
+ await expect(fsp.access(joinPath(snapshotDir, 'manifest.json'))).rejects.toMatchObject({ code: 'ENOENT' });
+
+ spy.mockRestore();
+ fs.stat.mockImplementation(fsp.stat);
+ spawn.mockClear();
+ const retryProc = fakeProc();
+ spawn.mockReturnValue(retryProc);
+ const retry = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'retry rsync');
+ retryProc.emit('close', 0);
+ await expect(retry).resolves.toMatchObject({ status: 'ok' });
+ expect(await readJson(joinPath(dataRoot, 'backup', 'state.json')))
+ .toMatchObject({ status: 'ok', error: null });
+ });
+
+ it.each([
+ ['skipped', 'file', 'ok'],
+ ['failed', 'postgres', 'degraded'],
+ ])('allows an empty inventory and absent %s dump', async (pgStatus, backend, status) => {
+ process.env.MEMORY_BACKEND = backend;
+ getBackendName.mockReturnValue(null);
+ // Production subscribes to the error bus; EventEmitter otherwise throws
+ // an unhandled 'error' while broadcasting the expected degraded warning.
+ const { errorEvents } = await import('../lib/errorHandler.js');
+ const warning = vi.fn();
+ if (pgStatus === 'failed') errorEvents.once('error', warning);
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ proc.emit('close', 0);
+ await expect(pending).resolves.toMatchObject({
+ status, pgBackup: { status: pgStatus }, manifest: { fileCount: 0, files: {} },
+ });
+ expect(await readJson(joinPath(dataRoot, 'backup', 'state.json')))
+ .toMatchObject({ status, pgBackup: { status: pgStatus } });
+ expect(io.emit).toHaveBeenCalledWith('backup:completed', expect.objectContaining({ status }));
+ if (pgStatus === 'failed') expect(warning).toHaveBeenCalledWith(
+ expect.objectContaining({ code: 'BACKUP_DB_DUMP_FAILED' }), expect.any(Object));
+ });
+
+ it('fails if a successful dump disappears before inventory', async () => {
+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
+ getServerMajorVersion.mockResolvedValue(null);
+ const fsp = await actualFs();
+ const io = { emit: vi.fn() };
+ const rsync = fakeProc();
+ const pg = fakeProc();
+ spawn.mockReturnValueOnce(rsync).mockReturnValueOnce(pg);
+ const pending = runBackup(destRoot, io);
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ const snapshotDir = await findSnapshotDir();
+ const dumpPath = joinPath(snapshotDir, 'portos-db.sql');
+ rsync.emit('close', 0);
+ await waitFor(() => spawn.mock.calls.length === 2, 'pg_dump spawn');
+ await fsp.writeFile(dumpPath, 'CREATE TABLE example (id integer);');
+ // Enumeration starts only after dumpPostgres has verified and returned ok.
+ vi.spyOn(fs, 'readdir').mockImplementation(async (path, ...args) => {
+ if (path === joinPath(snapshotDir, 'data')) await fsp.unlink(dumpPath);
+ return fsp.readdir(path, ...args);
+ });
+ const rejected = expect(pending).rejects.toThrow('Backup manifest dump stat failed (ENOENT)');
+ pg.emit('close', 0);
+ await rejected;
+ expect(await readJson(joinPath(dataRoot, 'backup', 'state.json')))
+ .toMatchObject({ status: 'error' });
+ expect(io.emit.mock.calls.filter(([event]) => event === 'backup:completed')).toEqual([]);
+ await expect(fsp.access(joinPath(snapshotDir, 'manifest.json'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it('returns { skipped: true } for a concurrent call without a second rsync', async () => {
const io = { emit: vi.fn() };
const proc = fakeProc();