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: bound the LoRA effect probe's stall and stop it lying about a missing file (#4872)

[._.]/ Adam Eivy74dd74f87254
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index f0e486a568..91bef12c13 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -254,6 +254,15 @@ export default function Loras() {
.finally(() => { setInstallingVideoKey(null); setHfProgress(null); });
}, [installingVideoKey, hfInstalling, refresh]);
+ // The measurement lives in the LIST, not in the card. The Installed section
+ // swaps between LoraGrid and InstalledGroups when the media filter changes,
+ // which unmounts every card — a badge held only in card state would vanish
+ // right after the user ran the check. The server has cached the same report in
+ // the sidecar, so this just keeps the page consistent without a refetch.
+ const handleMeasured = useCallback((filename, effectReport) => {
+ setLoras((prev) => prev.map((l) => (l.filename === filename ? { ...l, effectReport } : l)));
+ }, []);
+
const handleDelete = async (filename) => {
setDeleting(filename);
await deleteLoraFull(filename, { silent: true })
@@ -458,8 +467,8 @@ export default function Loras() {
render it flat. */}
{visibleLoras.length > 0 && (
mediaFilter === 'all'
- ? <InstalledGroups loras={visibleLoras} deleting={deleting} onDelete={handleDelete} deleteConfirm={deleteConfirm} />
- : <LoraGrid loras={visibleLoras} deleting={deleting} onDelete={handleDelete} deleteConfirm={deleteConfirm} />
+ ? <InstalledGroups loras={visibleLoras} deleting={deleting} onDelete={handleDelete} onMeasured={handleMeasured} deleteConfirm={deleteConfirm} />
+ : <LoraGrid loras={visibleLoras} deleting={deleting} onDelete={handleDelete} onMeasured={handleMeasured} deleteConfirm={deleteConfirm} />
)}
</div>
</div>
@@ -1062,7 +1071,7 @@ function CivitaiAuthModal({ pendingUrl, message, auth, onClose, onSaved, onRetry
// Responsive grid of installed LoRA cards. Extracted so the Installed section
// can render either one flat grid (filtered view) or several grouped grids
// (the "All" view) without duplicating the grid markup.
-function LoraGrid({ loras, deleting, onDelete, deleteConfirm }) {
+function LoraGrid({ loras, deleting, onDelete, onMeasured, deleteConfirm }) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
{loras.map((lora) => (
@@ -1070,6 +1079,7 @@ function LoraGrid({ loras, deleting, onDelete, deleteConfirm }) {
key={lora.filename}
lora={lora}
onDelete={() => onDelete(lora.filename)}
+ onMeasured={onMeasured}
deleting={deleting === lora.filename}
deleteConfirm={deleteConfirm}
/>
@@ -1082,7 +1092,7 @@ function LoraGrid({ loras, deleting, onDelete, deleteConfirm }) {
// with a labeled header mirroring the suggestion panel's grouping. Empty groups
// are omitted. Video is listed first (fewer, and the source of the layout
// confusion this grouping resolves).
-function InstalledGroups({ loras, deleting, onDelete, deleteConfirm }) {
+function InstalledGroups({ loras, deleting, onDelete, onMeasured, deleteConfirm }) {
const video = loras.filter((l) => isVideoLoraFamily(l.runnerFamily));
const image = loras.filter((l) => !isVideoLoraFamily(l.runnerFamily));
const groups = [
@@ -1097,14 +1107,14 @@ function InstalledGroups({ loras, deleting, onDelete, deleteConfirm }) {
<h3 className="text-sm font-medium text-gray-300">{g.label}</h3>
<span className="text-xs text-gray-600">{g.items.length}</span>
</div>
- <LoraGrid loras={g.items} deleting={deleting} onDelete={onDelete} deleteConfirm={deleteConfirm} />
+ <LoraGrid loras={g.items} deleting={deleting} onDelete={onDelete} onMeasured={onMeasured} deleteConfirm={deleteConfirm} />
</div>
))}
</div>
);
}
-function LoraCard({ lora, onDelete, deleting, deleteConfirm }) {
+function LoraCard({ lora, onDelete, onMeasured, deleting, deleteConfirm }) {
const family = lora.runnerFamily;
const familyLabel = family ? (RUNNER_LABEL[family] || family) : 'Unsupported base';
const badgeClass = family ? (RUNNER_BADGE_CLASS[family] || 'bg-gray-600/20 text-gray-300 border-gray-500/30') : 'bg-port-warning/20 text-port-warning border-port-warning/30';
@@ -1125,17 +1135,17 @@ function LoraCard({ lora, onDelete, deleting, deleteConfirm }) {
// and "Delete undefined" is a bad thing to announce over a destructive action.
const displayName = lora.name || lora.filename;
- // Seeded from the server's CACHED report (listLoras never probes), then
- // replaced in place by an explicit re-check so the card reflects the new
- // measurement without a full refresh.
- const [effect, setEffect] = useState(lora.effectReport || null);
+ // Read straight off the server's CACHED report (listLoras never probes) — an
+ // explicit re-check hands the new one to `onMeasured`, which updates the list
+ // entry, so the badge survives this card being unmounted by a filter change.
+ const effect = lora.effectReport || null;
const [checkingEffect, setCheckingEffect] = useState(false);
const effectSummary = formatLoraEffect(effect);
const runEffectCheck = async () => {
setCheckingEffect(true);
await probeLoraEffect(lora.filename, { force: true, silent: true })
.then((report) => {
- setEffect(report);
+ onMeasured?.(lora.filename, report);
const summary = formatLoraEffect(report);
if (report?.status === LORA_EFFECT_STATUSES.ZERO) {
toast.error(`${displayName} has no measurable effect — a render would look as if it were off`);
diff --git a/server/lib/loraEffect.parity.test.js b/server/lib/loraEffect.parity.test.js
index d36ea2bcf4..2e8e9d7d81 100644
--- a/server/lib/loraEffect.parity.test.js
+++ b/server/lib/loraEffect.parity.test.js
@@ -13,7 +13,10 @@
*/
import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join } from 'path';
import {
+ LORA_EFFECT_PROBE_VERSION,
LORA_EFFECT_STATUSES as SERVER_STATUSES,
formatLoraEffect as serverFormat,
loraEffectIssue,
@@ -41,6 +44,28 @@ const REPORTS = [
{ status: 'ok', measured: 3, medianRms: null, maxRms: 0.2, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null },
];
+describe('loraEffect parity — JS vs the Python probe', () => {
+ it('keeps LORA_EFFECT_PROBE_VERSION in lockstep with PROBE_VERSION', () => {
+ // Drift here fails silently and expensively: every freshly written report
+ // reads as stale, so the sidecar cache stops working and each render
+ // re-reads the whole adapter with nothing logged anywhere.
+ const source = readFileSync(join(import.meta.dirname, '..', '..', 'scripts', 'lora_effect_probe.py'), 'utf-8');
+ const match = source.match(/^PROBE_VERSION = (\d+)$/m);
+ expect(match, 'scripts/lora_effect_probe.py must declare PROBE_VERSION').not.toBeNull();
+ expect(Number(match[1])).toBe(LORA_EFFECT_PROBE_VERSION);
+ });
+
+ it('agrees with the probe on the status vocabulary', () => {
+ const source = readFileSync(join(import.meta.dirname, '..', '..', 'scripts', 'lora_effect_probe.py'), 'utf-8');
+ // The probe's own docstring names the five it may emit; a status added on
+ // one side and not the other degrades to `unmeasurable` at normalization,
+ // which would quietly disable the verdict rather than fail.
+ for (const status of Object.values(SERVER_STATUSES)) {
+ expect(source, `probe never mentions status "${status}"`).toContain(status);
+ }
+ });
+});
+
describe('loraEffect parity — server vs client', () => {
it('mirrors the status vocabulary exactly', () => {
expect(CLIENT_STATUSES).toEqual(SERVER_STATUSES);
diff --git a/server/services/loraEffectProbe.js b/server/services/loraEffectProbe.js
index 27d0e60a29..47c9beb68d 100644
--- a/server/services/loraEffectProbe.js
+++ b/server/services/loraEffectProbe.js
@@ -20,8 +20,10 @@
* describes this machine's Python, not the adapter, and caching it would
* make a transient environment problem permanent.
*
- * 3. **Never fatal.** Every failure path — no interpreter, no numpy, spawn
+ * 3. **Never fatal.** Every PROBE failure — no interpreter, no numpy, spawn
* error, timeout, malformed output — resolves to an `unmeasurable` report.
+ * Two caller errors still throw, because they are not probe failures: an
+ * unsafe filename, and a LoRA that isn't on disk (a 404, as everywhere else).
* The diagnostic refuses a render only on a positive measurement of zero
* effect (`loraEffectIssue`), so a machine that cannot run the probe is a
* machine that renders exactly as it did before this existed.
@@ -31,6 +33,7 @@ import { existsSync } from 'fs';
import { stat } from 'fs/promises';
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
import { createSingleFlight } from '../lib/singleFlight.js';
import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';
import { withAbortTimeout } from '../lib/abortTimeout.js';
@@ -51,6 +54,10 @@ export const LORA_EFFECT_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'lora_effect
// bound is therefore sized to catch a wedged interpreter, NOT to cap a slow
// read — timing out a legitimate measurement would report 'unmeasurable' for
// exactly the largest adapters, where a wasted render costs the most.
+//
+// It is a budget for the WHOLE candidate walk, not per interpreter: this runs
+// inline ahead of a render, before the job even has an id to report progress
+// against, so N installed venvs must not be able to multiply the stall.
const PROBE_TIMEOUT_MS = 300_000;
const installedCandidates = (paths) => [
@@ -92,7 +99,11 @@ const unmeasurable = (reason) => normalizeLoraEffectReport({
// spawning a pile of interpreters against the same weights.
const inFlight = createSingleFlight();
-const runProbeOnce = async (bin, filePath) => {
+// Returns `{ report, timedOut }`. `timedOut` is what stops the candidate walk:
+// a timeout says the FILE is slow to read, which every interpreter would be
+// equally slow at, so retrying is guaranteed waste. Every other failure is about
+// this interpreter (no numpy, a broken venv) and is worth another candidate.
+const runProbeOnce = async (bin, filePath, budgetMs) => {
// try/catch is warranted here despite the repo's no-try/catch rule: this runs
// outside the Express lifecycle (a background render job awaits it), and
// runSidecarProcess only *models* failures as resolutions — the underlying
@@ -102,21 +113,30 @@ const runProbeOnce = async (bin, filePath) => {
// both settle paths.
let result;
try {
- result = await withAbortTimeout(PROBE_TIMEOUT_MS, (signal) => runSidecarProcess({
+ result = await withAbortTimeout(budgetMs, (signal) => runSidecarProcess({
bin,
args: [LORA_EFFECT_PROBE_SCRIPT, filePath],
signal,
}));
} catch (err) {
- return unmeasurable(`the effect probe could not be started (${err?.message || err})`);
+ return { report: unmeasurable(`the effect probe could not be started (${err?.message || err})`) };
}
// The probe prints RESULT: even when it exits non-zero (the missing-numpy
// case), so parse stdout before judging the exit — an exit code alone would
// throw away the reason the caller needs.
const parsed = parseSidecarResult(result.stdout);
- if (parsed) return normalizeLoraEffectReport(parsed);
- if (result.canceled) return unmeasurable(`the effect probe timed out after ${PROBE_TIMEOUT_MS / 1000}s`);
- return unmeasurable(`the effect probe produced no result (${result.reason || 'no output'})`);
+ // `parsed` is whatever JSON.parse produced, so a `RESULT:[1,2]` line is truthy
+ // but not a report; normalizeLoraEffectReport answers null for it and the
+ // caller needs the honest "no result" reason, not a null dereference.
+ const report = parsed ? normalizeLoraEffectReport(parsed) : null;
+ if (report) return { report };
+ if (result.canceled) {
+ return {
+ report: unmeasurable(`the effect probe ran out of its ${PROBE_TIMEOUT_MS / 1000}s budget reading this adapter`),
+ timedOut: true,
+ };
+ }
+ return { report: unmeasurable(`the effect probe produced no result (${result.reason || 'no output'})`) };
};
// The measurement proper — everything after the cache miss. Split out so the
@@ -131,16 +151,32 @@ const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs }) =>
// and this runs inline ahead of a render — say so, or the pause looks like a
// hang with nothing in the log.
console.log(`🔬 Measuring LoRA effect for ${filename} (${Math.round(sizeBytes / 1e6)} MB)`);
+ const deadline = Date.now() + PROBE_TIMEOUT_MS;
let last = null;
+ let timedOut = false;
for (const bin of candidates) {
- last = await runProbeOnce(bin, filePath);
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) { timedOut = true; break; }
+ ({ report: last, timedOut = false } = await runProbeOnce(bin, filePath, remaining));
// Only an unmeasurable verdict is worth another interpreter; every other
- // status is a real answer about the file and identical on any Python.
- if (last.status !== LORA_EFFECT_STATUSES.UNMEASURABLE) break;
+ // status is a real answer about the file and identical on any Python. A
+ // timeout stops the walk outright — see runProbeOnce.
+ if (timedOut || last.status !== LORA_EFFECT_STATUSES.UNMEASURABLE) break;
}
+ if (last === null) last = unmeasurable(`the effect probe ran out of its ${PROBE_TIMEOUT_MS / 1000}s budget reading this adapter`);
if (last.status === LORA_EFFECT_STATUSES.UNMEASURABLE) {
console.log(`⚠️ LoRA effect probe unavailable for ${filename}: ${last.reason || 'unknown'}`);
- return last;
+ // A timeout is cached, unlike every other unmeasurable verdict. The others
+ // describe this machine's Python — a venv the user may install in a minute,
+ // so freezing them in would make a transient problem permanent. A timeout
+ // instead describes the cost of READING THIS FILE on this storage, which is
+ // exactly what the size+mtime cache key already scopes. Without caching it,
+ // a pathologically slow adapter re-burns the full budget ahead of every
+ // single render, forever.
+ if (!timedOut) return last;
+ const timeoutReport = normalizeLoraEffectReport(last, { sizeBytes, mtimeMs, measuredAt: new Date().toISOString() });
+ await patchLoraSidecar(filename, { effectReport: timeoutReport }).catch(() => {});
+ return timeoutReport;
}
const report = normalizeLoraEffectReport(last, { sizeBytes, mtimeMs, measuredAt: new Date().toISOString() });
console.log(`🔬 LoRA effect ${filename}: ${report.status} (${report.measured}/${report.modules} modules)`);
@@ -164,7 +200,14 @@ export const probeLoraEffect = async (filename, { force = false } = {}) => {
const filePath = join(PATHS.loras, filename);
const fileStat = await stat(filePath).catch(() => null);
if (!fileStat || !fileStat.isFile()) {
- return unmeasurable(`LoRA "${filename}" is not a regular file on disk`);
+ // NOT a soft `unmeasurable`: that word is reserved for "this machine could
+ // not run the probe", and answering it here would tell the user their
+ // adapter is unmeasurable when it simply isn't there. A missing file is a
+ // caller-visible 404 exactly as it is for getLora/patch/delete, and it is
+ // outside the never-fatal contract for the same reason the filename
+ // assertion above is. `resolveVideoLoras` already proved the file exists
+ // before it probes, so the render path cannot reach this.
+ throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
}
// The cache key: both stamps come from the stat we already did, so verifying a
// stored report costs nothing and a same-size rewrite still invalidates it.
diff --git a/server/services/loraEffectProbe.test.js b/server/services/loraEffectProbe.test.js
index cde8ec3f36..dfe115b19e 100644
--- a/server/services/loraEffectProbe.test.js
+++ b/server/services/loraEffectProbe.test.js
@@ -195,7 +195,42 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
state.existing = new Set(['/venv/ltx2/bin/python3']);
const report = await probeLoraEffect('style.safetensors');
expect(report.status).toBe('unmeasurable');
- expect(report.reason).toMatch(/timed out/i);
+ expect(report.reason).toMatch(/budget/i);
+ });
+
+ it('stops the candidate walk on a timeout instead of paying the budget per interpreter', async () => {
+ // A timeout says the FILE is slow to read; every interpreter would be
+ // equally slow, so retrying multiplies an inline stall for nothing. This
+ // runs before generateVideo even mints a job id, so the UI shows nothing
+ // while it waits.
+ state.responses = [
+ { ok: false, canceled: true, reason: 'cancelled (SIGTERM)', stdout: '' },
+ { ok: true, stdout: resultLine(OK_PAYLOAD) },
+ ];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs).toHaveLength(1);
+ expect(report.status).toBe('unmeasurable');
+ });
+
+ it('CACHES a timeout, so a pathologically slow adapter stalls one render and not every one', async () => {
+ // Unlike the other unmeasurable verdicts (which describe this machine's
+ // Python and may fix themselves the moment a venv installs), a timeout
+ // describes what reading THIS file costs on THIS storage — exactly what the
+ // size+mtime key already scopes.
+ state.responses = [{ ok: false, canceled: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
+ await probeLoraEffect('style.safetensors');
+ expect(state.patched).toHaveLength(1);
+ expect(state.patched[0].patch.effectReport).toMatchObject({ status: 'unmeasurable', sizeBytes: 4096 });
+ });
+
+ it('does NOT cache an unmeasurable that is only about this machine', async () => {
+ state.responses = [
+ { ok: false, reason: 'exit 3', stdout: resultLine({ status: 'unmeasurable', reason: 'numpy is not installed' }) },
+ { ok: false, reason: 'exit 3', stdout: resultLine({ status: 'unmeasurable', reason: 'numpy is not installed' }) },
+ { ok: false, reason: 'exit 3', stdout: resultLine({ status: 'unmeasurable', reason: 'numpy is not installed' }) },
+ ];
+ await probeLoraEffect('style.safetensors');
+ expect(state.patched).toHaveLength(0);
});
it('reports unmeasurable for malformed probe output instead of a hollow verdict', async () => {
@@ -205,18 +240,33 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
expect(report.status).toBe('unmeasurable');
});
+ it('survives well-formed JSON that is not a report object', async () => {
+ // `RESULT:[1,2]` parses fine and is truthy, but normalizes to null — a
+ // caller that only checked truthiness would dereference it.
+ for (const line of ['RESULT:[1,2]\n', 'RESULT:"nope"\n', 'RESULT:null\n', 'RESULT:7\n']) {
+ state.existing = new Set(['/venv/ltx2/bin/python3']);
+ state.responses = [{ ok: true, stdout: line }];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(report.status).toBe('unmeasurable');
+ expect(report.reason).toMatch(/produced no result/i);
+ }
+ });
+
it('still returns the measurement when the sidecar cache write fails', async () => {
state.patchThrows = true;
state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
await expect(probeLoraEffect('style.safetensors')).resolves.toMatchObject({ status: 'ok' });
});
- it('reports unmeasurable — not a verdict — when the LoRA is missing or not a regular file', async () => {
+ it('404s for a missing or non-regular LoRA rather than calling it unmeasurable', async () => {
+ // "unmeasurable" means this machine could not run the probe. Saying it about
+ // a file that isn't there would tell the user their adapter is unmeasurable
+ // when it simply does not exist — and every sibling route 404s.
state.statThrows = true;
- await expect(probeLoraEffect('gone.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
+ await expect(probeLoraEffect('gone.safetensors')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
state.statThrows = false;
state.statResult = { size: 0, mtimeMs: 0, isFile: () => false };
- await expect(probeLoraEffect('dir.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
+ await expect(probeLoraEffect('dir.safetensors')).rejects.toMatchObject({ status: 404 });
expect(state.runs).toHaveLength(0);
});