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(backup): retain blockers after uncertain publication rollback
[._.]/ Adam Eivy738fd1e752b9
diff --git a/docs/BACKUP_PUBLICATION_ADMISSION.md b/docs/BACKUP_PUBLICATION_ADMISSION.mdindex 8bae6524ff..70be1c7061 100644--- a/docs/BACKUP_PUBLICATION_ADMISSION.md+++ b/docs/BACKUP_PUBLICATION_ADMISSION.md@@ -20,6 +20,12 @@ and deleting leases repeatedly during a long snapshot. Directory creation andremoval work on Windows and POSIX; ownership files are fsynced, with directoryfsync on POSIX (Windows does not support opening a directory that way).+If a publication cannot restore its previous pair, throw an error with+`backupPublicationUncertain: true`. The boundary settles its local callback count+but retains the durable owner with an uncertainty marker. Even a nested failure+caught by its caller retains this blocker; ordinary errors after successful+rollback release admission normally. The next snapshot refuses until recovery.+Every owner has a random ID, process generation, PID, kind, and timestamp. Onlythe matching owner may release its directory. Neither elapsed time nor a missingPID permits automatic removal: a dead publication may have left an incompletediff --git a/server/lib/backupSharedAdmission.js b/server/lib/backupSharedAdmission.jsindex a550537cda..cb2f72d630 100644--- a/server/lib/backupSharedAdmission.js+++ b/server/lib/backupSharedAdmission.js@@ -46,7 +46,7 @@ export function createBackupSharedAdmission(directory, { io = fs, makeId = randoconst owner = JSON.parse(io.readFileSync(join(path, 'owner.json'), 'utf8'));if (owner.version !== 1 || typeof owner.id !== 'string' || typeof owner.generation !== 'string'|| !Number.isInteger(owner.pid) || !['publication', 'snapshot'].includes(owner.kind)) throw new Error('Invalid ownership record');- return { ...owner, path };+ return { ...owner, path, ...(exists(join(path, 'uncertain')) ? { uncertain: true } : {}) };} catch { return { path, unreadable: true }; }};const writeOwner = (path, kind) => {@@ -60,6 +60,13 @@ export function createBackupSharedAdmission(directory, { io = fs, makeId = randoreturn {owner, path,get active() { return active; },+ markUncertain() {+ const marker = join(path, 'uncertain');+ const fd = io.openSync(marker, 'wx', 0o600);+ try { io.writeFileSync(fd, 'Publication rollback failed; reconcile both stores before retiring this owner.\n'); io.fsyncSync(fd); }+ finally { io.closeSync(fd); }+ syncDir(path);+ },release() {if (!active) return;if (describe(path).id !== owner.id) throw busy(`Backup admission ownership changed at ${path}; reconcile the recorded owner before retrying.`, { recoveryPath: path });diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex acea16cf18..eb2faecae6 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -62,7 +62,13 @@ async function waitForLocalCut(deadline) {async function withAdmittedBackupAssetPublication(work, timeoutMs) {const scope = publicationScope.getStore();- if (scope?.active) return work();+ if (scope?.active) {+ try { return await work(); }+ catch (error) {+ if (error?.backupPublicationUncertain === true) scope.uncertain = true;+ throw error;+ }+ }if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new TypeError('Publication timeoutMs must be a non-negative finite number');const deadline = Date.now() + timeoutMs;// Work spawned by a still-admitted lease joins it: the cut already waits for that lease.@@ -80,14 +86,27 @@ async function withAdmittedBackupAssetPublication(work, timeoutMs) {const lease = { active: true, sharedLease };try {return await publicationScope.run(lease, work);+ } catch (error) {+ if (error?.backupPublicationUncertain === true) lease.uncertain = true;+ throw error;} finally {lease.active = false;- sharedLease.release();- admitted -= 1;- if (admitted === 0) {- const waiters = drainWaiters;- drainWaiters = [];- for (const resolve of waiters) resolve();+ try {+ if (lease.uncertain) {+ // The owner was already durable before work started. A diagnostic+ // marker failure must never release that existing recovery blocker.+ try { sharedLease.markUncertain(); }+ catch (error) { console.error(`❌ Backup publication recovery marker failed at ${sharedLease.path}: ${error.message}`); }+ } else sharedLease.release();+ } finally {+ // Settled local callbacks no longer count as running. The retained+ // shared owner supplies concrete diagnostics to the next refused cut.+ admitted -= 1;+ if (admitted === 0) {+ const waiters = drainWaiters;+ drainWaiters = [];+ for (const resolve of waiters) resolve();+ }}}}diff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.jsindex 745afc3612..83172bd4da 100644--- a/server/lib/backupSnapshotBoundary.test.js+++ b/server/lib/backupSnapshotBoundary.test.js@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { acquireBackupSnapshotCut, runOutsideBackupAssetPublication, withBackupAssetPublication } from './backupSnapshotBoundary.js';+import { rmSync } from 'node:fs';+import { backupPublicationAdmissionStatus, acquireBackupSnapshotCut, runOutsideBackupAssetPublication, withBackupAssetPublication } from './backupSnapshotBoundary.js';const deferred = () => {let resolve;@@ -73,6 +74,32 @@ describe('backup snapshot publication admission', () => {await first;});+ it.each([false, true])('retains explicit rollback uncertainty after local callbacks settle (caught nested=%s)', async nested => {+ const error = Object.assign(new Error('rollback incomplete'), { backupPublicationUncertain: true });+ try {+ if (nested) {+ await withBackupAssetPublication(async () => {+ await withBackupAssetPublication(async () => { throw error; }).catch(() => {});+ });+ } else {+ await expect(withBackupAssetPublication(async () => { throw error; })).rejects.toBe(error);+ }+ const owners = backupPublicationAdmissionStatus().publications;+ expect(owners).toEqual([expect.objectContaining({ kind: 'publication', uncertain: true })]);+ await expect(acquireBackupSnapshotCut({ timeoutMs: 10 })).rejects.toMatchObject({+ code: 'BACKUP_SNAPSHOT_BUSY', blockers: [expect.objectContaining({ id: owners[0].id, uncertain: true })],+ });+ // Successful rollback failures do not leave another recovery owner.+ await expect(withBackupAssetPublication(async () => { throw new Error('rolled back'); })).rejects.toThrow('rolled back');+ expect(backupPublicationAdmissionStatus().publications).toHaveLength(1);+ } finally {+ // Explicit fixture teardown, never a production stale-owner recovery.+ for (const owner of backupPublicationAdmissionStatus().publications) rmSync(owner.path, { recursive: true });+ }+ const release = await acquireBackupSnapshotCut();+ release();+ });+it('bounds a local publication wait without releasing the cut or leaving a queued callback', async () => {vi.useFakeTimers();const release = await acquireBackupSnapshotCut();diff --git a/server/services/imageGen/publication.js b/server/services/imageGen/publication.jsindex a8786afce6..a2cc3dd9ab 100644--- a/server/services/imageGen/publication.js+++ b/server/services/imageGen/publication.js@@ -15,12 +15,12 @@ export function publishImageFiles(paths, work) {try {return await work();} catch (error) {- // Wait for every rollback before releasing admission, including a failed one.+ // Settle every rollback; a failed rollback retains the durable admission owner.const restored = await Promise.allSettled(paths.map((path, i) => previous[i] === null? unlinkGuarded(path).catch(err => { if (err.code !== 'ENOENT') throw err; }): atomicWrite(path, previous[i])));const failures = restored.filter(result => result.status === 'rejected').map(result => result.reason);- if (failures.length) throw new AggregateError([error, ...failures], 'Image publication and rollback failed');+ if (failures.length) throw Object.assign(new AggregateError([error, ...failures], 'Image publication and rollback failed'), { backupPublicationUncertain: true });throw error;}}));diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex b54038f7d7..3e603e5a87 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -74,6 +74,7 @@ const executor = createRemoteMediaExecutor({// files until the history commit succeeds, and restore them on failure.const scratch = await mkdtemp(join(tmpdir(), 'portos-video-replay-'));const originals = [];+ let retainScratch = false;try {for (const [index, target] of [path, join(PATHS.videoThumbnails, `${jobId}.jpg`)].entries()) {const backup = join(scratch, String(index));@@ -86,13 +87,20 @@ const executor = createRemoteMediaExecutor({}}try { return await work(); } catch (error) {- for (const { target, backup } of originals) {+ const restored = await Promise.allSettled(originals.map(async ({ target, backup }) => {if (backup) await copyFile(backup, target);else await unlink(target).catch(error => { if (error.code !== 'ENOENT') throw error; });+ }));+ const failures = restored.filter(result => result.status === 'rejected').map(result => result.reason);+ if (failures.length) {+ retainScratch = true;+ throw Object.assign(new AggregateError([error, ...failures], `Video publication rollback failed; originals retained at ${scratch}`), {+ backupPublicationUncertain: true, recoveryPath: scratch,+ });}throw error;}- } finally { await rm(scratch, { recursive: true, force: true }); }+ } finally { if (!retainScratch) await rm(scratch, { recursive: true, force: true }); }}),async finalize({ jobId, path, filename, request, remoteJob, peerId, renderStartedAtMs }) {// Both ffmpeg passes are best-effort by construction (they no-op whendiff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.jsindex 71269c4f59..1bd49c7658 100644--- a/server/services/videoGen/remote.test.js+++ b/server/services/videoGen/remote.test.js@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createHash } from 'node:crypto';import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';-import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';+import { cp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -438,6 +438,35 @@ describe('federated video replacement backup cut', () => {} finally { gate.finish.resolve(); }});+ it('retains originals and a durable blocker when restoring the previous video fails', async () => {+ const { acquireBackupSnapshotCut, backupPublicationAdmissionStatus } = await import('../../lib/backupSnapshotBoundary.js');+ await prepare();+ ffmpeg.faststart.mockImplementationOnce(async () => {+ // Force a real restore-copy error after replacement installed, while the+ // poster restore remains possible and must still be attempted.+ await rm(video());+ await mkdir(video());+ throw new Error('finalizer failed');+ });+ const terminal = captureTerminal(LOCAL_JOB_ID);+ let scratch;+ try {+ await generateVideo(params());+ const outcome = await terminal;+ expect(outcome.type).toBe('failed');+ scratch = outcome.event.error.split('originals retained at ')[1];+ expect(scratch).toContain('portos-video-replay-');+ expect(await readFile(join(scratch, '0'), 'utf8')).toBe('original video');+ expect(await readFile(poster(), 'utf8')).toBe('original poster');+ await expect(acquireBackupSnapshotCut({ timeoutMs: 10 })).rejects.toMatchObject({+ code: 'BACKUP_SNAPSHOT_BUSY', blockers: [expect.objectContaining({ uncertain: true })],+ });+ } finally {+ for (const owner of backupPublicationAdmissionStatus().publications) rmSync(owner.path, { recursive: true });+ if (scratch) await rm(scratch, { recursive: true, force: true });+ }+ });+it('replays a matching completed result without duplicate history or another transfer', async () => {await prepare();await generateVideo(params());