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: coordinate media-job completion with backup snapshot admission (#9981)
Adam Eivy19e199b75a01
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 6c4495dd3b..f8a4a27cf0 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -17,9 +17,34 @@ If an admitted take does not drain within two minutes, or the cut cannot bereleased, the snapshot is marked failed (never published or used for retentionpruning) and take publication reopens.-This is the first slice of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923). Media-job completion, other durable asset-replacement/deletion paths, and database maintenance are tracked as separate-children. Until those owners are covered, `status: ok` reports that the file+**Media-job completion (#9981).** A render's completion holds the same admission+from staging its terminal queue row (`media-jobs.json`) through the `completed`+event fan-out; it is never held while rendering, waiting in the queue, calling a+provider, or for failure and cancellation outcomes. Each attach hook that names+the render's file in a row takes its own admission synchronously inside that+fan-out, so a cut already waiting to drain still waits for it. A completion that+arrives during the cut leaves the job `running` in the queue snapshot (the+finished file is an unreferenced extra, never a dangling reference) and+publishes once the cut releases; the lane stays occupied meanwhile, but the+renderer is not stopped and cancellation is unchanged. A terminal write that+fails inside the admission is retried inside it and releases it when it gives+up.++Admission inventory (`withBackupAssetPublication`):++| Owner | Status |+| --- | --- |+| Music Designer take publication (`musicTakePublication.js`) | Covered (#9980) |+| Media-job completion: queue terminal row + `completed` fan-out (`mediaJobQueue/index.js`) | Covered |+| Attach hooks on `completed` via `mediaJobImageHook.js` (writers-room, catalog, music-video scene image/video/cast-sets, CD scene image/music bed, FableLoom scene image/video, sprite references, deck cards, music studio) | Covered |+| Pipeline filename hooks (`filenameHookFactory.js` comic pages and storyboards, `seasonCoverFilenameHook.js`) | Covered |+| Recovery commit of a completion whose terminal write failed (the next queue write acknowledges it outside any admission) | Outstanding |+| Other `mediaJobEvents` `completed` subscribers that write rows (universe-builder collection hook, LoRA dataset, character sheet, sprite animation, Creative Director scene runner/plan advance/seed settle, music-video production) | Outstanding |+| Durable replacement/deletion owners | Outstanding (#9982) |+| Database maintenance | Outstanding (#9983) |++This is part of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923).+Until every owner is covered, `status: ok` reports that the filecopy, manifest, and database dump completed; it does not assert that everydatabase asset reference resolves to the captured filesystem bytes. A restoreoperator should verify affected assets before treating a snapshot as a completediff --git a/server/lib/README.md b/server/lib/README.mdindex fbc28ef921..99ba209ceb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -621,7 +621,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease. |+| `backupSnapshotBoundary.js` | `withBackupAssetPublication(work)` admits a complete durable file-plus-row mutation; `acquireBackupSnapshotCut()` drains admitted work and pauses new publication through backup's file copy, database dump, and manifest. Nested mutation calls reuse their lease; `runOutsideBackupAssetPublication(work)` lets a synchronous event fan-out give each listener its own lease. || `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. || `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. || `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex 2b654a7b08..ab76bcaf8f 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -22,8 +22,11 @@ function releasePublications() {/** Hold one admission across an entire file-plus-row workflow. Nested calls reuse it. */export async function withBackupAssetPublication(work) {- if (publicationScope.getStore()?.active) return work();- while (cutRequested || cutActive) {+ const scope = publicationScope.getStore();+ if (scope?.active) return work();+ // Work spawned by a still-admitted lease joins it: the cut already waits for that lease.+ const joinsAdmitted = scope?.spawnedBy?.active === true;+ while (!joinsAdmitted && (cutRequested || cutActive)) {await new Promise(resolve => publicationWaiters.push(resolve));}admitted += 1;@@ -41,6 +44,19 @@ export async function withBackupAssetPublication(work) {}}+/**+ * Run a synchronous fan-out (an event emit) so each listener acquires its OWN+ * lease while the caller's lease is still held, even if a cut is already+ * waiting to drain. A listener reusing the caller's lease would continue+ * unadmitted once the caller finished and could land mid-cut; one queued behind+ * the cut would leave the caller's publication half drained. Listeners must+ * call withBackupAssetPublication before their first await, and the caller must+ * not await them.+ */+export function runOutsideBackupAssetPublication(work) {+ return publicationScope.run({ active: false, spawnedBy: publicationScope.getStore() }, work);+}+/*** Close admission and drain already admitted workflows before copying files.* The returned release function owns only this cut. A timed-out drain reopensdiff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.jsindex a2469bdabf..e08539d93e 100644--- a/server/lib/backupSnapshotBoundary.test.js+++ b/server/lib/backupSnapshotBoundary.test.js@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { acquireBackupSnapshotCut, withBackupAssetPublication } from './backupSnapshotBoundary.js';+import { acquireBackupSnapshotCut, runOutsideBackupAssetPublication, withBackupAssetPublication } from './backupSnapshotBoundary.js';const deferred = () => {let resolve;@@ -72,4 +72,33 @@ describe('backup snapshot publication admission', () => {rowWrite.resolve();await first;});++ it('lets a listener spawned by an admitted workflow join it only while that workflow holds its lease', async () => {+ const listenerWrite = deferred();+ let listener;+ let later;+ const emitter = withBackupAssetPublication(async () => {+ runOutsideBackupAssetPublication(() => {+ listener = withBackupAssetPublication(async () => listenerWrite.promise);+ later = new Promise(resolve => setImmediate(resolve)).then(() => withBackupAssetPublication(() => 'late'));+ });+ });+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => {+ cutReady = true;+ return release;+ });+ await emitter;+ await new Promise(resolve => setImmediate(resolve));+ expect(cutReady).toBe(false); // the cut also waits for the spawned listener+ listenerWrite.resolve();+ await listener;+ const release = await cut;+ let lateRan = false;+ later.then(() => { lateRan = true; });+ await new Promise(resolve => setImmediate(resolve));+ expect(lateRan).toBe(false); // admitted after the spawner finished: waits behind the cut+ release();+ expect(await later).toBe('late');+ });});diff --git a/server/services/mediaJobImageHook.js b/server/services/mediaJobImageHook.jsindex 1ac397b36e..f36c3900cb 100644--- a/server/services/mediaJobImageHook.js+++ b/server/services/mediaJobImageHook.js@@ -59,6 +59,7 @@*/import { mediaJobEvents } from './mediaJobQueue/index.js';+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';import { createNewestWinsGuard } from '../lib/createNewestWinsGuard.js';@@ -135,7 +136,9 @@ export function createMediaJobImageHook(config) {if (completedHandler) return;completedHandler = (job) => {- void (async () => {+ // Admitted synchronously (before any await) so the attach — a durable+ // row write that points at the render's file — is never split by a backup cut.+ void withBackupAssetPublication(async () => {const ctx = decode(job);if (!ctx) return;const sKey = sceneKey ? sceneKey(ctx) : null;@@ -162,7 +165,7 @@ export function createMediaJobImageHook(config) {});if (result != null) onAttached(ctx, result);- })().catch((err) => {+ }).catch((err) => {// Last-resort net for synchronous throws (unexpected job shape, etc).console.log(`⚠️ ${label} hook crashed: ${err?.message || err}`);});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex f1e6be966a..b174f5a13e 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -33,6 +33,7 @@ import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';import { PATHS, readJSONFileStrict, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';import { SSE_HEADERS } from '../../lib/sseHeaders.js';+import { runOutsideBackupAssetPublication, withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';import {@@ -1149,6 +1150,15 @@ async function runJobLifecycle(job, markDispatched) {emitter.off?.('activity', onActivity);emitter.off?.('progress', onActivity);await drainProgressPersist();+ // Only a completion publishes durable output. It holds backup admission from+ // staging the terminal row through the hook fan-out, never while rendering+ // or waiting in the queue; failures and cancellations stay unadmitted so a+ // backup never delays them.+ const publish = () => publishTerminalTransition(state, apply);+ await (state === 'completed' ? withBackupAssetPublication(publish) : publish());+ }++ async function publishTerminalTransition(state, apply) {stageTerminalTransition(job, (job) => {apply(job);job.status = state;@@ -1180,7 +1190,9 @@ async function runJobLifecycle(job, markDispatched) {: { type: 'error', error: job.error };broadcastSse(sseEntry, ssePayload);closeJobAfterDelay(sseJobs, job.id);- mediaJobEvents.emit(state, job);+ // Hooks that publish files or rows acquire their own admission; see+ // runOutsideBackupAssetPublication.+ runOutsideBackupAssetPublication(() => mediaJobEvents.emit(state, job));});await persistTerminalTransition(job);}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 7375423a8e..2fd0e395a7 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -1,7 +1,7 @@vi.mock('../musicVideo/projects.js', () => ({ getProject: vi.fn(async () => ({ mediaMode: 'code-images-video' })) }));vi.mock('../musicVideo/productionReviewService.js', () => ({ assertMusicVideoSceneReview: vi.fn(async () => {}) }));import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';-import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';@@ -2959,3 +2959,129 @@ describe('durable execution and terminal settlement', () => {expect(stubs.generateVideo).toHaveBeenCalledTimes(1);});});++// A completion publishes a file (written by the generator before it reports+// done) and rows (the queue snapshot and the attach hooks that name the file).+// A backup cut must never capture one store without the other (#9981).+describe('backup snapshot admission for media completion', () => {+ let boundary;+ let rows;+ let hookGate;+ let hookStarted;+ let storageWrite;+ const onCompleted = (job) => {+ void boundary.withBackupAssetPublication(async () => {+ hookStarted = true;+ await hookGate;+ rows.set(job.id, job.result.filename);+ });+ };+ // What a backup would hold: the files copied, the queue snapshot and attached rows.+ const capture = (jobId) => ({+ files: existsSync(join(tempDataDir, 'videos')) ? readdirSync(join(tempDataDir, 'videos')) : [],+ queueStatus: persistedJobs().find((j) => j.id === jobId)?.status,+ rows: new Map(rows),+ });+ const startJob = async () => {+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'synthetic' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ return jobId;+ };+ const renderFinishes = (jobId) => {+ mkdirSync(join(tempDataDir, 'videos'), { recursive: true });+ writeFileSync(join(tempDataDir, 'videos', `${jobId}.mp4`), 'synthetic clip');+ videoGenEvents.emit('completed', { generationId: jobId, filename: `${jobId}.mp4` });+ };+ const failTerminalWrites = (times) => {+ const failures = { remaining: times, count: 0 };+ atomicWriteSpy.mockImplementation(async (path, data) => {+ if (failures.remaining > 0 && data?.jobs?.some((j) => j.status === 'completed')) {+ failures.remaining -= 1;+ failures.count += 1;+ throw new Error('disk full');+ }+ return storageWrite(path, data);+ });+ return failures;+ };+ const settle = () => new Promise((resolve) => setImmediate(resolve));++ beforeEach(async () => {+ boundary = await import('../../lib/backupSnapshotBoundary.js');+ rows = new Map();+ hookStarted = false;+ hookGate = Promise.resolve();+ storageWrite = atomicWriteSpy.getMockImplementation();+ stubs.generateVideo.mockImplementation(async () => ({}));+ mediaJobQueue.mediaJobEvents.on('completed', onCompleted);+ });+ afterEach(() => {+ mediaJobQueue.mediaJobEvents.off('completed', onCompleted);+ atomicWriteSpy.mockImplementation(storageWrite);+ });++ it('holds a completion that arrives during the cut away from both stores until it reopens', async () => {+ const jobId = await startJob();+ const release = await boundary.acquireBackupSnapshotCut();+ renderFinishes(jobId);+ // Unadmitted, the completion persists within a few milliseconds of real file I/O.+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(mediaJobQueue.getJob(jobId).status).toBe('running');+ expect(capture(jobId)).toEqual({ files: [`${jobId}.mp4`], queueStatus: 'running', rows: new Map() });+ release();+ await waitFor(() => mediaJobQueue.getJob(jobId).status === 'completed');+ await waitFor(() => rows.has(jobId));+ expect(capture(jobId)).toEqual({ files: [`${jobId}.mp4`], queueStatus: 'completed', rows: new Map([[jobId, `${jobId}.mp4`]]) });+ });++ it('drains a completion already publishing its queue row and hook rows before the cut', async () => {+ let finishWrite;+ const writeGate = new Promise((resolve) => { finishWrite = resolve; });+ let finishHook;+ hookGate = new Promise((resolve) => { finishHook = resolve; });+ let writeHeld = false;+ atomicWriteSpy.mockImplementation(async (path, data) => {+ if (data?.jobs?.some((j) => j.status === 'completed')) {+ writeHeld = true;+ await writeGate;+ }+ return storageWrite(path, data);+ });+ const jobId = await startJob();+ renderFinishes(jobId);+ await waitFor(() => writeHeld);+ let cutReady = false;+ const cut = boundary.acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });+ await settle();+ expect(cutReady).toBe(false);+ finishWrite();+ await waitFor(() => hookStarted);+ await settle();+ expect(cutReady).toBe(false);+ finishHook();+ const release = await cut;+ expect(capture(jobId)).toEqual({ files: [`${jobId}.mp4`], queueStatus: 'completed', rows: new Map([[jobId, `${jobId}.mp4`]]) });+ release();+ });++ it('retries a failed terminal write inside the same admission and releases it after final failure', async () => {+ const retried = await startJob();+ failTerminalWrites(1);+ renderFinishes(retried);+ await waitFor(() => rows.has(retried));+ expect(capture(retried).queueStatus).toBe('completed');+ (await boundary.acquireBackupSnapshotCut())();+ });++ it('releases admission after a terminal write fails for good, leaving no half-published outcome', async () => {+ const failed = await startJob();+ const failures = failTerminalWrites(3);+ renderFinishes(failed);+ await waitFor(() => failures.count === 3);+ await settle();+ // The abandoned publication holds nothing: a cut opens at once and sees no half-written outcome.+ const release = await boundary.acquireBackupSnapshotCut({ timeoutMs: 50 });+ expect(capture(failed)).toEqual({ files: [`${failed}.mp4`], queueStatus: 'running', rows: new Map() });+ release();+ });+});diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.jsindex 0e2a993b1a..769eda8da9 100644--- a/server/services/pipeline/filenameHookFactory.js+++ b/server/services/pipeline/filenameHookFactory.js@@ -31,6 +31,7 @@* test's still-running write (#9634).*/+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { mediaJobEvents } from '../mediaJobQueue/index.js';import { updateStageWithLatest } from './issues.js';@@ -60,7 +61,8 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,const runs = createHookRunTracker();const handler = (job) => {- void runs.track((async () => {+ // Admitted synchronously so the stage-row stamp is never split by a backup cut.+ void runs.track(withBackupAssetPublication(async () => {if (!job || job.kind !== kind) return;const filename = job.result?.filename;if (typeof filename !== 'string' || !filename) return;@@ -96,7 +98,7 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,});}}- })().catch((err) => {+ }).catch((err) => {console.error(`❌ ${name} filename hook crashed: ${err?.message || err}`);}));};diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsindex 25166e65c6..cf2792da09 100644--- a/server/services/pipeline/seasonCoverFilenameHook.js+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -18,6 +18,7 @@* stamps `filename` only when the jobId is still ours.*/+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { mediaJobEvents } from '../mediaJobQueue/index.js';import { parseSeasonCoverOwner, slotKeyForVariant } from './owners.js';import * as seriesSvc from './series.js';@@ -31,7 +32,8 @@ let registeredHandler = null;const runs = createHookRunTracker();const handler = (job) => {- void runs.track((async () => {+ // Admitted synchronously so the stamp and cover filing are never split by a backup cut.+ void runs.track(withBackupAssetPublication(async () => {if (!job || job.kind !== 'image') return;const filename = job.result?.filename;if (typeof filename !== 'string' || !filename) return;@@ -74,7 +76,7 @@ const handler = (job) => {// cover never becomes the thumbnail, so skip the recompute for it.if (target === 'cover') await refreshSeriesCoverImage(seriesId);}- })().catch((err) => {+ }).catch((err) => {console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);}));};