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: keep gallery mutations outside backup snapshots (#9982)

[._.]/ Adam Eivy51e0e8f4621b
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 5ceb8e750b..1bc6bd2704 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -62,9 +62,31 @@ Admission inventory (`withBackupAssetPublication`):
| 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) |
+| Direct gallery upload, image prompt/visibility sidecar replacement, and image deletion (`imageGen/local.js`) | Covered as one file/sidecar/index workflow (#9982 partial) |
+| Video-history deletion, including downloaded-video deletion (`videoGen/historyOps.js`) | Covered through file/history/index removal (#9982 partial) |
+| Other durable replacement/deletion owners and final global readiness/invariant check | Outstanding (#9982) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
+Direct gallery uploads encode before admission, then publish the final image,
+sidecar, and derived index row under one lease. Prompt/visibility edits and
+image/video deletions take admission before their first read or removal and
+hold it through the index update. A snapshot requested halfway through one of
+these workflows drains it; a mutation arriving during a snapshot waits until the
+file copy, SQL dump, and manifest are done. These leases do not make the two
+stores transactional: existing best-effort index failures can still leave
+stale derived rows for reconciliation, and a delete can leave other records
+that referenced the asset. The admission timeout/failure path still refuses the
+snapshot and preserves older recovery points.
+
+The remaining inventory includes LoRA dataset image writes/removals
+(`loraDatasets.js`), voice-profile asset copies (`voice/studio.js`), development
+artifact/vocal-stem import workflows (`musicVideo/devArtifactService.js`,
+`musicVideo/vocalStem.js`), direct render/index completion listeners, and the
+other completion paths above. Their persistence adapters and direct filesystem
+calls need workflow-level classification; independently locking `fileCore` or
+SQL primitives would not cover the gap between writes. No domain is newly
+excluded by this slice, and the final global readiness check is still pending.
+
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 file
copy, manifest, and database dump completed; it does not assert that every
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 0e72a4128c..7b09c82b1e 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -22,6 +22,7 @@ import { randomUUID } from 'crypto';
import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveImageInputPath, tryReadFile, rmGuarded, unlinkGuarded } from '../../lib/fileUtils.js';
import { extractPngGenerationMetadata, extractPngGenerationMetadataFile } from '../../lib/pngMetadata.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -1258,19 +1259,22 @@ export async function saveUploadedGalleryImage(base64Data, tempPath) {
const staging = `${output}.tmp`;
try {
await sharp(input, { limitInputPixels: MAX_GALLERY_UPLOAD_PIXELS }).rotate().png().toFile(staging);
- await rename(staging, output);
+ // Encoding stays outside admission. Publish the final file, metadata, and
+ // derived database row together so a backup cannot split those writes.
+ return await withBackupAssetPublication(async () => {
+ await rename(staging, output);
+ // PNG normalization strips source text chunks; keep their bounded
+ // projection in the gallery sidecar for listings and later attachments.
+ if (Object.keys(metadata).length > 0) {
+ await atomicWrite(join(PATHS.images, filename.replace('.png', '.metadata.json')), metadata);
+ }
+ await refreshImageIndex(filename);
+ console.log(`📥 Saved uploaded gallery image: ${filename} (PNG from ${detected.mime})`);
+ return { filename, path: `/data/images/${filename}`, metadata };
+ });
} finally {
await unlinkGuarded(staging).catch(() => {});
}
- // The normalized PNG intentionally has no source text chunks. Keep the
- // bounded projection in the canonical gallery sidecar so gallery listings,
- // media indexing, and later catalog attachments can still recover it.
- if (Object.keys(metadata).length > 0) {
- await atomicWrite(join(PATHS.images, filename.replace('.png', '.metadata.json')), metadata);
- }
- await refreshImageIndex(filename);
- console.log(`📥 Saved uploaded gallery image: ${filename} (PNG from ${detected.mime})`);
- return { filename, path: `/data/images/${filename}`, metadata };
}
export async function listGallery() {
@@ -1297,37 +1301,39 @@ export async function listGallery() {
export async function deleteImage(filename) {
assertGalleryFilename(filename);
- await unlinkGuarded(join(PATHS.imageThumbnails, filename.replace(/\.png$/i, '.webp'))).catch(() => {});
- await unlinkGuarded(join(PATHS.images, filename)).catch(() => {});
- await unlinkGuarded(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});
- await unlinkGuarded(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});
- // Drop the derived index row with the file (#2738). Without this the row
- // survives until the next boot reconcile, so anything counting the index
- // (the Character sheet's Auteur skill / Media Assets tile) reads high in
- // between. Non-fatal + dynamically imported: a broken index must never fail
- // the user's delete, and this keeps the pg stack out of this module's static
- // graph (the mirror of how the index dynamically imports the media stack).
- //
- // Gated on the PNG being CONFIRMED gone. The unlink above swallows its error,
- // so an EACCES/EBUSY/EIO failure leaves the image on disk and still listed by
- // listGallery() — unindexing it there would swap this bug for its mirror and
- // UNDERcount a live image. Failed-to-delete is not deleted.
- //
- // The probe is tri-state, NOT existsSync: that collapses "absent" and "I
- // couldn't tell" (EACCES on the dir, EIO) into the same `false`, which is the
- // absent-vs-failed sentinel trap — an unreadable gallery would read as "every
- // image is gone" and retire live rows. Only a definitive ENOENT retires the
- // row; present-or-unknown leaves it for the reconcile, which reads disk.
- const probeErr = await stat(join(PATHS.images, filename)).then(() => null, (err) => err);
- if (probeErr?.code === 'ENOENT') {
- await import('../mediaAssetIndex/index.js')
- .then((m) => m.unindexImage(filename))
- .catch((err) => console.error(`❌ Media index image delete hook: ${err.message}`));
- } else {
- console.error(`❌ Image file not confirmed gone (${probeErr?.code || 'still present'}), keeping its index row: ${filename}`);
- }
- console.log(`🗑️ Deleted image: ${filename}`);
- return { ok: true };
+ return withBackupAssetPublication(async () => {
+ await unlinkGuarded(join(PATHS.imageThumbnails, filename.replace(/\.png$/i, '.webp'))).catch(() => {});
+ await unlinkGuarded(join(PATHS.images, filename)).catch(() => {});
+ await unlinkGuarded(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});
+ await unlinkGuarded(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});
+ // Drop the derived index row with the file (#2738). Without this the row
+ // survives until the next boot reconcile, so anything counting the index
+ // (the Character sheet's Auteur skill / Media Assets tile) reads high in
+ // between. Non-fatal + dynamically imported: a broken index must never fail
+ // the user's delete, and this keeps the pg stack out of this module's static
+ // graph (the mirror of how the index dynamically imports the media stack).
+ //
+ // Gated on the PNG being CONFIRMED gone. The unlink above swallows its error,
+ // so an EACCES/EBUSY/EIO failure leaves the image on disk and still listed by
+ // listGallery() — unindexing it there would swap this bug for its mirror and
+ // UNDERcount a live image. Failed-to-delete is not deleted.
+ //
+ // The probe is tri-state, NOT existsSync: that collapses "absent" and "I
+ // couldn't tell" (EACCES on the dir, EIO) into the same `false`, which is the
+ // absent-vs-failed sentinel trap — an unreadable gallery would read as "every
+ // image is gone" and retire live rows. Only a definitive ENOENT retires the
+ // row; present-or-unknown leaves it for the reconcile, which reads disk.
+ const probeErr = await stat(join(PATHS.images, filename)).then(() => null, (err) => err);
+ if (probeErr?.code === 'ENOENT') {
+ await import('../mediaAssetIndex/index.js')
+ .then((m) => m.unindexImage(filename))
+ .catch((err) => console.error(`❌ Media index image delete hook: ${err.message}`));
+ } else {
+ console.error(`❌ Image file not confirmed gone (${probeErr?.code || 'still present'}), keeping its index row: ${filename}`);
+ }
+ console.log(`🗑️ Deleted image: ${filename}`);
+ return { ok: true };
+ });
}
// Sidecar edits are whole-file read→modify→replace cycles; atomicWrite stops a
@@ -1337,13 +1343,15 @@ export async function deleteImage(filename) {
const sidecarEditQueue = createKeyCachedQueue();
function editImageSidecar(filename, mutate) {
- return sidecarEditQueue(filename, async () => {
+ // Admit before joining the queue so a cut drains every already-requested
+ // edit, including one waiting for an earlier edit's index refresh.
+ return withBackupAssetPublication(() => sidecarEditQueue(filename, async () => {
const { path: sidecarPath, metadata } = await readImageSidecar(filename);
const result = mutate(metadata);
await atomicWrite(sidecarPath, metadata);
await refreshImageIndex(filename);
return result;
- });
+ }));
}
export async function setImageHidden(filename, hidden) {
diff --git a/server/services/mediaAssetMutationAdmission.test.js b/server/services/mediaAssetMutationAdmission.test.js
new file mode 100644
index 0000000000..ad91783e48
--- /dev/null
+++ b/server/services/mediaAssetMutationAdmission.test.js
@@ -0,0 +1,185 @@
+/** Real gallery/history workflows and files, with the derived PG index held at
+ * its commit seam. A cut must never enter after bytes change but before rows do. */
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import sharp from 'sharp';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+vi.mock('../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-asset-mutation-'),
+}));
+
+const rows = new Map();
+let beforeIndexWrite = async () => {};
+vi.mock('./mediaAssetIndex/index.js', () => ({
+ indexImage: async ({ filename }) => {
+ await beforeIndexWrite();
+ const metadata = await readFile(join(PATHS.images, filename.replace('.png', '.metadata.json')), 'utf8')
+ .then(JSON.parse, error => { if (error.code === 'ENOENT') return {}; throw error; });
+ rows.set(filename, { filename, ...metadata });
+ },
+ unindexImage: async filename => { await beforeIndexWrite(); rows.delete(filename); },
+ unindexVideo: async id => { await beforeIndexWrite(); rows.delete(id); },
+}));
+
+const { PATHS } = await import('../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { deleteImage, saveUploadedGalleryImage, setImageHidden, updateImagePrompt } = await import('./imageGen/local.js');
+const { deleteHistoryItem } = await import('./videoGen/historyOps.js');
+const { loadHistory, saveHistory } = await import('./videoGen/history.js');
+const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: 'red' } }).png().toBuffer();
+const imagePath = join(PATHS.images, 'fixture.png');
+const metadataPath = join(PATHS.images, 'fixture.metadata.json');
+const videoPath = join(PATHS.videos, 'fixture.mp4');
+const readMetadata = () => readFile(metadataPath, 'utf8').then(JSON.parse);
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+
+afterAll(cleanupTempDataRoots);
+beforeEach(async () => {
+ rows.clear();
+ beforeIndexWrite = async () => {};
+ await rm(PATHS.data, { recursive: true, force: true });
+ await Promise.all([PATHS.images, PATHS.videos, PATHS.imageThumbnails, PATHS.videoThumbnails]
+ .map(directory => mkdir(directory, { recursive: true })));
+ await writeFile(imagePath, png);
+ await writeFile(metadataPath, JSON.stringify({ prompt: 'before', hidden: false }));
+ await writeFile(videoPath, 'synthetic video');
+ await saveHistory([{ id: 'fixture-video', filename: 'fixture.mp4' }]);
+ rows.set('fixture.png', { filename: 'fixture.png', prompt: 'before', hidden: false });
+ rows.set('fixture-video', { filename: 'fixture.mp4' });
+});
+
+// Each case changes a different durable workflow. Holding its actual row write
+// catches a missing lease OR a lease released after only its filesystem half.
+it.each([
+ {
+ name: 'image prompt replacement',
+ mutate: () => updateImagePrompt('fixture.png', 'after'),
+ changedFiles: async () => expect(await readMetadata()).toMatchObject({ prompt: 'after' }),
+ captured: async () => expect(rows.get('fixture.png').prompt).toBe((await readMetadata()).prompt),
+ },
+ {
+ name: 'image visibility replacement',
+ mutate: () => setImageHidden('fixture.png', true),
+ changedFiles: async () => expect(await readMetadata()).toMatchObject({ hidden: true }),
+ captured: async () => expect(rows.get('fixture.png').hidden).toBe((await readMetadata()).hidden),
+ },
+ {
+ name: 'image deletion',
+ mutate: () => deleteImage('fixture.png'),
+ changedFiles: async () => expect(readFile(imagePath)).rejects.toMatchObject({ code: 'ENOENT' }),
+ captured: async () => expect(rows.has('fixture.png')).toBe(false),
+ },
+ {
+ name: 'video deletion',
+ mutate: () => deleteHistoryItem('fixture-video'),
+ changedFiles: async () => {
+ await expect(readFile(videoPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await loadHistory()).toEqual([]);
+ },
+ captured: async () => expect(rows.has('fixture-video')).toBe(false),
+ },
+ {
+ name: 'gallery upload',
+ mutate: () => saveUploadedGalleryImage(png.toString('base64')),
+ changedFiles: async () => expect((await readdir(PATHS.images)).filter(name => /^upload-.*\.png$/.test(name))).toHaveLength(1),
+ captured: async () => {
+ const uploaded = [...rows.keys()].find(name => name.startsWith('upload-'));
+ expect(uploaded).toBeTruthy();
+ expect(await readFile(join(PATHS.images, uploaded))).toEqual(png);
+ },
+ },
+])('drains the complete $name before admitting a snapshot', async ({ mutate, changedFiles, captured }) => {
+ const rowReached = deferred();
+ const commitRow = deferred();
+ beforeIndexWrite = async () => { rowReached.resolve(); await commitRow.promise; };
+ const mutation = mutate();
+ await rowReached.promise;
+ let acquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => { acquired = true; return release; });
+ try {
+ await changedFiles();
+ // The cut would already resolve if only the filesystem write held a lease.
+ expect(acquired).toBe(false);
+ } finally {
+ commitRow.resolve();
+ await mutation;
+ (await cut)();
+ }
+ await captured();
+});
+
+it('keeps prompt replacement and deletion behind an active cut, preserving the captured image', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const replacement = updateImagePrompt('fixture.png', 'after');
+ const deletion = deleteHistoryItem('fixture-video');
+ try {
+ // This is the file-copy / dump order used by backup. Both reads are real;
+ // the mutation may run only after the pair has been captured.
+ expect(await readMetadata()).toMatchObject({ prompt: 'before' });
+ expect(await readFile(videoPath, 'utf8')).toBe('synthetic video');
+ expect(rows.get('fixture.png').prompt).toBe('before');
+ expect(rows.get('fixture-video')).toEqual({ filename: 'fixture.mp4' });
+ } finally {
+ release();
+ await Promise.all([replacement, deletion]);
+ }
+ expect(await readMetadata()).toMatchObject({ prompt: 'after' });
+ expect(rows.has('fixture-video')).toBe(false);
+});
+
+it('does not keep snapshot admission closed after a history mutation rejects', async () => {
+ await expect(deleteHistoryItem('missing')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ const release = await acquireBackupSnapshotCut();
+ release();
+ expect(await readFile(videoPath, 'utf8')).toBe('synthetic video');
+ expect(await loadHistory()).toEqual([{ id: 'fixture-video', filename: 'fixture.mp4' }]);
+});
+
+it('drains a queued sidecar edit through its index commit before taking the cut', async () => {
+ const firstReached = deferred();
+ const commitFirst = deferred();
+ const secondReached = deferred();
+ const commitSecond = deferred();
+ let writes = 0;
+ beforeIndexWrite = async () => {
+ writes += 1;
+ const reached = writes === 1 ? firstReached : secondReached;
+ const commit = writes === 1 ? commitFirst : commitSecond;
+ reached.resolve();
+ await commit.promise;
+ };
+
+ const prompt = updateImagePrompt('fixture.png', 'after');
+ await firstReached.promise;
+ const visibility = setImageHidden('fixture.png', true);
+ const cut = acquireBackupSnapshotCut();
+ try {
+ expect(await readMetadata()).toEqual({ prompt: 'after', hidden: false });
+ commitFirst.resolve();
+ // If admission is acquired only INSIDE the queue's turn, the cut can
+ // overtake the second edit and leave it waiting behind the snapshot.
+ const next = await Promise.race([
+ secondReached.promise.then(() => 'queued edit'),
+ cut.then(() => 'snapshot'),
+ ]);
+ expect(next).toBe('queued edit');
+ expect(await readMetadata()).toEqual({ prompt: 'after', hidden: true });
+ // The first commit finished, but the second row is still deliberately held.
+ expect(rows.get('fixture.png')).toMatchObject({ prompt: 'after', hidden: false });
+ } finally {
+ // Always release both commits and any acquired cut, including when a
+ // negative-control implementation let the snapshot overtake the queue.
+ commitFirst.resolve();
+ commitSecond.resolve();
+ (await cut)();
+ await Promise.all([prompt, visibility]);
+ }
+ expect(rows.get('fixture.png')).toMatchObject({ prompt: 'after', hidden: true });
+ expect(await readMetadata()).toEqual({ prompt: 'after', hidden: true });
+});
diff --git a/server/services/videoGen/historyOps.js b/server/services/videoGen/historyOps.js
index c4d0b696f1..aaee6954bd 100644
--- a/server/services/videoGen/historyOps.js
+++ b/server/services/videoGen/historyOps.js
@@ -2,6 +2,7 @@
import { PATHS, unlinkGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { safeUnder } from '../../lib/ffmpeg.js';
import { loadHistory, mutateVideoHistory } from './history.js';
@@ -40,33 +41,37 @@ export async function setHistoryItemHidden(id, hidden) {
}
export async function deleteHistoryItem(id) {
- const history = await loadHistory();
- const item = history.find((h) => h.id === id);
- if (!item) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
- // Same path-traversal guard as extractLastFrame — unlink only if the
- // filename resolves to inside the expected dir.
- const videoFile = safeUnder(PATHS.videos, item.filename);
- if (videoFile) await unlinkGuarded(videoFile).catch(() => {});
- if (item.thumbnail) {
- const thumbFile = safeUnder(PATHS.videoThumbnails, item.thumbnail);
- if (thumbFile) await unlinkGuarded(thumbFile).catch(() => {});
- }
- // Delete evaluation frame thumbnails written by sampleEvaluationFrames:
- // `${jobId}-f1.jpg` … `${jobId}-f9.jpg` (max count in sampleEvaluationFrames is 5,
- // but 9 is a safe upper bound to catch any future increase).
- for (let i = 1; i <= 9; i++) {
- const frameFile = safeUnder(PATHS.videoThumbnails, `${id}-f${i}.jpg`);
- if (frameFile) await unlinkGuarded(frameFile).catch(() => {});
- }
- // Serialized removal through the shared tail (re-filters the freshest list),
- // so a concurrent download/render append isn't dropped by this save.
- await mutateVideoHistory((h) => h.filter((x) => x.id !== id));
- // Drop the derived index row with the entry (#2738) — keyed by job id, the
- // ref the index wrote it under. Non-fatal + dynamically imported; see the
- // matching hook in imageGen/local.js#deleteImage for the rationale.
- await import('../mediaAssetIndex/index.js')
- .then((m) => m.unindexVideo(id))
- .catch((err) => console.error(`❌ Media index video delete hook: ${err.message}`));
- console.log(`🗑️ Deleted video: ${item.filename}`);
- return { ok: true };
+ // One lease covers the history read, file removals, history rewrite, and
+ // derived row removal; per-file admission would leave gaps between stores.
+ return withBackupAssetPublication(async () => {
+ const history = await loadHistory();
+ const item = history.find((h) => h.id === id);
+ if (!item) throw new ServerError('Not found', { status: 404, code: 'NOT_FOUND' });
+ // Same path-traversal guard as extractLastFrame — unlink only if the
+ // filename resolves to inside the expected dir.
+ const videoFile = safeUnder(PATHS.videos, item.filename);
+ if (videoFile) await unlinkGuarded(videoFile).catch(() => {});
+ if (item.thumbnail) {
+ const thumbFile = safeUnder(PATHS.videoThumbnails, item.thumbnail);
+ if (thumbFile) await unlinkGuarded(thumbFile).catch(() => {});
+ }
+ // Delete evaluation frame thumbnails written by sampleEvaluationFrames:
+ // `${jobId}-f1.jpg` … `${jobId}-f9.jpg` (max count in sampleEvaluationFrames is 5,
+ // but 9 is a safe upper bound to catch any future increase).
+ for (let i = 1; i <= 9; i++) {
+ const frameFile = safeUnder(PATHS.videoThumbnails, `${id}-f${i}.jpg`);
+ if (frameFile) await unlinkGuarded(frameFile).catch(() => {});
+ }
+ // Serialized removal through the shared tail (re-filters the freshest list),
+ // so a concurrent download/render append isn't dropped by this save.
+ await mutateVideoHistory((h) => h.filter((x) => x.id !== id));
+ // Drop the derived index row with the entry (#2738) — keyed by job id, the
+ // ref the index wrote it under. Non-fatal + dynamically imported; see the
+ // matching hook in imageGen/local.js#deleteImage for the rationale.
+ await import('../mediaAssetIndex/index.js')
+ .then((m) => m.unindexVideo(id))
+ .catch((err) => console.error(`❌ Media index video delete hook: ${err.message}`));
+ console.log(`🗑️ Deleted video: ${item.filename}`);
+ return { ok: true };
+ });
}