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 training registration, promotion and deletion whole across backups (#9982)

Adam Eivy1ba91d0876c8
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 67514bec2d..1eee895483 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -79,7 +79,8 @@ Admission inventory (`withBackupAssetPublication`):
| Voice benchmark audio and row (`voice/profileBenchmarks.js`), cloned-candidate recording and row (`voice/profiles.js`), and the fine-tune job record that names each sealed checkpoint (`voice/fineTuning.js`) | Covered (#9982 partial); promoting a checkpoint writes only a row naming bytes the job record already named |
| Pipeline audio stage rows: generated music, cue render and voice-over line render (`routes/pipeline/audio.js`) | Covered (#9982 partial): the row that first names the WAV takes the lease; the sidecar or synthesizer writes the WAV before it |
| Music-library upload attach: Music Designer upload, pipeline music upload and YouTube import (`routes/tracks.js`, `routes/pipeline/audio.js`, `trackYoutubeImport.js`) | Reference-only: the admitted library import copies the file first and the track or issue row commits after it |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, Music Video renders and records, video generation, image generation tails, Writers Room drafts, LoRA registration and deletion, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports |
+| LoRA training and deployed LoRAs: trained-adapter registration, checkpoint promotion over the deployed adapter, the promoted-checkpoint preview copy, the progress row naming trainer-written samples and checkpoints, run deletion, and LoRA deletion from the LoRA manager or Media Models (`loraTraining/index.js`, `loras.js`) | Covered (#9982 partial): registration and promotion hold one lease from the adapter write through the run row and dataset flag; Civitai and Hugging Face installs admit the sidecar that first names the already-linked weights |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, Music Video renders and records, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports |
| Durable replacement/deletion owners not yet classified | Outstanding (#9982) |
| Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
@@ -148,6 +149,20 @@ possibly while a cut was running, and a row that waits out the cut can only name
audio the snapshot copied, or nothing. Music library uploads need no lease of
their own at the row: the admitted import copies the file first.
+LoRA training registers its adapter, sidecar, run row and dataset flag under one
+lease, and checkpoint promotion does the same while it overwrites the deployed
+adapter in place; the completion event fires after the lease so the media
+queue's own admitted commit never borrows it. The trainer writes samples and
+checkpoints itself, so only the progress row that first names them takes the
+lease, and a progress-only update never waits out a cut. Run deletion holds one
+lease from the artifact-directory removal through the LoRA unlink, the dataset
+reset and the row delete. A LoRA deleted from the manager leaves runs and other
+records that named it pointing at the removed file, so that unlink holds the
+lease too. A downloaded LoRA is linked under its final name before its sidecar
+is written; the sidecar write takes the lease, so a snapshot can hold weights
+without their sidecar (they list with fallback metadata) but never a sidecar
+without its weights.
+
**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventories
each durable owner as `admitted`, `reference-only` or `outstanding`, and its
test fails when an `admitted` entry stops taking the lease or a module that
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 059370d2fb..3dbcd8663a 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -76,6 +76,20 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'admitted',
modules: ['services/voice/fineTuning.js', 'services/voice/profileBenchmarks.js', 'services/voice/profiles.js'],
},
+ {
+ // Trained LoRA registration (adapter, sidecar, run row, dataset flag),
+ // checkpoint promotion over the deployed adapter, the promoted-checkpoint
+ // preview copy, the progress row that first names trainer-written samples
+ // and checkpoints, run deletion, and LoRA deletion from either manager
+ // route. Civitai and Hugging Face installs land the weights under their
+ // final name first; the sidecar naming them is the admitted commit.
+ // Staged trainer inputs are rebuilt from the dataset on every run and
+ // resume, and sidecar metadata patches change no asset bytes. Dataset
+ // deletion is part of `lora-dataset-workflows`.
+ id: 'lora-training-registration-and-deletion',
+ status: 'admitted',
+ modules: ['services/loraTraining/index.js', 'services/loras.js'],
+ },
{
// Generated and cue-rendered music and voice-over line audio land on disk
// before the issue row that names them; the row commit takes the lease.
@@ -150,13 +164,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'outstanding',
modules: ['services/writersRoom/local.js', 'services/writersRoom/sync.js', 'services/writersRoom/polish.js'],
},
- {
- // Trained LoRA registration and checkpoint promotion, preview copies, and
- // the run, LoRA and dataset deletes.
- id: 'lora-training-registration-and-deletion',
- status: 'outstanding',
- modules: ['services/loraTraining/index.js', 'services/loras.js', 'routes/loraTraining.js', 'routes/loras.js'],
- },
{
// Generated HTML, package import and repair, run artifacts, and the final
// stage whose soundtrack mux rewrites the MP4 before the history append.
diff --git a/server/routeValidationConventions.test.js b/server/routeValidationConventions.test.js
index 5e08ed23d8..0ef7a646c1 100644
--- a/server/routeValidationConventions.test.js
+++ b/server/routeValidationConventions.test.js
@@ -259,7 +259,6 @@ const UNVALIDATED_QUERY_BASELINE = [
'routes/jira.js GET /reports',
'routes/localLlm.js GET /catalog',
'routes/localLlm.js GET /loaded',
- 'routes/loraTraining.js DELETE /runs/:id',
'routes/loras.js GET /',
'routes/loras.js GET /suggestions',
'routes/meatspaceAlcoholRoutes.js GET /alcohol/daily',
diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.js
index 11e7a80096..9418b13ca5 100644
--- a/server/routes/imageVideoModels.js
+++ b/server/routes/imageVideoModels.js
@@ -221,14 +221,11 @@ router.delete('/lora/:filename', asyncHandler(async (req, res) => {
if (!filename.endsWith('.safetensors') || filename.includes('/') || filename.includes('\\') || filename.includes('..')) {
throw new ServerError('Invalid filename', { status: 400, code: 'VALIDATION_ERROR' });
}
- const filePath = join(PATHS.loras, filename);
- if (!existsSync(filePath)) throw new ServerError('LoRA not found', { status: 404, code: 'NOT_FOUND' });
- console.log(`🗑️ Deleting LoRA: ${filename}`);
- await rmGuarded(filePath, { force: true });
- // This route removes the weight file directly rather than going through
- // `loras.deleteLora`, so it clears the manifest entry itself.
- await recordModelUninstall({ backend: 'lora', key: filename });
- res.json({ ok: true });
+ // The LoRA manager's delete removes the sidecar with the weights, clears the
+ // manifest entry, and holds backup admission across the unlink (#9982).
+ // Imported on use so this route's graph doesn't carry the installers.
+ const { deleteLora } = await import('../services/loras.js');
+ res.json(await deleteLora(filename));
}));
// DELETE /store/:backend/:key — remove or clear one item of a file-system model
diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.js
index d2497e01fc..d1574856f6 100644
--- a/server/routes/loraTraining.js
+++ b/server/routes/loraTraining.js
@@ -11,13 +11,12 @@ import { join } from 'path';
import { z } from 'zod';
import { asyncHandler, sendErrorResponse, ServerError } from '../lib/errorHandler.js';
import { startTrainingRunSchema, validateRequest } from '../lib/validation.js';
-import { assertSafeFilename, rmGuarded } from '../lib/fileUtils.js';
+import { assertSafeFilename } from '../lib/fileUtils.js';
import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../lib/pythonSetup.js';
import { getSettings } from '../services/settings.js';
import { attachSseClient, cancelJob } from '../services/mediaJobQueue/index.js';
import {
- clearDatasetForDeletedLora,
- deleteRun,
+ deleteTrainingRun,
getRunRequired,
isMfluxTrainAvailable,
listCheckpoints,
@@ -25,12 +24,10 @@ import {
listSamples,
promoteCheckpoint,
resumeTrainingRun,
- runDir,
runSamplesDir,
startTrainingRun,
} from '../services/loraTraining/index.js';
import { TRAINING_DEFAULTS } from '../services/loraTraining/runtimes.js';
-import { deleteLora } from '../services/loras.js';
const router = Router();
@@ -107,23 +104,10 @@ router.post('/runs/:id/resume', asyncHandler(async (req, res) => {
res.status(202).json(await resumeTrainingRun(req.params.id));
}));
+const deleteRunQuerySchema = z.object({ deleteLora: z.enum(['true', 'false']).optional() });
router.delete('/runs/:id', asyncHandler(async (req, res) => {
- const run = await getRunRequired(req.params.id);
- if (['queued', 'running'].includes(run.status)) {
- throw new ServerError('Cancel the run before deleting it', { status: 409, code: 'RUN_ACTIVE' });
- }
- // Artifact dir is server-derived from the run id (uuid) — confined under
- // PATHS.trainingRuns by construction.
- await rmGuarded(runDir(run.id), { recursive: true, force: true });
- if (req.query.deleteLora === 'true' && run.output?.loraFilename) {
- await deleteLora(run.output.loraFilename).catch((err) => {
- console.log(`⚠️ trained LoRA delete skipped: ${err?.message}`);
- });
- // Reset the owning dataset off 'trained' so it can't keep advertising the
- // subject as trained against the file we just deleted.
- await clearDatasetForDeletedLora(run, run.output.loraFilename);
- }
- res.json(await deleteRun(run.id));
+ const { deleteLora } = validateRequest(deleteRunQuerySchema, req.query);
+ res.json(await deleteTrainingRun(req.params.id, { withLora: deleteLora === 'true' }));
}));
// Checkpoint picker: list every saved checkpoint with its step, loss, and
diff --git a/server/services/loraTraining/backupAdmission.test.js b/server/services/loraTraining/backupAdmission.test.js
new file mode 100644
index 0000000000..60c54d072e
--- /dev/null
+++ b/server/services/loraTraining/backupAdmission.test.js
@@ -0,0 +1,158 @@
+/** LoRA training and deployed-LoRA workflows over real files. A backup cut must
+ * never copy a replaced adapter whose run row it then dumps unchanged, and must
+ * never let a deletion remove bytes a captured row still names (#9982). */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-lora-training-backup-'),
+}));
+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));
+
+// In-memory run rows; every write awaits `beforeRowWrite` so a test can hold
+// a workflow at its row commit.
+const rows = new Map();
+let beforeRowWrite = async () => {};
+vi.mock('./db.js', () => ({
+ getRun: async id => rows.get(id) ?? null,
+ getRunRequired: async (id) => {
+ if (!rows.has(id)) throw Object.assign(new Error(`Run ${id} not found`), { status: 404 });
+ return rows.get(id);
+ },
+ updateRun: async (id, patch) => {
+ await beforeRowWrite(id);
+ const current = rows.get(id);
+ rows.set(id, typeof patch === 'function' ? patch(current) : { ...current, ...patch });
+ return rows.get(id);
+ },
+ deleteRun: async (id) => { await beforeRowWrite(id); rows.delete(id); return { ok: true, id }; },
+ listRuns: async () => [...rows.values()],
+ listActiveRuns: async () => [],
+}));
+vi.mock('./checkpoints.js', () => ({
+ listRunCheckpoints: () => [{ step: 100, loss: 0.1, previewUrl: '/preview.png' }],
+ listRunSamples: () => [],
+ resolveCheckpointAdapterBuffer: async () => Buffer.from('promoted adapter'),
+ resolveLatestCheckpointArtifact: () => null,
+ selectDeployableCheckpoint: vi.fn(),
+}));
+vi.mock('../loraDatasets.js', () => ({ updateDataset: async () => null }));
+vi.mock('../modelManifest.js', () => ({ recordModelInstall: async () => {}, recordModelUninstall: async () => {} }));
+vi.mock('../settings.js', () => ({ getSettings: async () => ({}) }));
+vi.mock('../../lib/pythonSetup.js', () => ({
+ isFlux2VenvHealthy: async () => false, resolveFlux2Python: () => null, resolveMfluxPython: () => null,
+}));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: () => {}, enqueueJob: vi.fn(), getJob: () => null, mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
+}));
+
+const { PATHS } = await import('../../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+const { deleteTrainingRun, promoteCheckpoint, runDir } = await import('./index.js');
+const { deleteLora, writeLoraSidecar } = await import('../loras.js');
+
+const LORA = 'lora-example-trained.safetensors';
+const deferred = () => {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+};
+const settle = () => new Promise(resolve => setImmediate(resolve));
+const settleSeveral = async () => { for (let i = 0; i < 5; i += 1) await settle(); };
+const adapterBytes = () => readFile(join(PATHS.loras, LORA), 'utf8');
+const seedRun = (overrides = {}) => rows.set('run-1', {
+ id: 'run-1', status: 'completed', name: 'Example', datasetId: null,
+ character: { entryId: 'subject-1', universeId: 'universe-1', name: 'Example Character' },
+ params: { steps: 100 }, progress: { step: 100 },
+ output: { loraFilename: LORA, selectedCheckpointStep: 200 },
+ ...overrides,
+});
+
+afterAll(() => cleanupTempDataRoots());
+beforeEach(async () => {
+ beforeRowWrite = async () => {};
+ rows.clear();
+ await rm(PATHS.data, { recursive: true, force: true });
+ await mkdir(PATHS.loras, { recursive: true });
+ await mkdir(join(runDir('run-1'), 'samples'), { recursive: true });
+ await writeFile(join(runDir('run-1'), 'samples', 'sample.png'), 'synthetic sample');
+ await writeFile(join(PATHS.loras, LORA), 'deployed adapter');
+ seedRun();
+});
+
+describe('checkpoint promotion', () => {
+ it('drains a promotion that already replaced the adapter until its run row commits', async () => {
+ const held = deferred();
+ const proceed = deferred();
+ beforeRowWrite = async () => { held.resolve(); await proceed.promise; };
+ const promotion = promoteCheckpoint('run-1', 100);
+ await held.promise;
+ expect(await adapterBytes()).toBe('promoted adapter');
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ await settleSeveral();
+ expect(cutReady).toBe(false);
+ proceed.resolve();
+ await promotion;
+ const release = await cut;
+ expect(rows.get('run-1').output.selectedCheckpointStep).toBe(100);
+ release();
+ });
+
+ it('leaves the deployed adapter untouched while a cut is open', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const promotion = promoteCheckpoint('run-1', 100);
+ await settleSeveral();
+ expect(await adapterBytes()).toBe('deployed adapter');
+ expect(rows.get('run-1').output.selectedCheckpointStep).toBe(200);
+ release();
+ await promotion;
+ expect(await adapterBytes()).toBe('promoted adapter');
+ });
+});
+
+describe('run and LoRA deletion', () => {
+ it('keeps the run artifacts, adapter and row until the cut that captured them finishes', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const deletion = deleteTrainingRun('run-1', { withLora: true });
+ await settleSeveral();
+ expect(existsSync(runDir('run-1'))).toBe(true);
+ expect(await readdir(PATHS.loras)).toContain(LORA);
+ expect(rows.has('run-1')).toBe(true);
+ release();
+ expect(await deletion).toEqual({ ok: true, id: 'run-1' });
+ expect(existsSync(runDir('run-1'))).toBe(false);
+ expect(await readdir(PATHS.loras)).not.toContain(LORA);
+ });
+
+ it('refuses to delete an active run before touching its files', async () => {
+ seedRun({ status: 'running' });
+ await expect(deleteTrainingRun('run-1')).rejects.toMatchObject({ code: 'RUN_ACTIVE' });
+ expect(existsSync(runDir('run-1'))).toBe(true);
+ });
+
+ it('holds a manager deletion until the cut finishes, since other rows may still name the LoRA', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const deletion = deleteLora(LORA);
+ await settleSeveral();
+ expect(await readdir(PATHS.loras)).toContain(LORA);
+ release();
+ await deletion;
+ expect(await readdir(PATHS.loras)).not.toContain(LORA);
+ });
+});
+
+describe('LoRA install commit', () => {
+ it('writes the sidecar naming newly linked weights only after the cut finishes', async () => {
+ const release = await acquireBackupSnapshotCut();
+ const commit = writeLoraSidecar(LORA, { name: 'Example' });
+ await settleSeveral();
+ expect(existsSync(join(PATHS.loras, `${LORA}.metadata.json`))).toBe(false);
+ release();
+ await commit;
+ expect(existsSync(join(PATHS.loras, `${LORA}.metadata.json`))).toBe(true);
+ });
+});
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index d7cd8f0982..87db96ed6c 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -17,8 +17,9 @@ import { spawn } from '../../lib/childProcess.js';
import { existsSync } from 'fs';
import { join, basename, dirname } from 'path';
import { platform } from 'os';
-import { PATHS, ensureDir, atomicWrite, shortId, copyFileGuarded, writeFileGuarded } from '../../lib/fileUtils.js';
+import { PATHS, ensureDir, atomicWrite, shortId, copyFileGuarded, writeFileGuarded, rmGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { maintenance } from '../../lib/maintenanceAdmission.js';
import { v4 as uuidv4 } from '../../lib/uuid.js';
import { hfChildEnv } from '../hfToken.js';
@@ -27,7 +28,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { getImageModels } from '../../lib/mediaModels.js';
import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
-import { writeLoraSidecar } from '../loras.js';
+import { deleteLora, writeLoraSidecar } from '../loras.js';
import { assertMediaQueueRoom, enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateDataset } from '../loraDatasets.js';
import { trainingEvents } from './events.js';
@@ -433,6 +434,34 @@ export const clearDatasetForDeletedLora = (run, deletedFilename) => {
}).catch((err) => console.error(`❌ dataset reset after LoRA delete failed: ${err?.message}`));
};
+/**
+ * Delete a terminal run: its artifact dir, optionally its trained LoRA (and the
+ * dataset's trained flag naming it), then the row. One backup admission spans
+ * every step, so a snapshot never dumps a row naming samples or an adapter its
+ * own file pass skipped (#9982).
+ */
+export async function deleteTrainingRun(runId, { withLora = false } = {}) {
+ return withBackupAssetPublication(async () => {
+ const run = await runsDb.getRunRequired(runId);
+ if (['queued', 'running'].includes(run.status)) {
+ throw new ServerError('Cancel the run before deleting it', { status: 409, code: 'RUN_ACTIVE' });
+ }
+ // Artifact dir is server-derived from the run id (uuid) — confined under
+ // PATHS.trainingRuns by construction.
+ await rmGuarded(runDir(run.id), { recursive: true, force: true });
+ const loraFilename = run.output?.loraFilename;
+ if (withLora && loraFilename) {
+ await deleteLora(loraFilename).catch((err) => {
+ console.warn(`⚠️ trained LoRA delete skipped: ${err?.message}`);
+ });
+ // Reset the owning dataset off 'trained' so it can't keep advertising the
+ // subject as trained against the file just deleted.
+ await clearDatasetForDeletedLora(run, loraFilename);
+ }
+ return runsDb.deleteRun(run.id);
+ });
+}
+
/**
* Queue-worker entry — `mediaJobQueue.runJob` calls this for kind
* 'training'. Resolves the trainer binary + args, spawns, parses the line
@@ -733,7 +762,11 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
if (!progressDirty) return Promise.resolve();
const flushing = progressDirty;
progressDirty = null;
- return runsDb.updateRun(runId, (current) => ({
+ // The trainer writes sample and checkpoint files in place before announcing
+ // them, so only the row that first names them takes backup admission
+ // (#9982); a progress-only flush never waits out a cut.
+ const namesArtifacts = !!(flushing.checkpoints || flushing.samples);
+ const write = () => runsDb.updateRun(runId, (current) => ({
...current,
progress: { ...current.progress, ...flushing.progress },
artifacts: {
@@ -746,8 +779,9 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
...(flushing.checkpoints ? { checkpoints: dedupeCheckpointsByStep([...current.artifacts.checkpoints, ...flushing.checkpoints]) } : {}),
...(flushing.samples ? { samples: [...new Set([...current.artifacts.samples, ...flushing.samples])] } : {}),
},
- })).then(() => {
- if (flushing.checkpoints || flushing.samples) trainingEvents.emit('checkpoints:changed', { runId });
+ }));
+ return (namesArtifacts ? withBackupAssetPublication(write) : write()).then(() => {
+ if (namesArtifacts) trainingEvents.emit('checkpoints:changed', { runId });
}).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));
};
// Checkpoints/samples accumulate as arrays so two that land in one debounce
@@ -983,26 +1017,32 @@ async function finalizeTraining({ jobId, runId, code, signal, state, stallKilled
const filename = trainedLoraFilename({
name: run?.name, characterName: run?.character?.name, runId,
});
- const { sizeBytes } = await registerTrainedLora({
- run,
- buffer: selection.buffer,
- filename,
- result: state.result,
- previewImageUrl: selection.previewUrl,
- selectedStep: selection.step,
- autoSelected: selection.autoSelected,
- });
- await runsDb.updateRun(runId, {
- status: 'completed',
- completedAt: new Date().toISOString(),
- output: {
- loraFilename: filename,
- finalLoss: Number.isFinite(state.result.final_loss) ? state.result.final_loss : null,
- selectedCheckpointStep: selection.step,
- autoSelectedCheckpoint: selection.autoSelected,
- },
+ // One backup admission from the adapter write through the run row and the
+ // dataset flag that name it (#9982). The completion event fires after the
+ // lease, so the queue's own admitted commit never borrows this one.
+ const { sizeBytes } = await withBackupAssetPublication(async () => {
+ const registered = await registerTrainedLora({
+ run,
+ buffer: selection.buffer,
+ filename,
+ result: state.result,
+ previewImageUrl: selection.previewUrl,
+ selectedStep: selection.step,
+ autoSelected: selection.autoSelected,
+ });
+ await runsDb.updateRun(runId, {
+ status: 'completed',
+ completedAt: new Date().toISOString(),
+ output: {
+ loraFilename: filename,
+ finalLoss: Number.isFinite(state.result.final_loss) ? state.result.final_loss : null,
+ selectedCheckpointStep: selection.step,
+ autoSelectedCheckpoint: selection.autoSelected,
+ },
+ });
+ await flipDatasetAfterRun(run, { trained: true, loraFilename: filename });
+ return registered;
});
- await flipDatasetAfterRun(run, { trained: true, loraFilename: filename });
if (selection.autoSelected) console.log(`⚠️ training [${shortId(jobId)}] ${selection.reason} (size ${sizeBytes ?? '?'}B)`);
console.log(`✅ training [${shortId(jobId)}] complete — registered ${filename} @ step ${selection.step}`);
trainingEvents.emit('completed', {
@@ -1124,26 +1164,30 @@ export async function promoteCheckpoint(runId, step) {
// Keep trainedSteps pointing at the run's final step so the sidecar can note
// "checkpoint @ step N" whenever the promoted step isn't the final one.
const finalStep = Math.max(0, ...listed.map((c) => c.step), run.progress?.step || 0) || null;
- await registerTrainedLora({
- run,
- buffer,
- filename,
- result: { steps: finalStep, final_loss: target.loss },
- previewImageUrl: target.previewUrl,
- selectedStep: step,
- autoSelected: false,
+ // Promotion replaces the deployed adapter in place, so the new bytes, the run
+ // row and the dataset flag publish under one backup admission (#9982).
+ await withBackupAssetPublication(async () => {
+ await registerTrainedLora({
+ run,
+ buffer,
+ filename,
+ result: { steps: finalStep, final_loss: target.loss },
+ previewImageUrl: target.previewUrl,
+ selectedStep: step,
+ autoSelected: false,
+ });
+ await runsDb.updateRun(runId, (current) => ({
+ ...current,
+ output: {
+ ...current.output,
+ loraFilename: filename,
+ selectedCheckpointStep: step,
+ autoSelectedCheckpoint: false,
+ },
+ }));
+ await flipDatasetAfterRun(run, { trained: true, loraFilename: filename });
});
- await runsDb.updateRun(runId, (current) => ({
- ...current,
- output: {
- ...current.output,
- loraFilename: filename,
- selectedCheckpointStep: step,
- autoSelectedCheckpoint: false,
- },
- }));
trainingEvents.emit('checkpoints:changed', { runId });
- await flipDatasetAfterRun(run, { trained: true, loraFilename: filename });
console.log(`📌 training [${shortId(runId)}] promoted checkpoint step ${step} → ${filename}`);
// If the promoted checkpoint had no preview (its step didn't land on the
// sampleEvery cadence — most often the final step, e.g. 1188 with sampleEvery
@@ -1214,15 +1258,19 @@ async function ensureCheckpointPreview(run, step, loraFilename) {
const renderedPath = join(PATHS.images, result?.filename || `lora-preview-${runId}-${step}.png`);
if (!existsSync(renderedPath)) { console.error(`⚠️ training [${shortId(runId)}] preview render produced no file`); return; }
- await ensureDir(samplesDir);
- await copyFileGuarded(renderedPath, dest);
- // Join is by step, sourced from artifacts.samples — append so listRunCheckpoints
- // picks it up. updateRun's function form merges against the freshest record.
- await runsDb.updateRun(runId, (current) => {
- const samples = current.artifacts?.samples || [];
- const name = previewSampleName(step);
- if (samples.includes(name)) return current;
- return { ...current, artifacts: { ...current.artifacts, samples: [...samples, name] } };
+ // The copy and the row naming it are one backup-admitted publication (#9982);
+ // the render above stays outside the lease.
+ await withBackupAssetPublication(async () => {
+ await ensureDir(samplesDir);
+ await copyFileGuarded(renderedPath, dest);
+ // Join is by step, sourced from artifacts.samples — append so listRunCheckpoints
+ // picks it up. updateRun's function form merges against the freshest record.
+ await runsDb.updateRun(runId, (current) => {
+ const samples = current.artifacts?.samples || [];
+ const name = previewSampleName(step);
+ if (samples.includes(name)) return current;
+ return { ...current, artifacts: { ...current.artifacts, samples: [...samples, name] } };
+ });
});
trainingEvents.emit('checkpoint-preview', { generationId: run.jobId || runId, runId, step });
trainingEvents.emit('checkpoints:changed', { runId });
diff --git a/server/services/loras.js b/server/services/loras.js
index a8bf3f88c2..db58233ca7 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -29,6 +29,7 @@ import {
siblingDownloadMeta,
streamResumableDownload,
} from '../lib/downloadPreflight.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, sha256File, PATHS, rmGuarded, unlinkGuarded } from '../lib/fileUtils.js';
import { verifySafetensorsStructure } from '../lib/hfCache.js';
import { isPlainObject } from '../lib/objects.js';
@@ -326,10 +327,13 @@ export const getLora = async (filename) => {
return lora;
};
+// Run, dataset and character rows can keep naming a deleted LoRA, so the
+// unlink holds backup admission: it waits out an open cut, and a cut waits out
+// an unlink in flight (#9982).
export const deleteLora = async (filename) => {
assertSafeLoraFilename(filename);
const filePath = join(PATHS.loras, filename);
- await queueSidecarWrite(filename, async () => {
+ await withBackupAssetPublication(() => queueSidecarWrite(filename, async () => {
if (!existsSync(filePath)) {
throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
}
@@ -356,7 +360,7 @@ export const deleteLora = async (filename) => {
throw modelRemovalError;
}
invalidateLoraMetadataCache(filename);
- });
+ }));
await recordModelUninstall({ backend: 'lora', key: filename });
console.log(`🗑️ Deleted LoRA: ${filename}`);
return { ok: true, filename };
@@ -385,7 +389,11 @@ const queueSidecarWrite = createKeyedFileWriteQueue();
// here rather than in each installer is what keeps a fourth one from arriving
// untracked — and a re-install over an existing filename keeps its original
// `installedAt`, so it does not read as newly downloaded.
-export const writeLoraSidecar = (filename, sidecar) => queueSidecarWrite(filename, async () => {
+//
+// The sidecar is the record that first names freshly installed or trained
+// weights, which are already on disk under their final name, so writing it is
+// the commit that takes backup admission (#9982).
+export const writeLoraSidecar = (filename, sidecar) => withBackupAssetPublication(() => queueSidecarWrite(filename, async () => {
const loraPath = join(PATHS.loras, filename);
if (!existsSync(loraPath)) {
throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
@@ -399,7 +407,7 @@ export const writeLoraSidecar = (filename, sidecar) => queueSidecarWrite(filenam
// HF one carries nothing, so the file itself is the only uniform source.
sizeBytes: await stat(loraPath).then((info) => info.size, () => null),
}));
-});
+}));
export const patchLoraSidecar = async (filename, patch) => {
assertSafeLoraFilename(filename);