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

address review (claude): derive canonical checkpoint step from filename; narrow promote gate

[._.]/ Adam Eivy2b5c3a7ea8a2
diff --git a/server/services/loraTraining/checkpoints.js b/server/services/loraTraining/checkpoints.js
index 37a20fa317..9b547a72bd 100644
--- a/server/services/loraTraining/checkpoints.js
+++ b/server/services/loraTraining/checkpoints.js
@@ -67,6 +67,23 @@ function stepFromSampleName(name) {
return m ? Number(m[1]) : null;
}
+/**
+ * Parse the boundary step a checkpoint artifact was saved at, from its
+ * basename. The mflux watcher tags its CHECKPOINT line with the POLL-TIME
+ * tqdm step, which can lag the actual save boundary by a few steps — so the
+ * recorded `step` may not match the boundary the preview filename embeds.
+ * Deriving the step from the filename (the same source `stepFromSampleName`
+ * uses) keeps the checkpoint↔preview join exact. Returns null if unparseable.
+ */
+function stepFromCheckpointName(name) {
+ // mflux: 0000250_checkpoint.zip ; flux2: step-000250
+ const m = String(name).match(/^(\d+)_checkpoint/) || String(name).match(/^step-(\d+)/);
+ return m ? Number(m[1]) : null;
+}
+
+/** Canonical (filename-derived) step for a recorded checkpoint, with fallback. */
+const checkpointStep = (c) => stepFromCheckpointName(c.path) ?? c.step;
+
/** Map step → sample basename from the run's recorded sample artifacts. */
function sampleByStep(run) {
const map = new Map();
@@ -90,13 +107,14 @@ export function listRunCheckpoints(run) {
const deployedStep = run.output?.selectedCheckpointStep ?? null;
const checkpoints = (run.artifacts?.checkpoints || [])
.map((c) => {
- const preview = samples.get(c.step) || null;
+ const step = checkpointStep(c);
+ const preview = samples.get(step) || null;
return {
- step: c.step,
+ step,
loss: Number.isFinite(c.loss) ? c.loss : null,
previewUrl: sampleUrl(run.id, preview),
hasPreview: !!preview,
- deployed: deployedStep != null && c.step === deployedStep,
+ deployed: deployedStep != null && step === deployedStep,
};
})
.sort((a, b) => a.step - b.step);
@@ -132,8 +150,11 @@ const pad6 = (n) => String(n).padStart(6, '0');
* Throws a clear error if the checkpoint artifact is missing.
*/
export async function resolveCheckpointAdapterBuffer(run, step) {
+ // Match on the canonical (filename-derived) step so a promote request from
+ // listRunCheckpoints — which reports filename steps — finds the right
+ // artifact even when the recorded poll-time `step` drifted.
if (run.runtime === TRAINING_RUNTIMES.MFLUX) {
- const recorded = (run.artifacts?.checkpoints || []).find((c) => c.step === step);
+ const recorded = (run.artifacts?.checkpoints || []).find((c) => checkpointStep(c) === step);
const zipName = recorded?.path || `${pad7(step)}_checkpoint.zip`;
const zipPath = join(resolveMfluxOutputDir(run.id), 'checkpoints', basename(zipName));
if (!existsSync(zipPath)) {
@@ -149,7 +170,7 @@ export async function resolveCheckpointAdapterBuffer(run, step) {
// flux2 torch runtime — diffusers save_lora_weights dir. Prefer the recorded
// checkpoint basename (symmetric with the mflux path) so a trainer naming
// change can't silently break resolution; fall back to the derived name.
- const recorded = (run.artifacts?.checkpoints || []).find((c) => c.step === step);
+ const recorded = (run.artifacts?.checkpoints || []).find((c) => checkpointStep(c) === step);
const dirName = recorded?.path ? basename(recorded.path) : `step-${pad6(step)}`;
const file = join(runDirFor(run.id), 'checkpoints', dirName, 'pytorch_lora_weights.safetensors');
if (!existsSync(file)) {
@@ -171,16 +192,22 @@ export async function resolveCheckpointAdapterBuffer(run, step) {
*/
export async function selectDeployableCheckpoint(run, finalAdapterPath, finalStep) {
const samples = sampleByStep(run);
- const withPreview = listRunCheckpoints(run).filter((c) => c.hasPreview);
+ const all = listRunCheckpoints(run);
+ const withPreview = all.filter((c) => c.hasPreview);
+ // The step to record as "deployed" is the newest recorded checkpoint (the
+ // one `finalAdapterPath` was extracted from), NOT the trainer's raw end-step
+ // counter — using a listed checkpoint's step keeps the picker's deployed flag
+ // accurate. Fall back to finalStep when no checkpoints were recorded.
+ const finalCkptStep = all.length ? all[all.length - 1].step : finalStep;
// Health proxy for the final adapter: its own preview, or — since mflux
// saves the final checkpoint a few steps PAST the last sampled step, so the
// final usually has no preview of its own — the most recent preview.
const latest = withPreview.length ? withPreview[withPreview.length - 1] : null;
- const finalPreviewName = samples.get(finalStep) || (latest ? samples.get(latest.step) : null);
+ const finalPreviewName = samples.get(finalCkptStep) || (latest ? samples.get(latest.step) : null);
const readFinal = async (reason = null) => ({
buffer: await readFile(finalAdapterPath),
- step: finalStep,
+ step: finalCkptStep,
previewUrl: sampleUrl(run.id, finalPreviewName),
autoSelected: false,
reason,
@@ -194,7 +221,7 @@ export async function selectDeployableCheckpoint(run, finalAdapterPath, finalSte
// Final diverged. Walk earlier checkpoints newest→oldest for a healthy one.
const earlier = withPreview
- .filter((c) => c.step < finalStep)
+ .filter((c) => c.step < finalCkptStep)
.sort((a, b) => b.step - a.step);
for (const cand of earlier) {
const previewName = samples.get(cand.step);
@@ -212,5 +239,5 @@ export async function selectDeployableCheckpoint(run, finalAdapterPath, finalSte
}
// Every preview collapsed (or no earlier adapter recoverable) — keep final
// so the run still registers a (flawed) LoRA the user can inspect/replace.
- return readFinal(`all previews collapsed — kept final step ${finalStep}`);
+ return readFinal(`all previews collapsed — kept final step ${finalCkptStep}`);
}
diff --git a/server/services/loraTraining/checkpoints.test.js b/server/services/loraTraining/checkpoints.test.js
index 046afa40de..db10d32897 100644
--- a/server/services/loraTraining/checkpoints.test.js
+++ b/server/services/loraTraining/checkpoints.test.js
@@ -118,6 +118,31 @@ describe('loraTraining/checkpoints', () => {
expect(list[1].deployed).toBe(false);
});
+ it('joins preview by the filename-derived step even when the recorded step drifted', async () => {
+ // mflux tags the CHECKPOINT line with the poll-time tqdm step, which can
+ // lag the save boundary — here the record says 252/502 but the zip names
+ // (and previews) are at 250/500. The join must use the filename step.
+ const run = buildRun({
+ artifacts: {
+ checkpoints: [
+ { step: 252, path: '0000250_checkpoint.zip', loss: 0.64 },
+ { step: 502, path: '0000500_checkpoint.zip', loss: 0.53 },
+ ],
+ samples: [
+ '0000250_preview_image_preview_1.png',
+ '0000500_preview_image_preview_1.png',
+ ],
+ },
+ output: { selectedCheckpointStep: 250, loraFilename: 'lora-x.safetensors' },
+ });
+ const list = listRunCheckpoints(run);
+ expect(list.map((c) => c.step)).toEqual([250, 500]); // canonical, not 252/502
+ expect(list.every((c) => c.hasPreview)).toBe(true);
+ expect(list[0].deployed).toBe(true); // selectedCheckpointStep 250 matches
+ // And the adapter resolves by that canonical step despite the drifted record.
+ expect((await resolveCheckpointAdapterBuffer(run, 250)).toString()).toBe(ADAPTER_250.toString());
+ });
+
it('flags a black preview as collapsed and a noisy one as healthy', async () => {
expect(await isPreviewCollapsed(join(runDir, 'samples', '0000500_preview_image_preview_1.png'))).toBe(true);
expect(await isPreviewCollapsed(join(runDir, 'samples', '0000250_preview_image_preview_1.png'))).toBe(false);
@@ -143,9 +168,15 @@ describe('loraTraining/checkpoints', () => {
expect(sel.reason).toMatch(/collapsed/);
});
- it('guard: keeps the final adapter when its preview is healthy', async () => {
- // finalStep 250 has the noisy (healthy) preview → no override.
- const sel = await selectDeployableCheckpoint(buildRun(), finalAdapterPath, 250);
+ it('guard: keeps the final adapter when its (latest checkpoint) preview is healthy', async () => {
+ // Latest checkpoint is 250 with the noisy (healthy) preview → no override.
+ const run = buildRun({
+ artifacts: {
+ checkpoints: [{ step: 250, path: '0000250_checkpoint.zip', loss: 0.64 }],
+ samples: ['0000250_preview_image_preview_1.png'],
+ },
+ });
+ const sel = await selectDeployableCheckpoint(run, finalAdapterPath, 250);
expect(sel.autoSelected).toBe(false);
expect(sel.step).toBe(250);
expect(sel.buffer.toString()).toBe(ADAPTER_500.toString()); // returns the on-disk final adapter as-is
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 6efc8d9444..957e091eda 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -561,9 +561,12 @@ export async function listCheckpoints(runId) {
*/
export async function promoteCheckpoint(runId, step) {
const run = await runsDb.getRunRequired(runId);
- if (!['completed', 'failed', 'canceled'].includes(run.status)) {
- throw new ServerError('Cannot promote a checkpoint while the run is active', {
- status: 409, code: 'RUN_ACTIVE',
+ // Only completed runs (matching the UI, which exposes the picker only there).
+ // Promoting flips the dataset to `trained` + deploys a LoRA — a failed or
+ // canceled run shouldn't masquerade as trained off a partial checkpoint.
+ if (run.status !== 'completed') {
+ throw new ServerError('Can only promote a checkpoint from a completed run', {
+ status: 409, code: 'RUN_NOT_COMPLETED',
});
}
const listed = listRunCheckpoints(run);