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: close seven correctness holes in the LoRA effect probe found in review (#4872)

[._.]/ Adam Eivycc8e9f622fd0
diff --git a/scripts/lora_effect_probe.py b/scripts/lora_effect_probe.py
index 9439e5db8b..ffcec7bfa5 100644
--- a/scripts/lora_effect_probe.py
+++ b/scripts/lora_effect_probe.py
@@ -86,8 +86,9 @@ EXIT_NO_NUMPY = 3
# Longest first: "foo.lora_A.weight" ends with both ".weight" forms and the bare
# ".lora_A", and a shorter match would strip the wrong number of characters.
-_DOWN_SUFFIXES = ("lora_A.weight", "lora_down.weight", "lora_A", "lora_down")
-_UP_SUFFIXES = ("lora_B.weight", "lora_up.weight", "lora_B", "lora_up")
+# Lowercase: _split_suffix matches against a lowercased name (see there).
+_DOWN_SUFFIXES = ("lora_a.weight", "lora_down.weight", "lora_a", "lora_down")
+_UP_SUFFIXES = ("lora_b.weight", "lora_up.weight", "lora_b", "lora_up")
# 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
@@ -125,12 +126,20 @@ def read_header(path: Path) -> tuple[dict | None, int]:
def _split_suffix(name: str) -> tuple[str, str] | None:
- """Map a tensor name to ``(module_prefix, 'down'|'up')``, or None."""
+ """Map a tensor name to ``(module_prefix, 'down'|'up')``, or None.
+
+ Matched case-INSENSITIVELY, because server/lib/safetensors.js classifies with
+ ``/i`` regexes: a file naming its pair ``lora_a``/``lora_b`` passes the key-layout
+ gate as a fusable LoRA, so a case-sensitive probe would call the very same
+ file unreadable. The prefix is sliced off the ORIGINAL name — it is the key
+ the header is looked up by.
+ """
+ lowered = name.lower()
for suffix in _DOWN_SUFFIXES:
- if name.endswith(suffix):
+ if lowered.endswith(suffix):
return name[: -len(suffix)].rstrip("."), "down"
for suffix in _UP_SUFFIXES:
- if name.endswith(suffix):
+ if lowered.endswith(suffix):
return name[: -len(suffix)].rstrip("."), "up"
return None
@@ -148,7 +157,7 @@ def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
for name in header:
if name == "__metadata__":
continue
- if name.endswith(".alpha") or name == "alpha":
+ if name.lower().endswith(".alpha") or name.lower() == "alpha":
# setdefault, so an alpha listed BEFORE its pair still lands on the
# right module; the completeness filter below drops an alpha whose
# pair never showed up.
@@ -163,7 +172,7 @@ def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
return {k: v for k, v in modules.items() if "down" in v and "up" in v}
-def _read_tensor(np, handle, payload_offset: int, desc, *, allow_scalar: bool = False):
+def _read_tensor(np, handle, payload_offset: int, desc, file_size: int, *, allow_scalar: bool = False):
"""Read one tensor as float32, or None when it is not something we can measure.
Rejects (rather than guesses at) unsupported dtypes, non-2-D shapes (conv
@@ -187,6 +196,12 @@ def _read_tensor(np, handle, payload_offset: int, desc, *, allow_scalar: bool =
start, end = offsets
if not isinstance(start, int) or not isinstance(end, int) or end < start:
return None
+ # The range must lie inside the payload. Without the lower bound a crafted
+ # ``data_offsets: [-4, 0]`` seeks BACK into the header and measures it as
+ # tensor data; without the upper bound an absurd declared length asks
+ # ``read()`` for gigabytes the file does not contain.
+ if start < 0 or payload_offset + end > file_size:
+ return None
count = math.prod(shape) if shape else 1
if (end - start) != count * spec[1]:
return None
@@ -204,7 +219,10 @@ def _read_tensor(np, handle, payload_offset: int, desc, *, allow_scalar: bool =
# full-size temporaries per module instead of one.
widened = np.zeros((len(buf) // 2, 2), dtype="<u2")
widened[:, 1] = np.frombuffer(buf, dtype="<u2")
- arr = widened.view(np.float32).reshape(-1)
+ # '<f4', not np.float32: the pair array is little-endian by
+ # construction, and viewing it through the NATIVE float32 would read the
+ # bytes backwards on a big-endian host.
+ arr = widened.view("<f4").astype(np.float32, copy=False).reshape(-1)
else:
# copy=False: an F32 adapter is already the target dtype on a
# little-endian host, and the read-only frombuffer view is all the two
@@ -241,7 +259,10 @@ def _module_rms(np, down, up, scale: float) -> float:
elements = out_features * in_features
if elements <= 0:
return math.nan
- return scale * math.sqrt(total) / math.sqrt(elements)
+ # abs(scale): a kohya file may carry a NEGATIVE alpha, and a magnitude is
+ # never negative. Without this a negative alpha yields a negative "RMS",
+ # which sorts below zero and would make max/median meaningless.
+ return abs(scale) * math.sqrt(total) / math.sqrt(elements)
def measure_lora_effect(path) -> dict:
@@ -284,14 +305,15 @@ def measure_lora_effect(path) -> dict:
values: list[float] = []
try:
+ file_size = path.stat().st_size
handle = open(path, "rb")
except OSError as err:
report["reason"] = f"{path.name} could not be opened: {err}"
return report
with handle:
for names in modules.values():
- down = _read_tensor(np, handle, payload_offset, header.get(names["down"]))
- up = _read_tensor(np, handle, payload_offset, header.get(names["up"]))
+ down = _read_tensor(np, handle, payload_offset, header.get(names["down"]), file_size)
+ up = _read_tensor(np, handle, payload_offset, header.get(names["up"]), file_size)
# Shapes must chain as (out, rank) @ (rank, in). Anything else is a
# layout this probe does not understand — skipping is honest, and
# transposing on a hunch would invent a measurement.
@@ -301,12 +323,20 @@ def measure_lora_effect(path) -> dict:
scale = 1.0
alpha_name = names.get("alpha")
if alpha_name is not None:
- alpha = _read_tensor(np, handle, payload_offset, header.get(alpha_name), allow_scalar=True)
+ alpha = _read_tensor(
+ np, handle, payload_offset, header.get(alpha_name), file_size, allow_scalar=True
+ )
rank = up.shape[1]
if alpha is not None and alpha.size == 1 and rank > 0:
alpha_value = float(alpha.reshape(-1)[0])
- if math.isfinite(alpha_value):
- scale = alpha_value / rank
+ if not math.isfinite(alpha_value):
+ # A NaN/Inf alpha makes this module's delta non-finite —
+ # count it as such. Falling back to scale 1.0 would
+ # report a plausible magnitude for a module that has
+ # none, which is the opposite of finite-safe.
+ report["skippedNonFinite"] += 1
+ continue
+ scale = alpha_value / rank
rms = _module_rms(np, down, up, scale)
if not math.isfinite(rms):
report["skippedNonFinite"] += 1
@@ -331,7 +361,14 @@ def measure_lora_effect(path) -> dict:
report["zeroModules"] = sum(1 for v in values if v == 0.0)
report["medianRms"] = float(statistics.median(values))
report["maxRms"] = float(max(values))
- if report["zeroModules"] == len(values):
+ skipped = report["skippedNonFinite"] + report["skippedUnsupported"]
+ # ``zero`` is the ONE verdict that refuses a render, so it has to mean the
+ # whole adapter is provably inert — not merely that the subset we could
+ # measure was. A file with one zero pair plus a conv-shaped or diverged pair
+ # we skipped may still carry real effect through the module we never read,
+ # and refusing it would block a working LoRA. Report the zero count and let
+ # it render.
+ if report["zeroModules"] == len(values) and skipped == 0:
report["status"] = "zero"
report["reason"] = (
f"all {len(values)} measurable LoRA module(s) have exactly zero effect "
diff --git a/scripts/lora_effect_probe_test.py b/scripts/lora_effect_probe_test.py
index b3ffb5aff0..d5ed0bc215 100644
--- a/scripts/lora_effect_probe_test.py
+++ b/scripts/lora_effect_probe_test.py
@@ -231,6 +231,81 @@ def run(tmp):
report = measure_lora_effect(truncated)
check("a truncated payload is skipped, not measured as garbage", report["measured"] == 0)
+ # --- the zero verdict must mean the WHOLE adapter is inert ---------------
+ # `zero` is the only status that refuses a render, so it may not be reached
+ # from a subset: a module we skipped could carry all the effect.
+ zero_plus_skipped = tmp / "zero_plus_conv.safetensors"
+ write_safetensors(zero_plus_skipped, {
+ **bare_pair("flat", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ **bare_pair("conv", np.ones((2, 4, 1, 1), np.float32), np.ones((4, 2, 1, 1), np.float32)),
+ })
+ report = measure_lora_effect(zero_plus_skipped)
+ check("a zero module alongside an UNSUPPORTED one does not refuse",
+ report["status"] == "ok" and report["skippedUnsupported"] == 1 and report["zeroModules"] == 1)
+
+ zero_plus_nan = tmp / "zero_plus_nan.safetensors"
+ write_safetensors(zero_plus_nan, {
+ **bare_pair("flat", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ **bare_pair("bad", rng.normal(size=(8, 64)).astype(np.float32), np.full((64, 8), np.nan, np.float32)),
+ })
+ report = measure_lora_effect(zero_plus_nan)
+ check("a zero module alongside a NON-FINITE one does not refuse",
+ report["status"] == "ok" and report["skippedNonFinite"] == 1)
+
+ # --- kohya alpha edge cases ---------------------------------------------
+ neg_alpha = tmp / "kohya_negative_alpha.safetensors"
+ write_safetensors(neg_alpha, {
+ "m.lora_down.weight": k_down,
+ "m.lora_up.weight": k_up,
+ "m.alpha": np.asarray(-4.0, np.float32),
+ })
+ neg_rms = measure_lora_effect(neg_alpha)["maxRms"]
+ check("a negative alpha yields a magnitude, never a negative RMS",
+ neg_rms > 0 and math.isclose(neg_rms, alpha_rms, rel_tol=1e-6))
+
+ nan_alpha = tmp / "kohya_nan_alpha.safetensors"
+ write_safetensors(nan_alpha, {
+ "m.lora_down.weight": k_down,
+ "m.lora_up.weight": k_up,
+ "m.alpha": np.asarray(np.nan, np.float32),
+ })
+ report = measure_lora_effect(nan_alpha)
+ check("a non-finite alpha makes the module non-finite, not a scale-1.0 guess",
+ report["status"] == "nonfinite" and report["skippedNonFinite"] == 1)
+
+ # --- case-insensitive pairing (server/lib/safetensors.js uses /i) --------
+ lower = tmp / "lowercase.safetensors"
+ write_safetensors(lower, {
+ "blocks.0.lora_a.weight": rng.normal(size=(8, 64)).astype(np.float32),
+ "blocks.0.lora_b.weight": rng.normal(size=(64, 8)).astype(np.float32),
+ })
+ report = measure_lora_effect(lower)
+ check("lowercase lora_a/lora_b pairs are measured, not called unreadable",
+ report["status"] == "ok" and report["measured"] == 1)
+
+ # --- hostile byte ranges -------------------------------------------------
+ # A negative start would seek BACK into the header and measure it as weights.
+ negative = tmp / "negative_offset.safetensors"
+ header = {
+ "m.lora_A.weight": {"dtype": "F32", "shape": [2, 4], "data_offsets": [-32, 0]},
+ "m.lora_B.weight": {"dtype": "F32", "shape": [4, 2], "data_offsets": [0, 32]},
+ }
+ blob = json.dumps(header).encode("utf-8")
+ negative.write_bytes(struct.pack("<Q", len(blob)) + blob + b"\0" * 32)
+ check("a negative data_offset is refused, never read from the header",
+ measure_lora_effect(negative)["measured"] == 0)
+
+ # A range past EOF must not be handed to read() as a giant allocation.
+ oversized = tmp / "oversized_offset.safetensors"
+ header = {
+ "m.lora_A.weight": {"dtype": "F32", "shape": [1, 2_000_000_000], "data_offsets": [0, 8_000_000_000]},
+ "m.lora_B.weight": {"dtype": "F32", "shape": [4, 2], "data_offsets": [0, 32]},
+ }
+ blob = json.dumps(header).encode("utf-8")
+ oversized.write_bytes(struct.pack("<Q", len(blob)) + blob + b"\0" * 32)
+ check("a byte range past EOF is refused before any read",
+ measure_lora_effect(oversized)["measured"] == 0)
+
# --- formatting ---------------------------------------------------------
summary = format_effect(measure_lora_effect(healthy))
check("format_effect names the statistics", "median RMS" in summary and "module(s)" in summary)
diff --git a/server/lib/loraEffect.js b/server/lib/loraEffect.js
index 442b5f69e7..3bea3ee4c1 100644
--- a/server/lib/loraEffect.js
+++ b/server/lib/loraEffect.js
@@ -69,14 +69,23 @@ const nonNegativeInt = (value) => {
* all; anything else yields a report — an unrecognized `status` degrades to
* `unmeasurable` rather than propagating a word nothing downstream understands.
*
- * `sizeBytes` / `measuredAt` are stamped by the caller (the probe measures the
- * file, it doesn't own the cache key) and are what makes a cached report
- * verifiable later.
+ * `sizeBytes` / `mtimeMs` / `measuredAt` are stamped by the caller (the probe
+ * measures the file, it doesn't own the cache key) and are what makes a cached
+ * report verifiable later.
*/
-export const normalizeLoraEffectReport = (raw, { sizeBytes = null, measuredAt = null } = {}) => {
+export const normalizeLoraEffectReport = (raw, { sizeBytes = null, mtimeMs = null, measuredAt = null } = {}) => {
if (!isPlainObject(raw)) return null;
- const status = isKnownLoraEffectStatus(raw.status) ? raw.status : LORA_EFFECT_STATUSES.UNMEASURABLE;
+ const declared = isKnownLoraEffectStatus(raw.status) ? raw.status : LORA_EFFECT_STATUSES.UNMEASURABLE;
const measured = nonNegativeInt(raw.measured);
+ const zeroModules = nonNegativeInt(raw.zeroModules);
+ // `zero` is the only status that refuses a render, so it is the only one whose
+ // internal consistency is worth checking: it must be backed by at least one
+ // measurement, and by EVERY measurement being zero. A payload claiming `zero`
+ // with nothing measured (a hand-edited sidecar, a future probe that redefines
+ // the word) would otherwise block a render on no evidence at all.
+ const status = declared === LORA_EFFECT_STATUSES.ZERO && !(measured > 0 && zeroModules === measured)
+ ? LORA_EFFECT_STATUSES.UNMEASURABLE
+ : declared;
// Statistics only exist alongside a measurement. Dropping them when
// `measured` is 0 keeps "no data" from ever reading as "measured 0.0", which
// is the exact confusion that would turn an unmeasurable adapter into a
@@ -89,11 +98,12 @@ export const normalizeLoraEffectReport = (raw, { sizeBytes = null, measuredAt =
measured,
skippedNonFinite: nonNegativeInt(raw.skippedNonFinite),
skippedUnsupported: nonNegativeInt(raw.skippedUnsupported),
- zeroModules: nonNegativeInt(raw.zeroModules),
+ zeroModules,
medianRms: stat(raw.medianRms),
maxRms: stat(raw.maxRms),
reason: typeof raw.reason === 'string' && raw.reason ? raw.reason : null,
sizeBytes: finiteOrNull(sizeBytes),
+ mtimeMs: finiteOrNull(mtimeMs),
measuredAt: typeof measuredAt === 'string' && measuredAt ? measuredAt : null,
};
};
@@ -103,20 +113,27 @@ export const normalizeLoraEffectReport = (raw, { sizeBytes = null, measuredAt =
* `readCachedLoraEffectReport` below is the only way to ask, so no caller can
* accidentally trust a report without normalizing it first.
*
- * The cache key is the probe version plus the file size: a LoRA replaced in
- * place under the same name is a different adapter, and re-probing a 500 MB
- * file on every list would defeat the "never measure on a passive read" rule
- * that this cache exists to serve. Size is not a hash — it will not catch an
- * edit that preserves byte count — but the alternative (sha256 of every LoRA
- * on every list) costs orders of magnitude more for a diagnostic the user can
- * always re-run explicitly.
+ * The cache key is the probe version plus the file's size AND mtime — both from
+ * the `stat` the caller already had, so verifying costs nothing. Size alone
+ * would miss a same-size replacement (a re-download of a sibling adapter, an
+ * in-place edit), leaving the old verdict — possibly a `zero` that blocks
+ * renders — attached to different weights. mtime closes that: anything that
+ * rewrites the file moves it.
+ *
+ * Still not a hash. A restore that deliberately preserves both stamps keeps the
+ * report, which is the correct answer for an rsync of the same bytes; and the
+ * user can always force a re-measure. Hashing every LoRA on every list would
+ * cost orders of magnitude more than the diagnostic is worth.
*/
-const isLoraEffectReportFresh = (report, { sizeBytes } = {}) => {
+const isLoraEffectReportFresh = (report, { sizeBytes, mtimeMs } = {}) => {
if (!isPlainObject(report)) return false;
if (report.probeVersion !== LORA_EFFECT_PROBE_VERSION) return false;
- const cached = finiteOrNull(report.sizeBytes);
- const actual = finiteOrNull(sizeBytes);
- return cached != null && actual != null && cached === actual;
+ const matches = (cached, actual) => {
+ const a = finiteOrNull(cached);
+ const b = finiteOrNull(actual);
+ return a != null && b != null && a === b;
+ };
+ return matches(report.sizeBytes, sizeBytes) && matches(report.mtimeMs, mtimeMs);
};
/**
@@ -124,9 +141,13 @@ const isLoraEffectReportFresh = (report, { sizeBytes } = {}) => {
* or `null`. Never probes — `listLoras()` calls this per entry, and a library
* page must not fan out into one Python child per installed adapter.
*/
-export const readCachedLoraEffectReport = (raw, sizeBytes) => {
- const report = normalizeLoraEffectReport(raw, { sizeBytes: raw?.sizeBytes, measuredAt: raw?.measuredAt });
- return isLoraEffectReportFresh(report, { sizeBytes }) ? report : null;
+export const readCachedLoraEffectReport = (raw, { sizeBytes, mtimeMs } = {}) => {
+ const report = normalizeLoraEffectReport(raw, {
+ sizeBytes: raw?.sizeBytes,
+ mtimeMs: raw?.mtimeMs,
+ measuredAt: raw?.measuredAt,
+ });
+ return isLoraEffectReportFresh(report, { sizeBytes, mtimeMs }) ? report : null;
};
/**
diff --git a/server/lib/loraEffect.test.js b/server/lib/loraEffect.test.js
index 517ec431cc..741f1f2373 100644
--- a/server/lib/loraEffect.test.js
+++ b/server/lib/loraEffect.test.js
@@ -38,11 +38,11 @@ describe('normalizeLoraEffectReport', () => {
});
it('carries a well-formed payload through and stamps the cache key', () => {
- const report = normalizeLoraEffectReport(okPayload, { sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z' });
+ const report = normalizeLoraEffectReport(okPayload, { sizeBytes: 4096, mtimeMs: 111, measuredAt: '2026-08-23T00:00:00.000Z' });
expect(report).toMatchObject({
status: 'ok', modules: 12, measured: 10, skippedNonFinite: 2, zeroModules: 1,
medianRms: 0.0031, maxRms: 0.0184,
- sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z',
+ sizeBytes: 4096, mtimeMs: 111, measuredAt: '2026-08-23T00:00:00.000Z',
});
});
@@ -101,28 +101,38 @@ describe('isKnownLoraEffectStatus', () => {
});
describe('readCachedLoraEffectReport', () => {
- const cached = { ...okPayload, sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z' };
+ const cached = { ...okPayload, sizeBytes: 4096, mtimeMs: 1_700_000_000_000, measuredAt: '2026-08-23T00:00:00.000Z' };
+ const onDisk = { sizeBytes: 4096, mtimeMs: 1_700_000_000_000 };
- it('accepts a report measured against the same file size at the same probe version', () => {
- expect(readCachedLoraEffectReport(cached, 4096)).toMatchObject({ status: 'ok', sizeBytes: 4096 });
+ it('accepts a report measured against the same file at the same probe version', () => {
+ expect(readCachedLoraEffectReport(cached, onDisk)).toMatchObject({ status: 'ok', sizeBytes: 4096 });
});
it('drops a report whose file has changed size underneath it', () => {
- expect(readCachedLoraEffectReport(cached, 8192)).toBeNull();
+ expect(readCachedLoraEffectReport(cached, { ...onDisk, sizeBytes: 8192 })).toBeNull();
+ });
+
+ it('drops a report whose file was rewritten at the SAME size', () => {
+ // Size alone would keep the old verdict attached to different weights — and
+ // a stale `zero` blocks renders of an adapter that may be fine.
+ expect(readCachedLoraEffectReport(cached, { ...onDisk, mtimeMs: 1_700_000_009_999 })).toBeNull();
});
it('drops a report from a different probe version', () => {
- expect(readCachedLoraEffectReport({ ...cached, probeVersion: LORA_EFFECT_PROBE_VERSION + 1 }, 4096)).toBeNull();
- expect(readCachedLoraEffectReport({ ...cached, probeVersion: undefined }, 4096)).toBeNull();
+ expect(readCachedLoraEffectReport({ ...cached, probeVersion: LORA_EFFECT_PROBE_VERSION + 1 }, onDisk)).toBeNull();
+ expect(readCachedLoraEffectReport({ ...cached, probeVersion: undefined }, onDisk)).toBeNull();
});
- it('drops a report that never recorded a size, and never treats a missing size as a match', () => {
- expect(readCachedLoraEffectReport({ ...cached, sizeBytes: undefined }, 4096)).toBeNull();
- expect(readCachedLoraEffectReport(cached, undefined)).toBeNull();
+ it('never treats a missing stamp on either side as a match', () => {
+ expect(readCachedLoraEffectReport({ ...cached, sizeBytes: undefined }, onDisk)).toBeNull();
+ expect(readCachedLoraEffectReport({ ...cached, mtimeMs: undefined }, onDisk)).toBeNull();
+ expect(readCachedLoraEffectReport(cached, { sizeBytes: 4096 })).toBeNull();
+ expect(readCachedLoraEffectReport(cached, { mtimeMs: 1_700_000_000_000 })).toBeNull();
+ expect(readCachedLoraEffectReport(cached, {})).toBeNull();
});
it('returns null for a missing sidecar field rather than a hollow report', () => {
- expect(readCachedLoraEffectReport(undefined, 4096)).toBeNull();
+ expect(readCachedLoraEffectReport(undefined, onDisk)).toBeNull();
});
});
@@ -139,6 +149,29 @@ describe('loraEffectIssue', () => {
expect(loraEffectIssue({ status: 'zero' })).toMatch(/zero effect/);
});
+ it('will not refuse on a "zero" payload that no measurement backs', () => {
+ // A hand-edited sidecar (or a future probe that redefines the word) claiming
+ // `zero` with nothing measured must not block a render on no evidence.
+ // normalizeLoraEffectReport downgrades it before the verdict is ever asked.
+ for (const bogus of [
+ { ...okPayload, status: 'zero', measured: 0, zeroModules: 0 },
+ { ...okPayload, status: 'zero', measured: 0, zeroModules: 4 },
+ { ...okPayload, status: 'zero', measured: 6, zeroModules: 3 },
+ ]) {
+ const report = normalizeLoraEffectReport(bogus);
+ expect(report.status).toBe('unmeasurable');
+ expect(loraEffectIssue(report)).toBeNull();
+ }
+ });
+
+ it('keeps a zero verdict that every measurement backs', () => {
+ const report = normalizeLoraEffectReport({
+ ...okPayload, status: 'zero', measured: 4, zeroModules: 4, medianRms: 0, maxRms: 0,
+ });
+ expect(report.status).toBe('zero');
+ expect(loraEffectIssue(report)).not.toBeNull();
+ });
+
it('refuses NOTHING else — an unrunnable probe must never block a render', () => {
for (const status of ['ok', 'nonfinite', 'unreadable', 'unmeasurable']) {
expect(loraEffectIssue({ ...okPayload, status, reason: 'something alarming' })).toBeNull();
diff --git a/server/services/loraEffectProbe.js b/server/services/loraEffectProbe.js
index 8af743947a..27d0e60a29 100644
--- a/server/services/loraEffectProbe.js
+++ b/server/services/loraEffectProbe.js
@@ -122,7 +122,7 @@ const runProbeOnce = async (bin, filePath) => {
// 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) => {
+const measureLoraEffect = async (filename, filePath, { sizeBytes, mtimeMs }) => {
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');
@@ -142,7 +142,7 @@ const measureLoraEffect = async (filename, filePath, sizeBytes) => {
console.log(`⚠️ LoRA effect probe unavailable for ${filename}: ${last.reason || 'unknown'}`);
return last;
}
- const report = normalizeLoraEffectReport(last, { sizeBytes, measuredAt: new Date().toISOString() });
+ const report = normalizeLoraEffectReport(last, { sizeBytes, mtimeMs, measuredAt: new Date().toISOString() });
console.log(`🔬 LoRA effect ${filename}: ${report.status} (${report.measured}/${report.modules} modules)`);
// Best-effort cache — a sidecar we can't write is a slower diagnostic, not a
// failed one.
@@ -166,10 +166,12 @@ export const probeLoraEffect = async (filename, { force = false } = {}) => {
if (!fileStat || !fileStat.isFile()) {
return unmeasurable(`LoRA "${filename}" is not a regular file on disk`);
}
- const sizeBytes = fileStat.size;
+ // 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.
+ const stamps = { sizeBytes: fileStat.size, mtimeMs: fileStat.mtimeMs };
if (!force) {
- const cached = readCachedLoraEffectReport((await readSidecar(filename))?.effectReport, sizeBytes);
+ const cached = readCachedLoraEffectReport((await readSidecar(filename))?.effectReport, stamps);
if (cached) return cached;
}
@@ -178,7 +180,7 @@ 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, sizeBytes)
+ return inFlight.run(filePath, () => measureLoraEffect(filename, filePath, stamps)
.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 d767960337..cde8ec3f36 100644
--- a/server/services/loraEffectProbe.test.js
+++ b/server/services/loraEffectProbe.test.js
@@ -13,7 +13,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const MOCK_LORAS_DIR = '/mock/loras';
const state = vi.hoisted(() => ({
- statResult: { size: 4096, isFile: () => true },
+ statResult: { size: 4096, mtimeMs: 1_700_000_000_000, isFile: () => true },
statThrows: false,
sidecar: null,
patched: [],
@@ -75,7 +75,7 @@ let LORA_EFFECT_PROBE_SCRIPT;
beforeEach(async () => {
vi.resetModules();
- state.statResult = { size: 4096, isFile: () => true };
+ state.statResult = { size: 4096, mtimeMs: 1_700_000_000_000, isFile: () => true };
state.statThrows = false;
state.sidecar = null;
state.patched = [];
@@ -99,32 +99,42 @@ describe('probeLoraEffect — happy path', () => {
expect(report.measuredAt).toEqual(expect.any(String));
});
- it('caches the measurement into the sidecar keyed by the file size', async () => {
+ it('caches the measurement into the sidecar keyed by the file size and mtime', async () => {
state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
await probeLoraEffect('style.safetensors');
expect(state.patched).toHaveLength(1);
expect(state.patched[0]).toMatchObject({
filename: 'style.safetensors',
- patch: { effectReport: expect.objectContaining({ status: 'ok', sizeBytes: 4096 }) },
+ patch: { effectReport: expect.objectContaining({ status: 'ok', sizeBytes: 4096, mtimeMs: 1_700_000_000_000 }) },
});
});
it('returns the cached report without spawning anything', async () => {
- state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z' } };
+ state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, mtimeMs: 1_700_000_000_000, measuredAt: '2026-08-23T00:00:00.000Z' } };
const report = await probeLoraEffect('style.safetensors');
expect(state.runs).toHaveLength(0);
expect(report).toMatchObject({ status: 'ok', measuredAt: '2026-08-23T00:00:00.000Z' });
});
it('re-measures a cached report when the file size changed underneath it', async () => {
- state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 999, measuredAt: '2026-08-23T00:00:00.000Z' } };
+ state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 999, mtimeMs: 1_700_000_000_000, measuredAt: '2026-08-23T00:00:00.000Z' } };
+ state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
+ await probeLoraEffect('style.safetensors');
+ expect(state.runs).toHaveLength(1);
+ });
+
+ it('re-measures when the file was rewritten at the same size', async () => {
+ // Same bytes-count, different mtime: a re-download of a sibling adapter.
+ // Trusting the old report here would attach the previous verdict to
+ // different weights.
+ state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, mtimeMs: 1_699_999_000_000, measuredAt: '2026-08-23T00:00:00.000Z' } };
state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
await probeLoraEffect('style.safetensors');
expect(state.runs).toHaveLength(1);
});
it('re-measures on force even when a fresh cached report exists', async () => {
- state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z' } };
+ state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, mtimeMs: 1_700_000_000_000, measuredAt: '2026-08-23T00:00:00.000Z' } };
state.responses = [{ ok: true, stdout: resultLine({ ...OK_PAYLOAD, status: 'zero', zeroModules: 4, medianRms: 0, maxRms: 0 }) }];
const report = await probeLoraEffect('style.safetensors', { force: true });
expect(state.runs).toHaveLength(1);
@@ -205,7 +215,7 @@ describe('probeLoraEffect — never fatal, never a false verdict', () => {
state.statThrows = true;
await expect(probeLoraEffect('gone.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
state.statThrows = false;
- state.statResult = { size: 0, isFile: () => false };
+ state.statResult = { size: 0, mtimeMs: 0, isFile: () => false };
await expect(probeLoraEffect('dir.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
expect(state.runs).toHaveLength(0);
});
diff --git a/server/services/loras.js b/server/services/loras.js
index c32abac92b..8e58545212 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -230,7 +230,7 @@ export const listLoras = async () => {
// the file has changed size underneath it. `null` = never measured (or
// measured against a different file), which the UI shows as an offer to
// run the check, not as a verdict.
- effectReport: readCachedLoraEffectReport(sidecar?.effectReport, s.size),
+ effectReport: readCachedLoraEffectReport(sidecar?.effectReport, { sizeBytes: s.size, mtimeMs: s.mtimeMs }),
};
},
});
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 38ff63f820..aa249db9d2 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -207,26 +207,34 @@ describe('listLoras', () => {
// it surfaces only what the explicit probe already measured, and only while
// that measurement still describes the file on disk.
describe('listLoras — cached adapter-effect report', () => {
- const writeLora = async (filename, bytes, sidecar) => {
+ const report = (over = {}) => ({
+ probeVersion: 1, status: 'ok', modules: 8, measured: 8, skippedNonFinite: 0,
+ skippedUnsupported: 0, zeroModules: 0, medianRms: 0.004, maxRms: 0.02,
+ reason: null, measuredAt: '2026-08-23T00:00:00.000Z', ...over,
+ });
+ // The cache key is the file's real size + mtime, so the sidecar has to be
+ // written from the file that actually landed on disk — `stamp` overrides let a
+ // test deliberately mismatch one of them.
+ const writeLora = async (filename, bytes, effectReport, stamp = {}) => {
const fs = await import('fs/promises');
await fs.mkdir(tmpLoras, { recursive: true });
- await fs.writeFile(join(tmpLoras, filename), Buffer.alloc(bytes, 1));
+ const path = join(tmpLoras, filename);
+ await fs.writeFile(path, Buffer.alloc(bytes, 1));
+ const s = await fs.stat(path);
+ const sidecar = effectReport
+ ? { effectReport: { ...effectReport, sizeBytes: s.size, mtimeMs: s.mtimeMs, ...stamp } }
+ : { name: 'Unmeasured' };
await fs.writeFile(join(tmpLoras, `${filename}.metadata.json`), JSON.stringify({ filename, ...sidecar }));
};
- const freshReport = (sizeBytes) => ({
- probeVersion: 1, status: 'ok', modules: 8, measured: 8, skippedNonFinite: 0,
- skippedUnsupported: 0, zeroModules: 0, medianRms: 0.004, maxRms: 0.02, minRms: 0.001,
- reason: null, sizeBytes, measuredAt: '2026-08-23T00:00:00.000Z',
- });
- it('surfaces a stored report whose size still matches the file', async () => {
- await writeLora('measured.safetensors', 512, { effectReport: freshReport(512) });
+ it('surfaces a stored report whose size and mtime still match the file', async () => {
+ await writeLora('measured.safetensors', 512, report());
const [lora] = await lorasService.listLoras();
expect(lora.effectReport).toMatchObject({ status: 'ok', measured: 8, medianRms: 0.004, sizeBytes: 512 });
});
it('reports null when the LoRA was never measured', async () => {
- await writeLora('unmeasured.safetensors', 512, { name: 'Unmeasured' });
+ await writeLora('unmeasured.safetensors', 512, null);
const [lora] = await lorasService.listLoras();
expect(lora.effectReport).toBeNull();
});
@@ -234,24 +242,36 @@ describe('listLoras — cached adapter-effect report', () => {
it('drops a stored report once the file has been replaced under the same name', async () => {
// A different size is a different adapter. Surfacing the old verdict would
// badge a freshly-installed LoRA with the previous file's measurement.
- await writeLora('swapped.safetensors', 1024, { effectReport: freshReport(512) });
+ await writeLora('swapped.safetensors', 1024, report(), { sizeBytes: 512 });
+ const [lora] = await lorasService.listLoras();
+ expect(lora.effectReport).toBeNull();
+ });
+
+ it('drops a stored report when the file was rewritten at the SAME size', async () => {
+ await writeLora('rewritten.safetensors', 512, report(), { mtimeMs: 1 });
const [lora] = await lorasService.listLoras();
expect(lora.effectReport).toBeNull();
});
it('drops a stored report written by a different probe version', async () => {
- await writeLora('old.safetensors', 512, { effectReport: { ...freshReport(512), probeVersion: 99 } });
+ await writeLora('old.safetensors', 512, report({ probeVersion: 99 }));
const [lora] = await lorasService.listLoras();
expect(lora.effectReport).toBeNull();
});
it('normalizes a hand-edited sidecar rather than trusting it', async () => {
- await writeLora('edited.safetensors', 512, {
- effectReport: { ...freshReport(512), status: 'catastrophic', medianRms: 'lots', maxRms: null },
- });
+ await writeLora('edited.safetensors', 512, report({ status: 'catastrophic', medianRms: 'lots', maxRms: null }));
const [lora] = await lorasService.listLoras();
expect(lora.effectReport).toMatchObject({ status: 'unmeasurable', medianRms: null, maxRms: null });
});
+
+ it('will not surface a "zero" verdict that no measurement backs', async () => {
+ // Refusing a render is the one thing a stale/edited sidecar must never be
+ // able to cause on its own.
+ await writeLora('bogus-zero.safetensors', 512, report({ status: 'zero', measured: 0, zeroModules: 0 }));
+ const [lora] = await lorasService.listLoras();
+ expect(lora.effectReport.status).toBe('unmeasurable');
+ });
});
describe('deleteLora', () => {