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 LoRA dataset changes outside backup snapshots (#9982)

[._.]/ Adam Eivy85a1492328bf
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 1bc6bd2704..6213a12384 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -61,9 +61,10 @@ Admission inventory (`withBackupAssetPublication`):
| 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 |
+| Other `mediaJobEvents` `completed` subscribers that write rows (universe-builder collection hook, character sheet, sprite animation, Creative Director scene runner/plan advance/seed settle, music-video production) | Outstanding |
| 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) |
+| LoRA dataset uploads, gallery imports, reference-sheet crops, generated completion/recovery copies, image/dataset deletion, and queued record edits (`loraDatasets.js`, `loraDatasetGenerate.js`) | Covered as complete file/record workflows (#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) |
@@ -78,8 +79,19 @@ 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
+LoRA datasets keep their metadata beside their images rather than in PostgreSQL.
+Their admitted workflows prevent rsync from capturing a half-applied image/record
+mutation too: upload/import normalization, reference-sheet cropping, generated
+image copies and recovery replacements, and image/dataset removal each hold one
+lease through their final metadata or file operation. Record edits acquire
+admission before joining the dataset write queue. Completion listeners acquire
+their own lease synchronously during queue fan-out; rendering, queue waits,
+captioning, and the vision crop proposal stay outside admission. Local image
+normalization/cropping and copying are included in the lease. Pending `rendering`
+entries can still name files that do not exist yet, and admission does not repair
+pre-existing missing files or make failed writes transactional.
+
+The remaining inventory includes 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
diff --git a/server/services/loraDatasetBackupAdmission.test.js b/server/services/loraDatasetBackupAdmission.test.js
new file mode 100644
index 0000000000..6e59f1524a
--- /dev/null
+++ b/server/services/loraDatasetBackupAdmission.test.js
@@ -0,0 +1,244 @@
+/** Exercise the real dataset/file workflows at their file-versus-record seam. */
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'fs/promises';
+import { join } from 'node:path';
+import sharp from 'sharp';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+let afterFileWrite = async () => {};
+let beforeRemove = async () => {};
+let beforeRecordWrite = async () => {};
+vi.mock('../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: () => lazyTempDataRoot('portos-lora-backup-'),
+ overrides: {
+ copyFileGuarded: async (source, dest) => { await actual.copyFileGuarded(source, dest); await afterFileWrite(dest); },
+ unlinkGuarded: async path => { await beforeRemove(path); return actual.unlinkGuarded(path); },
+ atomicWrite: async (path, value) => { await beforeRecordWrite(path); return actual.atomicWrite(path, value); },
+ },
+ });
+});
+vi.mock('fs/promises', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, rm: async (path, options) => { await beforeRemove(path); return actual.rm(path, options); } };
+});
+vi.mock('sharp', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, default: new Proxy(actual.default, {
+ apply(target, thisArg, args) {
+ const instance = Reflect.apply(target, thisArg, args);
+ const toFile = instance.toFile.bind(instance);
+ instance.toFile = async path => { const result = await toFile(path); await afterFileWrite(path); return result; };
+ return instance;
+ },
+ }) };
+});
+vi.mock('../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));
+vi.mock('./universeBuilder.js', () => ({ getUniverse: async () => ({
+ id: 'universe-1', characters: [{ id: 'subject-1', name: 'Example Character', referenceSheetImageRef: 'sheet.png' }],
+}) }));
+vi.mock('./settings.js', () => ({ getSettings: async () => ({ imageGen: { mode: 'local', local: { modelId: 'example-model' } } }) }));
+vi.mock('../lib/mediaModels.js', async importOriginal => ({
+ ...(await importOriginal()), getImageModels: () => [{ id: 'example-model', hardwareCompatibility: { state: 'available' } }],
+}));
+vi.mock('./visionTest.js', () => ({ describeImageDataUrlDetailed: vi.fn() }));
+vi.mock('./loraDatasetCaption.js', () => ({ resolveCaptionModel: vi.fn(), withCaptionVisionLock: work => work() }));
+vi.mock('./universeCharacterSheet.js', () => ({
+ extractCharacterPromptCommon: () => ({ name: 'Example Character' }),
+ REFERENCE_SHEET_CONSTANTS: { DEFAULT_EXPRESSIONS: ['neutral'] },
+}));
+vi.mock('./mediaJobQueue/index.js', async () => ({
+ mediaJobEvents: new (await import('node:events')).EventEmitter(),
+ getJob: () => null, enqueueJob: async () => ({ jobId: 'job-1' }),
+ assertMediaQueueRoom: () => {}, partialBatchAdmissionError: error => error,
+}));
+
+const { PATHS } = await import('../lib/fileUtils.js');
+const { acquireBackupSnapshotCut, runOutsideBackupAssetPublication, withBackupAssetPublication } = await import('../lib/backupSnapshotBoundary.js');
+const {
+ addUploadedImage, deleteDataset, deleteImage, datasetImagePath, datasetImagesDir,
+ getDataset, importGalleryImages, loraDatasetStore, reconcileRenderingImages, updateDataset,
+} = await import('./loraDatasets.js');
+const { generateDatasetImages, sliceReferenceSheet } = await import('./loraDatasetGenerate.js');
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const id = 'dataset-1';
+const recordPath = loraDatasetStore.recordPath(id);
+const oldBytes = await sharp({ create: { width: 128, height: 128, channels: 3, background: 'red' } }).png().toBuffer();
+const newBytes = await sharp({ create: { width: 128, height: 128, channels: 3, background: 'blue' } }).png().toBuffer();
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+const readRecord = () => readFile(recordPath, 'utf8').then(JSON.parse);
+const readImage = file => readFile(datasetImagePath(id, file));
+
+beforeEach(async () => {
+ afterFileWrite = beforeRemove = beforeRecordWrite = async () => {};
+ await rm(PATHS.data, { recursive: true, force: true });
+ await Promise.all([datasetImagesDir(id), PATHS.images, PATHS.imageRefs].map(path => mkdir(path, { recursive: true })));
+ await loraDatasetStore.saveOne(id, {
+ schemaVersion: 1, id, triggerWord: 'example_character',
+ character: { universeId: 'universe-1', entryId: 'subject-1', entryKind: 'characters', name: 'Example Character' },
+ images: [
+ { id: 'ready-1', file: 'ready.png', status: 'ready', caption: 'before' },
+ { id: 'pending-1', file: 'pending.png', status: 'rendering', sourceJobId: 'render-1' },
+ ],
+ });
+ await Promise.all([
+ writeFile(datasetImagePath(id, 'ready.png'), oldBytes),
+ writeFile(datasetImagePath(id, 'pending.png'), oldBytes),
+ writeFile(join(PATHS.images, 'source.png'), newBytes),
+ writeFile(join(PATHS.imageRefs, 'sheet.png'), newBytes),
+ writeFile(join(PATHS.data, 'upload.png'), newBytes),
+ ]);
+});
+afterAll(cleanupTempDataRoots);
+
+// The cut is requested AFTER bytes change but BEFORE updateDataset is entered.
+// Merely locking updateDataset or fileCore independently fails these contracts.
+it.each([
+ ['upload', () => addUploadedImage(id, { tmpPath: join(PATHS.data, 'upload.png') })],
+ ['gallery import', () => importGalleryImages(id, { filenames: ['source.png'] })],
+ ['reference-sheet crop', () => sliceReferenceSheet(id, { cols: 1, rows: 1, useVision: false })],
+ ['recovered render replacement', () => reconcileRenderingImages(id, {
+ jobLookup: () => ({ status: 'completed', result: { filename: 'source.png' } }),
+ })],
+])('drains the complete %s workflow before capturing dataset files', async (_name, mutate) => {
+ const fileWritten = deferred();
+ const finishWrite = deferred();
+ afterFileWrite = async path => {
+ if (path.startsWith(datasetImagesDir(id))) { fileWritten.resolve(); await finishWrite.promise; }
+ };
+ const mutation = mutate();
+ await fileWritten.promise;
+ const before = await readRecord();
+ expect(before.images).toHaveLength(2);
+ expect(before.images[1].status).toBe('rendering');
+ let entered = false;
+ const cut = acquireBackupSnapshotCut().then(release => { entered = true; return release; });
+ try {
+ await readdir(datasetImagesDir(id));
+ expect(entered).toBe(false);
+ } finally {
+ finishWrite.resolve();
+ await mutation;
+ (await cut)();
+ }
+ const published = await getDataset(id);
+ for (const image of published.images.filter(image => image.status === 'ready')) {
+ expect((await readImage(image.file)).length).toBeGreaterThan(0);
+ }
+});
+
+it.each([
+ ['image deletion', () => deleteImage(id, 'ready-1'), () => readImage('ready.png')],
+ ['dataset deletion', () => deleteDataset(id), () => readRecord()],
+])('drains %s through its final file removal', async (_name, mutate, readDeleted) => {
+ const removing = deferred();
+ const finishRemoval = deferred();
+ beforeRemove = async path => {
+ if (path.startsWith(loraDatasetStore.recordDir(id))) { removing.resolve(); await finishRemoval.promise; }
+ };
+ const mutation = mutate();
+ await removing.promise;
+ let entered = false;
+ const cut = acquireBackupSnapshotCut().then(release => { entered = true; return release; });
+ try {
+ expect(await readImage('ready.png')).toEqual(oldBytes);
+ expect(entered).toBe(false);
+ } finally {
+ finishRemoval.resolve();
+ await mutation;
+ (await cut)();
+ }
+ await expect(readDeleted()).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('keeps an existing snapshot stable while replacement and deletion wait', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const replacement = reconcileRenderingImages(id, {
+ jobLookup: () => ({ status: 'completed', result: { filename: 'source.png' } }),
+ });
+ const deletion = deleteImage(id, 'ready-1');
+ try {
+ expect(await readImage('pending.png')).toEqual(oldBytes);
+ expect(await readImage('ready.png')).toEqual(oldBytes);
+ expect((await readRecord()).images.map(image => image.status)).toEqual(['ready', 'rendering']);
+ } finally {
+ release();
+ await Promise.all([replacement, deletion]);
+ }
+ expect(await readImage('pending.png')).toEqual(newBytes);
+ await expect(readImage('ready.png')).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('drains a queued dataset edit through its record commit', async () => {
+ const inFirst = deferred();
+ const finishFirst = deferred();
+ const inSecond = deferred();
+ const finishSecond = deferred();
+ const first = updateDataset(id, async current => { inFirst.resolve(); await finishFirst.promise; return current; });
+ await inFirst.promise;
+ const second = updateDataset(id, async current => { inSecond.resolve(); await finishSecond.promise; return current; });
+ const cut = acquireBackupSnapshotCut();
+ try {
+ finishFirst.resolve();
+ expect(await Promise.race([inSecond.promise.then(() => 'edit'), cut.then(() => 'snapshot')])).toBe('edit');
+ } finally {
+ finishFirst.resolve();
+ finishSecond.resolve();
+ (await cut)();
+ await Promise.all([first, second]);
+ }
+});
+
+it('joins a draining completion fan-out synchronously and keeps its own lease through the dataset write', async () => {
+ const result = await generateDatasetImages(id, { count: 1 });
+ const rendered = result.images[0];
+ const emitCompletion = deferred();
+ const fileWritten = deferred();
+ const finishCopy = deferred();
+ const writingRecord = deferred();
+ const finishRecord = deferred();
+ afterFileWrite = async () => { fileWritten.resolve(); await finishCopy.promise; };
+ beforeRecordWrite = async path => { if (path === recordPath) { writingRecord.resolve(); await finishRecord.promise; } };
+ const queueCompletion = withBackupAssetPublication(async () => {
+ await emitCompletion.promise;
+ runOutsideBackupAssetPublication(() => mediaJobEvents.emit('completed', {
+ id: rendered.jobId, result: { filename: 'source.png' },
+ }));
+ });
+ let entered = false;
+ const cut = acquireBackupSnapshotCut().then(release => { entered = true; return release; });
+ try {
+ emitCompletion.resolve();
+ expect(await Promise.race([fileWritten.promise.then(() => 'copy'), cut.then(() => 'snapshot')])).toBe('copy');
+ await queueCompletion;
+ finishCopy.resolve();
+ await writingRecord.promise;
+ expect((await readRecord()).images.find(image => image.id === rendered.imageId).status).toBe('rendering');
+ expect(entered).toBe(false);
+ } finally {
+ emitCompletion.resolve();
+ finishCopy.resolve();
+ finishRecord.resolve();
+ (await cut)();
+ await queueCompletion;
+ }
+ const published = (await getDataset(id)).images.find(image => image.id === rendered.imageId);
+ expect(published.status).toBe('ready');
+ expect(await readImage(published.file)).toEqual(newBytes);
+});
+
+it('releases admission after an invalid import without publishing an image entry', async () => {
+ await expect(importGalleryImages(id, { filenames: ['source.png', 'missing.png'] })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ const release = await acquireBackupSnapshotCut();
+ try {
+ expect((await readRecord()).images).toHaveLength(2);
+ expect((await readdir(datasetImagesDir(id))).sort()).toEqual(['pending.png', 'ready.png']);
+ } finally {
+ release();
+ }
+});
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index 2939618df7..183137f36b 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -20,6 +20,7 @@ import { join, basename } from 'path';
import sharp from 'sharp';
import { PATHS, ensureDir, shortId, copyFileGuarded } from '../lib/fileUtils.js';
import { ServerError } from '../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { buildVariationMatrix } from '../lib/loraDataset.js';
import { extractJson } from '../lib/jsonExtract.js';
@@ -348,13 +349,17 @@ export async function generateDatasetImages(datasetId, options = {}) {
if (unsubscribe) { unsubscribe(); unsubscribe = null; }
};
const handlers = {
- onCompleted: async (job) => {
+ onCompleted: (job) => {
detach();
- await onRenderComplete({
- datasetId, imageId, file, sourceFilename: job.result?.filename,
- }).catch(async (err) => {
- await setImageStatus(datasetId, imageId, 'failed');
- console.error(`❌ Dataset render post-completion failed [${shortId(jobId)}]: ${err?.message}`);
+ // Acquire synchronously in the queue's fan-out so a cut already
+ // draining completion waits for this listener's full copy + record.
+ return withBackupAssetPublication(async () => {
+ await onRenderComplete({
+ datasetId, imageId, file, sourceFilename: job.result?.filename,
+ }).catch(async (err) => {
+ await setImageStatus(datasetId, imageId, 'failed');
+ console.error(`❌ Dataset render post-completion failed [${shortId(jobId)}]: ${err?.message}`);
+ });
});
},
onFailed: async (job) => {
@@ -560,31 +565,35 @@ export async function sliceReferenceSheet(datasetId, {
}
}
- await ensureDir(datasetImagesDir(datasetId));
- const entries = [];
- for (const rect of rects) {
- const imageId = uuidv4();
- const file = `${imageId}.png`;
- await sharp(sheetPath)
- .extract(rect)
- .png()
- .toFile(datasetImagePath(datasetId, file));
- entries.push({
- id: imageId,
- file,
- caption: '',
- captionSource: null,
- captionedAt: null,
- source: 'refsheet-slice',
- sourceJobId: null,
- variation: null,
- status: 'ready',
- width: rect.width,
- height: rect.height,
- createdAt: new Date().toISOString(),
- });
- }
- await updateDataset(datasetId, (current) => ({ ...current, images: [...current.images, ...entries] }));
- console.log(`✂️ Dataset ${shortId(datasetId)} ← ${entries.length} crops from ${basename(sheetFilename)} (${method}${method === 'grid' ? ` ${cols}×${rows}` : ''})`);
- return { images: entries, sheet: basename(sheetFilename), method };
+ // Vision/provider work above stays outside admission. Keep the complete
+ // local crop publication together, including its final dataset record.
+ return withBackupAssetPublication(async () => {
+ await ensureDir(datasetImagesDir(datasetId));
+ const entries = [];
+ for (const rect of rects) {
+ const imageId = uuidv4();
+ const file = `${imageId}.png`;
+ await sharp(sheetPath)
+ .extract(rect)
+ .png()
+ .toFile(datasetImagePath(datasetId, file));
+ entries.push({
+ id: imageId,
+ file,
+ caption: '',
+ captionSource: null,
+ captionedAt: null,
+ source: 'refsheet-slice',
+ sourceJobId: null,
+ variation: null,
+ status: 'ready',
+ width: rect.width,
+ height: rect.height,
+ createdAt: new Date().toISOString(),
+ });
+ }
+ await updateDataset(datasetId, (current) => ({ ...current, images: [...current.images, ...entries] }));
+ console.log(`✂️ Dataset ${shortId(datasetId)} ← ${entries.length} crops from ${basename(sheetFilename)} (${method}${method === 'grid' ? ` ${cols}×${rows}` : ''})`);
+ return { images: entries, sheet: basename(sheetFilename), method };
+ });
}
diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.js
index d6b4fac312..92ad069322 100644
--- a/server/services/loraDatasets.js
+++ b/server/services/loraDatasets.js
@@ -19,6 +19,7 @@ import sharp from 'sharp';
import { PATHS, ensureDir, copyFileGuarded, unlinkGuarded } from '../lib/fileUtils.js';
import { assertGalleryFilename } from './imageGen/local.js';
import { createCollectionStore } from '../lib/collectionStore.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import {
LORA_DATASET_SCHEMA_VERSION,
LORA_DATASET_ENTRY_KINDS,
@@ -71,10 +72,12 @@ const requireDataset = async (id) => {
* Read-modify-write a dataset inside its per-id write queue so concurrent
* mutations (caption blur-save + render-completion hook) merge against the
* freshest persisted record. `mutate` receives the sanitized record and
- * returns the next record (or null to abort without writing).
+ * returns the next record (or null to abort without writing). Backup admission
+ * begins before entering the queue; callers publishing bytes hold the outer
+ * lease through this record commit.
*/
export async function updateDataset(id, mutate) {
- return loraDatasetStore.queueRecordWrite(id, async () => {
+ return withBackupAssetPublication(() => loraDatasetStore.queueRecordWrite(id, async () => {
const current = await loraDatasetStore.loadOne(id);
if (!current) {
throw new ServerError(`LoRA dataset not found: ${id}`, { status: 404, code: 'NOT_FOUND' });
@@ -85,7 +88,7 @@ export async function updateDataset(id, mutate) {
await loraDatasetStore.saveOneNow(id, next);
trainingEvents.emit('dataset:changed', { datasetId: id });
return next;
- });
+ }));
}
const summarize = (dataset) => ({
@@ -306,12 +309,14 @@ export async function patchDataset(id, {
}
export async function deleteDataset(id) {
- await requireDataset(id);
- // deleteOne removes the whole `lora-datasets/<id>/` subtree — record AND
- // the images/ sidecar dir go together.
- await loraDatasetStore.deleteOne(id);
- console.log(`🗑️ Deleted LoRA dataset ${id}`);
- return { ok: true, id };
+ return withBackupAssetPublication(async () => {
+ await requireDataset(id);
+ // deleteOne removes the whole `lora-datasets/<id>/` subtree — record AND
+ // the images/ sidecar dir go together.
+ await loraDatasetStore.deleteOne(id);
+ console.log(`🗑️ Deleted LoRA dataset ${id}`);
+ return { ok: true, id };
+ });
}
/** Canonical dataset-image entry. One source of truth for the shape so every
@@ -341,25 +346,27 @@ const makeImageEntry = ({ imageId, file, source, info, sourceJobId = null }) =>
* upload is normalized rather than trusted by its claimed type.
*/
export async function addUploadedImage(id, { tmpPath, originalname = '' }) {
- await requireDataset(id);
- const imageId = uuidv4();
- const file = `${imageId}.png`;
- await ensureDir(datasetImagesDir(id));
- const destPath = datasetImagePath(id, file);
- const cleanup = () => unlinkGuarded(tmpPath).catch(() => {});
- const info = await sharp(tmpPath).rotate().png().toFile(destPath).catch(async (err) => {
+ return withBackupAssetPublication(async () => {
+ await requireDataset(id);
+ const imageId = uuidv4();
+ const file = `${imageId}.png`;
+ await ensureDir(datasetImagesDir(id));
+ const destPath = datasetImagePath(id, file);
+ const cleanup = () => unlinkGuarded(tmpPath).catch(() => {});
+ const info = await sharp(tmpPath).rotate().png().toFile(destPath).catch(async (err) => {
+ await cleanup();
+ throw new ServerError(
+ `"${originalname || 'upload'}" is not a decodable image: ${err?.message || err}`,
+ { status: 422, code: 'INVALID_IMAGE' },
+ );
+ });
await cleanup();
- throw new ServerError(
- `"${originalname || 'upload'}" is not a decodable image: ${err?.message || err}`,
- { status: 422, code: 'INVALID_IMAGE' },
- );
- });
- await cleanup();
- const entry = makeImageEntry({ imageId, file, source: 'upload', info });
- await updateDataset(id, (current) => ({ ...current, images: [...current.images, entry] }));
- console.log(`📥 Dataset ${id} ← upload ${file} (${entry.width}×${entry.height})`);
- return entry;
+ const entry = makeImageEntry({ imageId, file, source: 'upload', info });
+ await updateDataset(id, (current) => ({ ...current, images: [...current.images, entry] }));
+ console.log(`📥 Dataset ${id} ← upload ${file} (${entry.width}×${entry.height})`);
+ return entry;
+ });
}
/**
@@ -371,49 +378,51 @@ export async function addUploadedImage(id, { tmpPath, originalname = '' }) {
* dedup — same as uploading the same file twice). Returns the appended entries.
*/
export async function importGalleryImages(id, { filenames = [] } = {}) {
- await requireDataset(id);
- if (!Array.isArray(filenames) || !filenames.length) {
- throw new ServerError('No gallery filenames provided', { status: 400, code: 'VALIDATION_ERROR' });
- }
- await ensureDir(datasetImagesDir(id));
- // sharp transcodes are independent CPU/disk work — run them concurrently
- // (single-user trust model; the per-id write queue still serializes the one
- // dataset mutation below). Use allSettled, NOT all: a rejection from all()
- // returns before sibling toFile() calls finish, so files written *after* the
- // first failure would escape cleanup and orphan. allSettled waits for every
- // transcode to land before we either commit them all or unlink them all.
- const written = [];
- const results = await Promise.allSettled(filenames.map(async (filename) => {
- // Reuse the gallery's own path-traversal/extension guard.
- assertGalleryFilename(filename);
- const sourcePath = join(PATHS.images, basename(filename));
- if (!existsSync(sourcePath)) {
- throw new ServerError(`Gallery image not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ return withBackupAssetPublication(async () => {
+ await requireDataset(id);
+ if (!Array.isArray(filenames) || !filenames.length) {
+ throw new ServerError('No gallery filenames provided', { status: 400, code: 'VALIDATION_ERROR' });
}
- const imageId = uuidv4();
- const file = `${imageId}.png`;
- const destPath = datasetImagePath(id, file);
- const info = await sharp(sourcePath).rotate().png().toFile(destPath)
- .then((i) => { written.push(destPath); return i; })
- .catch((err) => {
- throw new ServerError(
- `"${filename}" is not a decodable image: ${err?.message || err}`,
- { status: 422, code: 'INVALID_IMAGE' },
- );
- });
- return makeImageEntry({ imageId, file, source: 'gallery', info });
- }));
- const failure = results.find((r) => r.status === 'rejected');
- if (failure) {
- // All transcodes have settled now, so `written` is complete — no late write
- // can re-orphan a file after this cleanup.
- await Promise.all(written.map((p) => unlinkGuarded(p).catch(() => {})));
- throw failure.reason;
- }
- const entries = results.map((r) => r.value);
- await updateDataset(id, (current) => ({ ...current, images: [...current.images, ...entries] }));
- console.log(`🖼️ Dataset ${id} ← imported ${entries.length} gallery image(s)`);
- return entries;
+ await ensureDir(datasetImagesDir(id));
+ // sharp transcodes are independent CPU/disk work — run them concurrently
+ // (single-user trust model; the per-id write queue still serializes the one
+ // dataset mutation below). Use allSettled, NOT all: a rejection from all()
+ // returns before sibling toFile() calls finish, so files written *after* the
+ // first failure would escape cleanup and orphan. allSettled waits for every
+ // transcode to land before we either commit them all or unlink them all.
+ const written = [];
+ const results = await Promise.allSettled(filenames.map(async (filename) => {
+ // Reuse the gallery's own path-traversal/extension guard.
+ assertGalleryFilename(filename);
+ const sourcePath = join(PATHS.images, basename(filename));
+ if (!existsSync(sourcePath)) {
+ throw new ServerError(`Gallery image not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ const imageId = uuidv4();
+ const file = `${imageId}.png`;
+ const destPath = datasetImagePath(id, file);
+ const info = await sharp(sourcePath).rotate().png().toFile(destPath)
+ .then((i) => { written.push(destPath); return i; })
+ .catch((err) => {
+ throw new ServerError(
+ `"${filename}" is not a decodable image: ${err?.message || err}`,
+ { status: 422, code: 'INVALID_IMAGE' },
+ );
+ });
+ return makeImageEntry({ imageId, file, source: 'gallery', info });
+ }));
+ const failure = results.find((r) => r.status === 'rejected');
+ if (failure) {
+ // All transcodes have settled now, so `written` is complete — no late write
+ // can re-orphan a file after this cleanup.
+ await Promise.all(written.map((p) => unlinkGuarded(p).catch(() => {})));
+ throw failure.reason;
+ }
+ const entries = results.map((r) => r.value);
+ await updateDataset(id, (current) => ({ ...current, images: [...current.images, ...entries] }));
+ console.log(`🖼️ Dataset ${id} ← imported ${entries.length} gallery image(s)`);
+ return entries;
+ });
}
export async function updateImageCaption(id, imageId, caption) {
@@ -481,16 +490,18 @@ export async function stripSharedCaptionFragments(id) {
}
export async function deleteImage(id, imageId) {
- let removed = null;
- await updateDataset(id, (current) => {
- removed = current.images.find((img) => img.id === imageId) || null;
- if (!removed) {
- throw new ServerError(`Image ${imageId} not found in dataset`, { status: 404, code: 'NOT_FOUND' });
- }
- return { ...current, images: current.images.filter((img) => img.id !== imageId) };
+ return withBackupAssetPublication(async () => {
+ let removed = null;
+ await updateDataset(id, (current) => {
+ removed = current.images.find((img) => img.id === imageId) || null;
+ if (!removed) {
+ throw new ServerError(`Image ${imageId} not found in dataset`, { status: 404, code: 'NOT_FOUND' });
+ }
+ return { ...current, images: current.images.filter((img) => img.id !== imageId) };
+ });
+ await unlinkGuarded(datasetImagePath(id, removed.file)).catch(() => {});
+ return { ok: true, imageId };
});
- await unlinkGuarded(datasetImagePath(id, removed.file)).catch(() => {});
- return { ok: true, imageId };
}
/**
@@ -504,44 +515,46 @@ export async function deleteImage(id, imageId) {
* `jobLookup` is injectable for tests; defaults to the queue's getJob.
*/
export async function reconcileRenderingImages(id, { jobLookup = getJob } = {}) {
- const dataset = await requireDataset(id);
- const pending = dataset.images.filter((img) => img.status === 'rendering');
- if (!pending.length) return dataset;
+ return withBackupAssetPublication(async () => {
+ const dataset = await requireDataset(id);
+ const pending = dataset.images.filter((img) => img.status === 'rendering');
+ if (!pending.length) return dataset;
- const resolutions = new Map(); // imageId → { status, sourceFilename? , dims? }
- for (const img of pending) {
- const job = img.sourceJobId ? jobLookup(img.sourceJobId) : null;
- if (!job || job.status === 'failed' || job.status === 'canceled') {
- resolutions.set(img.id, { status: 'failed' });
- } else if (job.status === 'completed' && job.result?.filename) {
- resolutions.set(img.id, { status: 'ready', sourceFilename: job.result.filename });
+ const resolutions = new Map(); // imageId → { status, sourceFilename? , dims? }
+ for (const img of pending) {
+ const job = img.sourceJobId ? jobLookup(img.sourceJobId) : null;
+ if (!job || job.status === 'failed' || job.status === 'canceled') {
+ resolutions.set(img.id, { status: 'failed' });
+ } else if (job.status === 'completed' && job.result?.filename) {
+ resolutions.set(img.id, { status: 'ready', sourceFilename: job.result.filename });
+ }
+ // queued/running jobs stay 'rendering' — the live hook will land them.
}
- // queued/running jobs stay 'rendering' — the live hook will land them.
- }
- if (!resolutions.size) return dataset;
+ if (!resolutions.size) return dataset;
- for (const [imageId, res] of resolutions) {
- if (res.status !== 'ready') continue;
- const img = pending.find((p) => p.id === imageId);
- await ensureDir(datasetImagesDir(id));
- // basename() so a hand-edited media-jobs.json filename can't traverse
- // out of the gallery (mirrors onRenderComplete in loraDatasetGenerate).
- await copyFileGuarded(join(PATHS.images, basename(res.sourceFilename)), datasetImagePath(id, img.file))
- .catch((err) => {
- console.error(`❌ Dataset ${id} reconcile copy failed [${imageId}]: ${err?.message}`);
- resolutions.set(imageId, { status: 'failed' });
- });
- }
+ for (const [imageId, res] of resolutions) {
+ if (res.status !== 'ready') continue;
+ const img = pending.find((p) => p.id === imageId);
+ await ensureDir(datasetImagesDir(id));
+ // basename() so a hand-edited media-jobs.json filename can't traverse
+ // out of the gallery (mirrors onRenderComplete in loraDatasetGenerate).
+ await copyFileGuarded(join(PATHS.images, basename(res.sourceFilename)), datasetImagePath(id, img.file))
+ .catch((err) => {
+ console.error(`❌ Dataset ${id} reconcile copy failed [${imageId}]: ${err?.message}`);
+ resolutions.set(imageId, { status: 'failed' });
+ });
+ }
- const updated = await updateDataset(id, (current) => ({
- ...current,
- images: current.images.map((img) => {
- const res = resolutions.get(img.id);
- return res ? { ...img, status: res.status } : img;
- }),
- }));
- const resolved = [...resolutions.values()];
- const readyCount = resolved.filter((r) => r.status === 'ready').length;
- console.log(`🩹 Dataset ${id} reconciled ${resolved.length} rendering image(s) → ${readyCount} ready, ${resolved.length - readyCount} failed`);
- return updated;
+ const updated = await updateDataset(id, (current) => ({
+ ...current,
+ images: current.images.map((img) => {
+ const res = resolutions.get(img.id);
+ return res ? { ...img, status: res.status } : img;
+ }),
+ }));
+ const resolved = [...resolutions.values()];
+ const readyCount = resolved.filter((r) => r.status === 'ready').length;
+ console.log(`🩹 Dataset ${id} reconciled ${resolved.length} rendering image(s) → ${readyCount} ready, ${resolved.length - readyCount} failed`);
+ return updated;
+ });
}