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: stop an external kill, a 4-LoRA batch, or a DoRA tensor from misreporting a LoRA (#4872)

[._.]/ Adam Eivy5a1a800860b8
diff --git a/scripts/lora_effect_probe.py b/scripts/lora_effect_probe.py
index 57ce27c548..af32edfc9d 100644
--- a/scripts/lora_effect_probe.py
+++ b/scripts/lora_effect_probe.py
@@ -90,6 +90,26 @@ EXIT_NO_NUMPY = 3
_DOWN_SUFFIXES = ("lora_a.weight", "lora_down.weight", "lora_a", "lora_down")
_UP_SUFFIXES = ("lora_b.weight", "lora_up.weight", "lora_b", "lora_up")
+# Adapter tensors that carry real effect but are NOT a low-rank pair this probe
+# can multiply out: DoRA magnitude vectors, LyCORIS Hadamard/Kronecker factors,
+# orthogonal fine-tuning blocks, and kohya's full-rank `.diff` deltas.
+#
+# They exist only so the `zero` verdict stays honest. `zero` refuses a render on
+# the claim that the adapter is PROVABLY inert — but a hybrid file whose lora_A/
+# lora_B pairs are zeroed while its effect rides on one of these would otherwise
+# look entirely-zero, because tensors that never enter pair_lora_modules are
+# neither measured NOR counted as skipped. Counting them makes the file report
+# `ok` with a skip count, which is the truthful answer: we could not measure all
+# of it.
+_UNMEASURABLE_ADAPTER_MARKERS = (
+ "lora_magnitude_vector",
+ "hada_w",
+ "lokr_",
+ "oft_",
+ "boft_",
+ ".diff",
+)
+
# dtype tag -> (numpy dtype string, bytes per element). BF16 has no numpy dtype;
# it is widened to float32 by shifting the 16 stored bits into the high half of
# a float32, which is exact (bfloat16 IS the top half of a float32).
@@ -144,7 +164,7 @@ def _split_suffix(name: str) -> tuple[str, str] | None:
return None
-def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
+def pair_lora_modules(header: dict) -> tuple[dict[str, dict[str, str]], int]:
"""Group tensor names into ``{module: {'down': name, 'up': name, 'alpha': name}}``.
Covers every layout PortOS classifies: bare and ComfyUI files name the pair
@@ -152,6 +172,10 @@ def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
ships a companion ``alpha`` scalar. The diagnostic deliberately measures
layouts the LTX-2 loader cannot fuse too — "this adapter is dead" is worth
knowing about a kohya file the user is about to re-export.
+
+ Also returns a count of adapter tensors it could NOT pair: an incomplete pair,
+ or one of the _UNMEASURABLE_ADAPTER_MARKERS families. See that constant for
+ why the count matters to the `zero` verdict.
"""
modules: dict[str, dict[str, str]] = {}
for name in header:
@@ -169,7 +193,13 @@ def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
prefix, role = split
modules.setdefault(prefix, {})[role] = name
# Only complete pairs are measurable; a lone lora_A carries no delta.
- return {k: v for k, v in modules.items() if "down" in v and "up" in v}
+ complete = {k: v for k, v in modules.items() if "down" in v and "up" in v}
+ unpairable = len(modules) - len(complete)
+ for name in header:
+ lowered = name.lower()
+ if any(marker in lowered for marker in _UNMEASURABLE_ADAPTER_MARKERS):
+ unpairable += 1
+ return complete, unpairable
def _read_tensor(np, handle, payload_offset: int, desc, file_size: int, *, allow_scalar: bool = False):
@@ -306,8 +336,9 @@ def measure_lora_effect(path) -> dict:
report["reason"] = f"{path.name} is not a readable safetensors file"
return report
- modules = pair_lora_modules(header)
+ modules, unpairable = pair_lora_modules(header)
report["modules"] = len(modules)
+ report["skippedUnsupported"] = unpairable
if not modules:
report["reason"] = f"{path.name} contains no lora_A/lora_B (or lora_down/lora_up) pairs"
return report
diff --git a/scripts/lora_effect_probe_test.py b/scripts/lora_effect_probe_test.py
index 11307e2d98..4746d878a0 100644
--- a/scripts/lora_effect_probe_test.py
+++ b/scripts/lora_effect_probe_test.py
@@ -96,13 +96,14 @@ def run(tmp):
check("read_header refuses an absurd header length", read_header(absurd) == (None, 0))
# --- pairing ------------------------------------------------------------
- paired = pair_lora_modules({
+ paired, unpairable = pair_lora_modules({
"m.lora_A.weight": {}, "m.lora_B.weight": {},
"k.lora_down.weight": {}, "k.lora_up.weight": {}, "k.alpha": {},
"lonely.lora_A.weight": {},
"__metadata__": {},
})
check("pairs bare and kohya modules, drops the unpaired one", sorted(paired) == ["k", "m"])
+ check("the unpaired module is COUNTED, not silently dropped", unpairable == 1)
check("kohya alpha is attached to its module", paired["k"].get("alpha") == "k.alpha")
# --- a healthy adapter --------------------------------------------------
@@ -266,6 +267,26 @@ def run(tmp):
check("a tiny-but-real adapter is ok, never underflowed into a zero refusal",
report["status"] == "ok" and report["maxRms"] > 0)
+ # A hybrid adapter whose lora pairs are zeroed but whose effect rides on a
+ # DoRA/LyCORIS tensor we cannot multiply out must NOT be refused: `zero`
+ # claims the adapter is provably inert, and we did not measure all of it.
+ hybrid = tmp / "hybrid_dora.safetensors"
+ write_safetensors(hybrid, {
+ **bare_pair("m", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ "m.lora_magnitude_vector": np.full((64,), 1.5, np.float32),
+ })
+ report = measure_lora_effect(hybrid)
+ check("a zeroed pair beside an unmeasurable DoRA tensor does not refuse",
+ report["status"] == "ok" and report["skippedUnsupported"] == 1)
+
+ lycoris = tmp / "hybrid_lycoris.safetensors"
+ write_safetensors(lycoris, {
+ **bare_pair("m", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ "m.hada_w1_a": np.ones((4, 4), np.float32),
+ })
+ check("a LyCORIS Hadamard factor also blocks the zero refusal",
+ measure_lora_effect(lycoris)["status"] == "ok")
+
# --- kohya alpha edge cases ---------------------------------------------
neg_alpha = tmp / "kohya_negative_alpha.safetensors"
write_safetensors(neg_alpha, {
diff --git a/server/lib/README.md b/server/lib/README.md
index b224289a35..6ef515a83a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). |
| `multipart.js` | Streaming multipart/form-data parser. |
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. `classifyLoraKeyLayoutFromHeader(header)` / `classifyLoraKeyLayout(path)` classify the key layout as `LORA_KEY_LAYOUTS` (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`, `null` = unreadable), `isKnownLoraKeyLayout(layout)` validates a layout read back out of persisted state, and `videoLoraLayoutIssue(layout)` returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or `null` when it can). |
-| `loraEffect.js` | LoRA adapter-effect report rules — the JS half of the `scripts/lora_effect_probe.py` diagnostic (#4872), mirrored to the client by `client/src/lib/loraEffect.js` and pinned by `loraEffect.parity.test.js`. `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`) + `isKnownLoraEffectStatus`; `normalizeLoraEffectReport(raw,{sizeBytes,measuredAt})` coerces every non-finite number to `null` and drops statistics when nothing was measured, so "no data" can never read as "measured 0.0"; `readCachedLoraEffectReport(raw,sizeBytes)` returns a stored report only while its probe version and file size still match, which is what lets `listLoras()` surface one without ever spawning a probe; `loraEffectIssue(report)` is the user-facing refusal phrase for a measured entirely-zero adapter and `null` for EVERY other status; `formatLoraEffect(report)` is the one-line log/UI summary. |
+| `loraEffect.js` | LoRA adapter-effect report rules — the JS half of the `scripts/lora_effect_probe.py` diagnostic (#4872), mirrored to the client by `client/src/lib/loraEffect.js` and pinned by `loraEffect.parity.test.js` (which also holds `LORA_EFFECT_PROBE_VERSION` in lockstep with the probe`s `PROBE_VERSION` — drift silently disables the cache). `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`) + `isKnownLoraEffectStatus`; `normalizeLoraEffectReport(raw,{sizeBytes,mtimeMs,measuredAt})` coerces every non-finite number to `null`, drops statistics when nothing was measured so "no data" can never read as "measured 0.0", and downgrades a `zero` status that no measurement backs; `readCachedLoraEffectReport(raw,{sizeBytes,mtimeMs})` returns a stored report only while its probe version, file size AND mtime all still match, which is what lets `listLoras()` surface one without ever spawning a probe; `loraEffectIssue(report)` is the user-facing refusal phrase for a measured entirely-zero adapter and `null` for EVERY other status; `formatLoraEffect(report)` is the one-line log/UI summary. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
| `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `collectZipEntry(entry, maxBytes?)` buffers one `parseZip` entry into a Buffer (size-capped); `collectZipEntries(path, { match, onMatch, maxBytes? })` owns the multi-entry import lifecycle (teardown, autodrain, per-entry await) leaving callers only match/parse; `isZipUpload(file)` predicate for an uploaded ZIP; `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |
| `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. |
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index c9604b38f9..af64ad828d 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -538,13 +538,15 @@ export const HF_HUB_PYTHON_RESOLVERS = Object.freeze([
// The LTX-2.x video venvs are deliberately NOT here — their paths are owned by
// services/videoGen/runtimes.js, and lib/ must not import from services/. The
// probe prepends them itself; this list is everything pythonSetup can see.
-// NOTE the mflux entry resolves the venv PATH directly rather than going through
+// NOTE the mflux entries resolve venv PATHS directly rather than going through
// `resolveMfluxPython`: that resolver answers "which interpreter can run
// mflux-train", so it returns null on an mflux install without the trainer
-// package — an interpreter that has numpy and would have measured fine.
+// package — an interpreter that has numpy and would have measured fine. Both
+// candidates are listed, not just the default, because an install provisioned
+// under data/python/ is exactly as capable as one under ~/.portos/.
export const NUMPY_PYTHON_RESOLVERS = Object.freeze([
resolveFlux2Python,
- () => MFLUX_VENV_DEFAULT,
+ ...MFLUX_VENV_CANDIDATES.map((path) => () => path),
...HF_HUB_PYTHON_RESOLVERS,
]);
diff --git a/server/services/loraEffectProbe.js b/server/services/loraEffectProbe.js
index a71b703b11..fc0f552aad 100644
--- a/server/services/loraEffectProbe.js
+++ b/server/services/loraEffectProbe.js
@@ -13,12 +13,16 @@
* route or from the render path that is about to spend GPU minutes on the
* adapter — both of which are a user asking for the answer.
*
- * 2. **Cached in the sidecar, keyed by file size + probe version.** A LoRA is
- * measured once; every later render and every library page reads the stored
- * report for free. Replacing the file (different size) or bumping the probe
- * re-measures. An `unmeasurable` result is deliberately NOT cached — it
- * describes this machine's Python, not the adapter, and caching it would
- * make a transient environment problem permanent.
+ * 2. **Cached in the sidecar, keyed by probe version + file size + mtime.** A
+ * LoRA is measured once; every later render and every library page reads the
+ * stored report for free. Bumping the probe, or any rewrite of the file
+ * (including a same-size one), re-measures. An `unmeasurable` result is
+ * deliberately NOT cached — it describes this machine's Python, not the
+ * adapter, and caching it would make a transient environment problem
+ * permanent. The ONE exception is our own timeout: that describes what
+ * reading this file costs on this storage, which is what the key already
+ * scopes, and without caching it a slow adapter re-burns the budget before
+ * every render.
*
* 3. **Never fatal.** Every PROBE failure — no interpreter, no numpy, spawn
* error, timeout, malformed output — resolves to an `unmeasurable` report.
@@ -60,7 +64,8 @@ export const LORA_EFFECT_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'lora_effect
// 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;
+export const LORA_EFFECT_PROBE_BUDGET_MS = 300_000;
+const PROBE_TIMEOUT_MS = LORA_EFFECT_PROBE_BUDGET_MS;
const installedCandidates = (paths) => [
...new Set(paths.filter((p) => typeof p === 'string' && p && existsSync(p))),
@@ -133,9 +138,16 @@ const runProbeOnce = async (bin, filePath, budgetMs) => {
// forever. Hold the handle and escalate to SIGKILL, as every other
// runSidecarProcess caller does.
let child = null;
+ // OUR timeout, specifically. `result.canceled` is set for ANY SIGTERM/SIGKILL
+ // death of the child — an OOM kill, a stray pkill, a process-group signal
+ // during shutdown — and only our own budget expiring may be reported as (and
+ // cached as) a timeout. Reading them as the same thing would permanently badge
+ // an adapter "Not measurable" because something unrelated killed one probe.
+ let didTimeout = false;
try {
result = await withAbortTimeout(budgetMs, (signal) => {
signal.addEventListener('abort', () => {
+ didTimeout = true;
if (child) killWithEscalation(child, { label: 'LoRA effect probe', stillRunning: () => true });
}, { once: true });
return runSidecarProcess({
@@ -157,8 +169,11 @@ const runProbeOnce = async (bin, filePath, budgetMs) => {
// caller needs the honest "no result" reason, not a null dereference.
const report = parsed ? normalizeLoraEffectReport(parsed) : null;
if (report) return { report };
+ if (didTimeout) return { report: timeoutReport(), timedOut: true };
if (result.canceled) {
- return { report: timeoutReport(), timedOut: true };
+ // Killed by something that isn't us — report it honestly and let the walk
+ // try another interpreter; nothing about the adapter has been learned.
+ return { report: unmeasurable(`the effect probe was killed (${result.reason || 'signal'})`) };
}
return { report: unmeasurable(`the effect probe produced no result (${result.reason || 'no output'})`) };
};
@@ -166,7 +181,7 @@ const runProbeOnce = async (bin, filePath, budgetMs) => {
// The measurement proper — everything after the cache miss. Split out so the
// never-fatal guarantee is one `.catch` at the single call site below rather
// than a defensive wrapper around each step.
-const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs }) => {
+const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs, deadline }) => {
const candidates = await probeInterpreterCandidates();
if (!candidates.length) {
return unmeasurable('no Python interpreter with numpy is installed — set up a Video Gen or Image Gen runtime first');
@@ -175,7 +190,6 @@ 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) {
@@ -205,9 +219,12 @@ const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs }) =>
// 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;
+ // NOT named `timeoutReport`: that is a module-level helper, and shadowing it
+ // here would turn any future call to it earlier in this block into a TDZ
+ // ReferenceError rather than the helper.
+ const cachedTimeout = normalizeLoraEffectReport(last, { sizeBytes, mtimeMs, measuredAt: new Date().toISOString() });
+ await patchLoraSidecar(filename, { effectReport: cachedTimeout }).catch(() => {});
+ return cachedTimeout;
}
const report = normalizeLoraEffectReport(last, { sizeBytes, mtimeMs, measuredAt: new Date().toISOString() });
console.log(`🔬 LoRA effect ${filename}: ${report.status} (${report.measured}/${report.modules} modules)`);
@@ -225,8 +242,12 @@ const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs }) =>
* Returns a normalized report (never throws for a probe failure — see the
* module header). `force: true` re-measures even when a fresh cached report
* exists, which is what the manager's explicit re-check button passes.
+ *
+ * `deadline` (an epoch ms) lets a caller measuring SEVERAL adapters share one
+ * budget across all of them. Without it a 4-LoRA render could stall for four
+ * full budgets back to back, before the job even has an id to report against.
*/
-export const probeLoraEffect = async (filename, { force = false } = {}) => {
+export const probeLoraEffect = async (filename, { force = false, deadline = null } = {}) => {
assertSafeLoraFilename(filename);
const filePath = join(PATHS.loras, filename);
const fileStat = await stat(filePath).catch(() => null);
@@ -254,7 +275,12 @@ export const probeLoraEffect = async (filename, { force = false } = {}) => {
// rejects in an unmodelled way, anything. `assertSafeLoraFilename` above is
// deliberately OUTSIDE it — a path-traversal attempt is a caller bug that
// must still surface as a 400, not be swallowed into a soft verdict.
- return inFlight.run(filePath, () => measureLoraEffect(filename, filePath, stamps)
+ // A caller-supplied deadline can only ever SHORTEN the budget — it is a
+ // shared allowance, not a way to ask for more time than the probe permits.
+ const ownDeadline = Date.now() + PROBE_TIMEOUT_MS;
+ const effectiveDeadline = deadline == null ? ownDeadline : Math.min(deadline, ownDeadline);
+
+ return inFlight.run(filePath, () => measureLoraEffect(filename, filePath, { ...stamps, deadline: effectiveDeadline })
.catch((err) => {
console.log(`⚠️ LoRA effect probe failed for ${filename}: ${err?.message || err}`);
return unmeasurable(`the effect probe failed unexpectedly (${err?.message || err})`);
diff --git a/server/services/loraEffectProbe.test.js b/server/services/loraEffectProbe.test.js
index 345b3ca4f3..09647e6d78 100644
--- a/server/services/loraEffectProbe.test.js
+++ b/server/services/loraEffectProbe.test.js
@@ -35,9 +35,17 @@ vi.mock('../lib/fileUtils.js', () => ({ PATHS: { root: '/mock/root', loras: MOCK
vi.mock('../lib/sidecarProcess.js', async (importOriginal) => ({
...await importOriginal(),
- runSidecarProcess: vi.fn(async ({ bin, args }) => {
+ runSidecarProcess: vi.fn(async ({ bin, args, signal }) => {
state.runs.push({ bin, args });
- return state.responses.shift() || { ok: true, stdout: '' };
+ const response = state.responses.shift() || { ok: true, stdout: '' };
+ // `aborted: true` models OUR budget expiring: withAbortTimeout fires the
+ // signal, the caller's listener observes it, and the child then dies of the
+ // SIGTERM that follows. A response with `canceled` but no `aborted` models
+ // an EXTERNAL kill (OOM, stray pkill), where the signal never fires — the
+ // distinction the production code has to make.
+ if (response.aborted) signal?.dispatchEvent(new Event('abort'));
+ const { aborted, ...rest } = response;
+ return rest;
}),
}));
@@ -191,7 +199,7 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
});
it('reports unmeasurable on a timeout rather than surfacing a cancel', async () => {
- state.responses = [{ ok: false, canceled: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
+ state.responses = [{ ok: false, canceled: true, aborted: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
state.existing = new Set(['/venv/ltx2/bin/python3']);
const report = await probeLoraEffect('style.safetensors');
expect(report.status).toBe('unmeasurable');
@@ -204,7 +212,7 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
// 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: false, canceled: true, aborted: true, reason: 'cancelled (SIGTERM)', stdout: '' },
{ ok: true, stdout: resultLine(OK_PAYLOAD) },
];
const report = await probeLoraEffect('style.safetensors');
@@ -221,7 +229,7 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
// Asserting the WRITE alone is vacuous: a report stamped with the wrong
// probe version is written and then never read back, which is exactly how
// this regressed once. Feed the stored value back through the cache.
- state.responses = [{ ok: false, canceled: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
+ state.responses = [{ ok: false, canceled: true, aborted: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
await probeLoraEffect('style.safetensors');
expect(state.patched).toHaveLength(1);
const stored = state.patched[0].patch.effectReport;
@@ -235,6 +243,30 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
expect(second.status).toBe('unmeasurable');
});
+ it('does not mistake an EXTERNAL kill for its own timeout', async () => {
+ // runSidecarProcess reports `canceled` for any SIGTERM/SIGKILL death — an
+ // OOM kill, a stray pkill, a process-group signal at shutdown. Reading that
+ // as "our budget expired" would permanently badge the adapter Not
+ // measurable, because timeouts are the one unmeasurable verdict we cache.
+ state.responses = [
+ { ok: false, canceled: true, reason: 'cancelled (SIGKILL)', stdout: '' },
+ { ok: true, stdout: resultLine(OK_PAYLOAD) },
+ ];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs.length).toBeGreaterThan(1);
+ expect(report.status).toBe('ok');
+ expect(state.patched.some((w) => w.patch.effectReport?.status === 'unmeasurable')).toBe(false);
+ });
+
+ it('reports an external kill honestly rather than as a budget overrun', async () => {
+ state.existing = new Set(['/venv/ltx2/bin/python3']);
+ state.responses = [{ ok: false, canceled: true, reason: 'cancelled (SIGKILL)', stdout: '' }];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(report.status).toBe('unmeasurable');
+ expect(report.reason).toMatch(/killed/i);
+ expect(state.patched).toHaveLength(0);
+ });
+
it('never caches the previous candidate\'s verdict when the budget runs out between them', async () => {
// The walk can end on budget exhaustion with `last` still holding a
// machine-specific "numpy is not installed" — freezing that into the
@@ -313,6 +345,15 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
expect(report.reason).toMatch(/could not be started/i);
});
+ it('honors a caller deadline that has already passed, without spawning', async () => {
+ // resolveVideoLoras shares ONE deadline across every selected adapter, so a
+ // batch cannot stall for one full budget per LoRA.
+ state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
+ const report = await probeLoraEffect('style.safetensors', { deadline: Date.now() - 1 });
+ expect(state.runs).toHaveLength(0);
+ expect(report.status).toBe('unmeasurable');
+ });
+
it('coalesces concurrent probes of the same file into one child', async () => {
state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
const [a, b] = await Promise.all([
diff --git a/server/services/loras.js b/server/services/loras.js
index 87960cf6f3..5970440f12 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -271,7 +271,7 @@ export const deleteLora = async (filename) => {
);
}
await rm(filePath, { force: true });
- await rm(sidecarPath(filename), { force: true });
+ await removeSidecar(filename);
console.log(`🗑️ Deleted LoRA: ${filename}`);
return { ok: true, filename };
};
@@ -279,14 +279,27 @@ export const deleteLora = async (filename) => {
// Patch the sidecar with user-editable fields (name, recommendedScale, notes).
// Civitai-derived fields are passed through but the route layer scopes the
// patch so callers can't trample those.
-// One sidecar patch at a time per LoRA. Every patch is a read-modify-write of a
-// whole JSON document, and there are now several writers: the user renaming a
-// LoRA in the manager, listLoras() healing keyLayout/fluxVariant on read, and
-// the effect probe caching its measurement when it finishes. Interleaved, the
-// last write wins the whole file and silently drops the other's field. Keyed, so
-// patches to different LoRAs still run in parallel.
+// One sidecar write at a time per LoRA. A patch is a read-modify-write of a
+// whole JSON document, and there are several writers: the user renaming a LoRA
+// in the manager, listLoras() healing keyLayout/fluxVariant on read, the effect
+// probe caching its measurement when it finishes, and the two installers
+// replacing the sidecar wholesale. Interleaved, the last write wins the whole
+// file and silently drops the other's field — a re-install over an existing
+// filename could have its fresh civitai block overwritten by a patch that read
+// the pre-install sidecar. EVERY writer goes through here, not just patches, or
+// the serialization is a half-measure. Keyed, so different LoRAs still run in
+// parallel.
const queueSidecarWrite = createKeyedFileWriteQueue();
+// Replace a sidecar wholesale (the install paths), serialized against patches.
+const writeSidecar = (filename, sidecar) => queueSidecarWrite(filename, () =>
+ atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n'));
+
+// Remove a sidecar, serialized so a queued patch can't recreate it after the
+// LoRA is gone.
+const removeSidecar = (filename) => queueSidecarWrite(filename, () =>
+ rm(sidecarPath(filename), { force: true }));
+
export const patchLoraSidecar = async (filename, patch) => {
assertSafeLoraFilename(filename);
const filePath = join(PATHS.loras, filename);
@@ -573,7 +586,7 @@ export const installFromCivitai = async (input, { fetchImpl = fetch } = {}) => {
await verifyDownloadedLora(destPath, { expectedSha256: file?.hashes?.SHA256 || null, source: 'civitai' });
const sidecar = await withKeyLayout(buildSidecar({ model, version, file, filename }), destPath);
- await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ await writeSidecar(filename, sidecar);
console.log(`✅ Installed Civitai LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);
return sidecar;
};
@@ -672,7 +685,7 @@ export const installFromHuggingface = async (input, { fetchImpl = fetch, onProgr
buildHfLoraSidecar({ repo, revision, file, model, family, filename, fluxVariant }),
destPath,
);
- await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ await writeSidecar(filename, sidecar);
console.log(`✅ Installed HuggingFace LoRA: ${filename} [layout=${sidecar.keyLayout || 'unknown'}]`);
return sidecar;
};
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 029c189a6f..d977debe74 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -315,6 +315,7 @@ vi.mock('../loras.js', () => ({
// gate's own tests set a status explicitly.
const loraEffectState = vi.hoisted(() => ({ reportByFilename: {}, defaultReport: { status: 'unmeasurable', measured: 0, reason: 'no numpy' } }));
vi.mock('../loraEffectProbe.js', () => ({
+ LORA_EFFECT_PROBE_BUDGET_MS: 300_000,
probeLoraEffect: vi.fn(async (filename) => loraEffectState.reportByFilename[filename] || loraEffectState.defaultReport),
}));