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(backup): retain authority on failed Windows video rollback

[._.]/ Adam Eivy00918c90d29d
diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.js
index eb2faecae6..2d38ae47a5 100644
--- a/server/lib/backupSnapshotBoundary.js
+++ b/server/lib/backupSnapshotBoundary.js
@@ -60,12 +60,22 @@ async function waitForLocalCut(deadline) {
});
}
+function retainUncertainPublication(scope, error) {
+ if (error?.backupPublicationUncertain !== true) return;
+ scope.uncertain = true;
+ // Diagnostic decoration is best effort; a frozen error cannot release authority.
+ try {
+ error.backupPublicationOwner = { ...scope.sharedLease.owner, path: scope.sharedLease.path };
+ error.recoveryPath ??= scope.sharedLease.path;
+ } catch { /* The durable owner remains the recovery authority. */ }
+}
+
async function withAdmittedBackupAssetPublication(work, timeoutMs) {
const scope = publicationScope.getStore();
if (scope?.active) {
try { return await work(); }
catch (error) {
- if (error?.backupPublicationUncertain === true) scope.uncertain = true;
+ retainUncertainPublication(scope, error);
throw error;
}
}
@@ -87,7 +97,7 @@ async function withAdmittedBackupAssetPublication(work, timeoutMs) {
try {
return await publicationScope.run(lease, work);
} catch (error) {
- if (error?.backupPublicationUncertain === true) lease.uncertain = true;
+ retainUncertainPublication(lease, error);
throw error;
} finally {
lease.active = false;
diff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.js
index 83172bd4da..025a03d6b9 100644
--- a/server/lib/backupSnapshotBoundary.test.js
+++ b/server/lib/backupSnapshotBoundary.test.js
@@ -86,6 +86,7 @@ describe('backup snapshot publication admission', () => {
}
const owners = backupPublicationAdmissionStatus().publications;
expect(owners).toEqual([expect.objectContaining({ kind: 'publication', uncertain: true })]);
+ expect(error).toMatchObject({ recoveryPath: owners[0].path, backupPublicationOwner: { id: owners[0].id, path: owners[0].path } });
await expect(acquireBackupSnapshotCut({ timeoutMs: 10 })).rejects.toMatchObject({
code: 'BACKUP_SNAPSHOT_BUSY', blockers: [expect.objectContaining({ id: owners[0].id, uncertain: true })],
});
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 394f6a212a..49d2ac4b42 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -582,8 +582,9 @@ const appendFilter = (chain, filter) => {
// Windows, fs.rename fails when the destination already exists — but a simple
// unlink-first would destroy the original if the subsequent rename failed
// (locked file, AV scan, transient permissions). Move the original aside to a
-// .bak first, install the new file, and restore the backup on any failure, so
-// the worst case is "the operation was skipped", never "the video is gone".
+// .bak first, install the new file, and restore the backup on failure. If the
+// restore itself fails, retain that original and signal uncertain publication
+// state so backup admission cannot accept the temporarily missing target.
//
// Extracted because three callers here (`trimVideoFromFrame`, `upscaleVideo2x`,
// `optimizeForStreaming`) need this identical rollback, and a data-loss-
@@ -593,22 +594,29 @@ const appendFilter = (chain, filter) => {
// `rename` was exactly the copy that never got fixed (#7237). `label` names
// the operation for the failure message.
//
-// Returns `{ ok: true, outPath }` or `{ ok: false, reason }`.
+// Returns `{ ok: true, outPath }` or `{ ok: false, reason }`. A failed rollback
+// throws explicitly uncertain publication state and retains the original backup.
export const installEncodedVideo = async (tmpPath, targetPath, label) => {
let backupPath = null;
try {
if (IS_WIN) {
- backupPath = `${targetPath}.bak.${randomUUID()}`;
- await rename(targetPath, backupPath).catch((err) => {
- if (err?.code === 'ENOENT') { backupPath = null; return; }
- throw err;
+ const candidate = `${targetPath}.bak.${randomUUID()}`;
+ await rename(targetPath, candidate).then(() => { backupPath = candidate; }).catch((err) => {
+ if (err?.code !== 'ENOENT') throw err;
});
}
await rename(tmpPath, targetPath);
if (backupPath) await unlink(backupPath).catch(() => {});
return { ok: true, outPath: targetPath };
} catch (err) {
- if (backupPath) await rename(backupPath, targetPath).catch(() => {});
+ if (backupPath) {
+ try { await rename(backupPath, targetPath); }
+ catch (rollbackError) {
+ throw Object.assign(new AggregateError([err, rollbackError], `Failed to restore ${label} video; original retained at ${backupPath}`), {
+ backupPublicationUncertain: true, recoveryPath: backupPath,
+ });
+ }
+ }
await unlink(tmpPath).catch(() => {});
return { ok: false, reason: `Failed to install ${label} video: ${err.message}` };
}
diff --git a/server/lib/ffmpeg.rollback.test.js b/server/lib/ffmpeg.rollback.test.js
new file mode 100644
index 0000000000..c8245000c0
--- /dev/null
+++ b/server/lib/ffmpeg.rollback.test.js
@@ -0,0 +1,58 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let failRestore = false;
+let failInitialMove = false;
+vi.mock('fs/promises', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, rename: async (from, to) => {
+ if ((failRestore && from.includes('.bak.')) || (failInitialMove && to.includes('.bak.'))) {
+ throw Object.assign(new Error('synthetic access refusal'), { code: 'EACCES' });
+ }
+ return actual.rename(from, to);
+ } };
+});
+vi.mock('./childProcess.js', () => ({ execFile: vi.fn(), spawn: vi.fn() }));
+vi.mock('./processEnv.js', () => ({ safeChildProcessOptions: () => ({}), whichFirst: vi.fn() }));
+vi.mock('./fileUtils.js', () => ({ ensureDir: vi.fn(), PATHS: {} }));
+// Load the Windows branch on every CI host, then immediately restore the host.
+const descriptor = Object.getOwnPropertyDescriptor(process, 'platform');
+let installEncodedVideo;
+try {
+ Object.defineProperty(process, 'platform', { ...descriptor, value: 'win32' });
+ ({ installEncodedVideo } = await import('./ffmpeg.js'));
+} finally { Object.defineProperty(process, 'platform', descriptor); }
+const { withBackupAssetPublication, acquireBackupSnapshotCut, backupPublicationAdmissionStatus } = await import('./backupSnapshotBoundary.js');
+const root = await mkdtemp(join(tmpdir(), 'portos-ffmpeg-rollback-'));
+const target = join(root, 'video.mp4');
+const missing = join(root, 'missing.mp4');
+beforeEach(async () => {
+ failRestore = false; failInitialMove = false;
+ await writeFile(target, 'original');
+});
+afterAll(() => rm(root, { recursive: true, force: true }));
+
+describe('Windows encoded video rollback admission', () => {
+ it('retains the original and durable owner when install and restore both fail', async () => {
+ failRestore = true;
+ try {
+ await expect(withBackupAssetPublication(() => installEncodedVideo(missing, target, 'mux'))).rejects.toMatchObject({ backupPublicationUncertain: true });
+ const original = (await readdir(root)).find(name => name.includes('.bak.'));
+ expect(await readFile(join(root, original), 'utf8')).toBe('original');
+ await expect(readFile(target)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(acquireBackupSnapshotCut({ timeoutMs: 10 })).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY', blockers: [expect.objectContaining({ uncertain: true })] });
+ } finally {
+ for (const owner of backupPublicationAdmissionStatus().publications) await rm(owner.path, { recursive: true, force: true });
+ }
+ });
+
+ it.each([false, true])('releases admission when original remains coherent (initial move failure=%s)', async initial => {
+ failInitialMove = initial;
+ expect((await withBackupAssetPublication(() => installEncodedVideo(missing, target, 'mux'))).ok).toBe(false);
+ expect(await readFile(target, 'utf8')).toBe('original');
+ const release = await acquireBackupSnapshotCut({ timeoutMs: 10 });
+ release();
+ });
+});