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

feat: measure whether a LoRA actually changes anything before a video render burns GPU time (#4872)

[._.]/ Adam Eivyc7e9038486c4
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d56d08aeb5..09185666e6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -50,6 +50,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
| `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/cosValidation.js`. |
| `reviewerPins.js` | Client mirrors of the per-reviewer pin vocabularies — `MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput` and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against the server's own ladders, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. |
+| `loraEffect.js` | Mirror of the LoRA adapter-effect report vocabulary in `server/lib/loraEffect.js` (#4872): `LORA_EFFECT_STATUSES` (`ok`/`zero`/`nonfinite`/`unreadable`/`unmeasurable`), `LORA_EFFECT_BADGES` + `loraEffectBadge(status)` (badge label and Tailwind tone — only `zero` is styled as an error, because only `zero` refuses a render server-side), and `formatLoraEffect(report)`, the same one-line summary the server logs, returning `null` when the badge already says everything. Pinned by `loraEffect.parity.test.js`. |
| `loraTriggers.js` | Mirror of the trigger-word predicates in `server/lib/loraTriggers.js` (#4665): `firstTriggerWord` (the canonical activation token of a Civitai `trainedWords` list) and `promptHasTriggerWord` (whole-token, case-insensitive presence — `aria_tok` does not match inside `aria_token`). Plus `appendTriggerWords(prompt, words, effectivePrompt?)` — the "+ trigger" button's append, which adds ALL of a LoRA's words (the server only ever weaves the first) and judges presence against the composed prompt the page will actually submit. Lets the LoRA picker warn that the server is about to append a token, with the button and the hint sharing one presence rule. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
| `slashdoCatalog.js` | Mirror of `server/lib/slashdoCatalog.js` — the launchable slashdo workflows (`SLASHDO_WORKFLOWS`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`) driving the app-overview Agent Operations buttons. Adds only the per-button Tailwind classes; pinned by `server/lib/slashdoCatalog.test.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 8d356d23c1..ed47b0b8f0 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -48,6 +48,7 @@ export * from './pipelineImageDefaults.js';
export * from './reverseOutlineGrid.js';
export * from './reviewerModels.js';
export * from './reviewerPins.js';
+export * from './loraEffect.js';
export * from './loraTriggers.js';
export * from './runnerFamilies.js';
export * from './slashdoCatalog.js';
diff --git a/client/src/lib/loraEffect.js b/client/src/lib/loraEffect.js
new file mode 100644
index 0000000000..42df5602e4
--- /dev/null
+++ b/client/src/lib/loraEffect.js
@@ -0,0 +1,67 @@
+/**
+ * Client mirror of the LoRA adapter-effect report vocabulary in
+ * `server/lib/loraEffect.js` (issue #4872).
+ *
+ * The server is the decision point — it measures the adapter, decides which
+ * verdict blocks a render (`loraEffectIssue`: only `zero` does), and caches the
+ * report in the LoRA sidecar. These helpers exist so the manager card can say
+ * the same thing the render will, in the same words. `loraEffect.parity.test.js`
+ * pins the status list against the server module; keep `formatLoraEffect` in
+ * step with its server twin by hand, or a card and a render log will describe
+ * one measurement two different ways.
+ *
+ * Same shape as `client/src/lib/loraTriggers.js` mirroring its server twin.
+ */
+
+// Mirrors LORA_EFFECT_STATUSES in server/lib/loraEffect.js.
+export const LORA_EFFECT_STATUSES = Object.freeze({
+ OK: 'ok',
+ ZERO: 'zero',
+ NONFINITE: 'nonfinite',
+ UNREADABLE: 'unreadable',
+ UNMEASURABLE: 'unmeasurable',
+});
+
+// Badge text + Tailwind tone per status. Presentation is legitimately
+// client-only, but it lives beside the mirrored status list so a new verdict
+// can't render as a bare slug — one table rather than two parallel maps, which
+// is the pair that would otherwise drift.
+export const LORA_EFFECT_BADGES = Object.freeze({
+ // Only `zero` refuses a render server-side, so only `zero` is styled as an
+ // error. `nonfinite` is a genuinely broken adapter the user should see, but
+ // it still renders — warning, not error.
+ ok: { label: 'Active', tone: 'text-port-success' },
+ zero: { label: 'No effect', tone: 'text-port-error' },
+ nonfinite: { label: 'Diverged', tone: 'text-port-warning' },
+ unreadable: { label: 'Unreadable', tone: 'text-port-warning' },
+ unmeasurable: { label: 'Not measurable', tone: 'text-gray-500' },
+});
+
+export const loraEffectBadge = (status) => LORA_EFFECT_BADGES[status]
+ || { label: status || 'Unknown', tone: 'text-gray-400' };
+
+/**
+ * One-line summary of a measurement — the mirror of `formatLoraEffect` in
+ * server/lib/loraEffect.js, and deliberately the same wording.
+ *
+ * Returns `null` when there is nothing to add beyond the badge, so a caller can
+ * omit the separator rather than printing "Unreadable — Unreadable".
+ */
+export const formatLoraEffect = (report) => {
+ if (!report) return null;
+ // Both statistics, not just `measured`: the server nulls a non-finite value
+ // while leaving `measured` intact, so a measured report can still arrive with
+ // no renderable number.
+ if (!Number.isFinite(report.medianRms) || !Number.isFinite(report.maxRms)) {
+ return report.reason || null;
+ }
+ const parts = [
+ `median RMS ${report.medianRms.toExponential(2)}`,
+ `max ${report.maxRms.toExponential(2)}`,
+ `across ${report.measured} module(s)`,
+ ];
+ if (report.skippedNonFinite > 0) parts.push(`${report.skippedNonFinite} non-finite skipped`);
+ if (report.skippedUnsupported > 0) parts.push(`${report.skippedUnsupported} unsupported skipped`);
+ if (report.zeroModules > 0) parts.push(`${report.zeroModules} zero`);
+ return parts.join(', ');
+};
diff --git a/client/src/pages/Loras.jsx b/client/src/pages/Loras.jsx
index 2c91c486e5..f0e486a568 100644
--- a/client/src/pages/Loras.jsx
+++ b/client/src/pages/Loras.jsx
@@ -9,7 +9,7 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router';
-import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search } from 'lucide-react';
+import { Trash2, Download, ExternalLink, Sparkles, AlertTriangle, KeyRound, Check, X, RefreshCw, Wand2, Search, Activity } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
@@ -21,6 +21,7 @@ import { FormField } from '../components/ui/FormField';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
import { formatBytes } from '../utils/formatters';
import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, isVideoLoraFamily } from '../lib/runnerFamilies';
+import { LORA_EFFECT_STATUSES, formatLoraEffect, loraEffectBadge } from '../lib/loraEffect';
import {
listLorasFull,
installLoraFromCivitai,
@@ -31,6 +32,7 @@ import {
clearCivitaiAuth,
getCivitaiSuggestions,
searchCivitaiLoras,
+ probeLoraEffect,
} from '../services/api';
const RUNNER_LABEL = {
@@ -1123,6 +1125,30 @@ 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);
+ 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);
+ 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`);
+ } else if (report?.status === LORA_EFFECT_STATUSES.OK) {
+ toast.success(`${displayName} is active — ${summary}`);
+ } else {
+ toast(summary || `${displayName}: ${loraEffectBadge(report?.status).label}`);
+ }
+ })
+ .catch((err) => toast.error(err?.message || 'Effect check failed'))
+ .finally(() => setCheckingEffect(false));
+ };
+
return (
<div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col">
{lora.previewImageUrl ? (
@@ -1178,6 +1204,18 @@ function LoraCard({ lora, onDelete, deleting, deleteConfirm }) {
{civitai?.baseModel && (<><span>Base model</span><span className="text-gray-300 truncate text-right" title={civitai.baseModel}>{civitai.baseModel}</span></>)}
</div>
+ {effect && (
+ <div className="text-[11px] mb-3 -mt-1">
+ <span className={`font-medium ${loraEffectBadge(effect.status).tone}`}>
+ {loraEffectBadge(effect.status).label}
+ </span>
+ {/* formatLoraEffect returns null when the badge already says
+ everything, so a reason-less verdict doesn't render as
+ "Unreadable — Unreadable". */}
+ {effectSummary && <span className="text-gray-500"> — {effectSummary}</span>}
+ </div>
+ )}
+
{/* Armed state replaces the whole action row instead of squeezing the
confirm pair in beside Test/Civitai — a narrow card (or a phone at
one column) has no room for both, and the row would wrap. */}
@@ -1224,6 +1262,15 @@ function LoraCard({ lora, onDelete, deleting, deleteConfirm }) {
<ExternalLink size={14} />
</a>
)}
+ <button
+ onClick={runEffectCheck}
+ disabled={checkingEffect}
+ className="text-gray-400 hover:text-gray-200 p-1.5 rounded hover:bg-port-bg disabled:opacity-50 disabled:cursor-not-allowed"
+ title={`Check whether ${displayName} actually changes a render`}
+ aria-label={`Check effect of ${displayName}`}
+ >
+ {checkingEffect ? <BrailleSpinner /> : <Activity size={14} />}
+ </button>
<button
onClick={() => deleteConfirm.requestDelete(lora.filename)}
className="text-port-error hover:text-port-error/80 p-1.5 rounded hover:bg-port-error/10"
diff --git a/client/src/pages/Loras.test.jsx b/client/src/pages/Loras.test.jsx
index 2824977904..a8dcd97318 100644
--- a/client/src/pages/Loras.test.jsx
+++ b/client/src/pages/Loras.test.jsx
@@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import Loras from './Loras';
-import { listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream } from '../services/api';
+import { listLorasFull, deleteLoraFull, installLoraFromHuggingfaceStream, probeLoraEffect } from '../services/api';
vi.mock('../services/api', () => ({
listLorasFull: vi.fn(),
@@ -19,6 +19,7 @@ vi.mock('../services/api', () => ({
clearCivitaiAuth: vi.fn(),
getCivitaiSuggestions: vi.fn(async () => ({ runners: {}, video: [], fetchedAt: null })),
searchCivitaiLoras: vi.fn(),
+ probeLoraEffect: vi.fn(),
}));
vi.mock('../components/ui/Toast', () => ({
@@ -133,3 +134,66 @@ describe('Loras HuggingFace family picker', () => {
expect(screen.queryByText(/Install it as an LTX-Video LoRA/)).not.toBeInTheDocument();
});
});
+
+// Adapter-effect diagnostic (#4872). The card seeds from the server's CACHED
+// report and re-measures on demand; only a measured all-zero adapter is the
+// alarming one, and the badge must never echo itself when there is no summary.
+describe('Loras adapter-effect check', () => {
+ const withEffect = (effectReport) => ({ ...LORA, effectReport });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ deleteLoraFull.mockResolvedValue({});
+ });
+
+ it('renders the cached report without asking the server to re-measure', async () => {
+ listLorasFull.mockResolvedValue([withEffect({
+ status: 'ok', measured: 8, medianRms: 0.004, maxRms: 0.02,
+ skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null,
+ })]);
+ renderPage();
+ expect(await screen.findByText('Active')).toBeInTheDocument();
+ expect(screen.getByText(/median RMS 4.00e-3, max 2.00e-2, across 8 module\(s\)/)).toBeInTheDocument();
+ expect(probeLoraEffect).not.toHaveBeenCalled();
+ });
+
+ it('shows no effect row at all for a LoRA that was never measured', async () => {
+ listLorasFull.mockResolvedValue([withEffect(null)]);
+ renderPage();
+ await screen.findByText('Example LoRA');
+ expect(screen.queryByText('Active')).not.toBeInTheDocument();
+ expect(screen.queryByText('Not measurable')).not.toBeInTheDocument();
+ });
+
+ it('force-re-measures on click and swaps the badge in place', async () => {
+ listLorasFull.mockResolvedValue([withEffect(null)]);
+ probeLoraEffect.mockResolvedValue({
+ status: 'zero', measured: 6, medianRms: 0, maxRms: 0,
+ skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 6,
+ reason: 'all 6 measurable LoRA module(s) have exactly zero effect',
+ });
+ renderPage();
+ fireEvent.click(await screen.findByRole('button', { name: 'Check effect of Example LoRA' }));
+ expect(probeLoraEffect).toHaveBeenCalledWith('example-lora.safetensors', { force: true, silent: true });
+ expect(await screen.findByText('No effect')).toBeInTheDocument();
+ });
+
+ it('renders the badge alone — never echoed — when there is nothing to add', async () => {
+ listLorasFull.mockResolvedValue([withEffect({
+ status: 'unreadable', measured: 0, medianRms: null, maxRms: null,
+ skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null,
+ })]);
+ renderPage();
+ expect(await screen.findByText('Unreadable')).toBeInTheDocument();
+ expect(screen.queryByText(/Unreadable — Unreadable/)).not.toBeInTheDocument();
+ });
+
+ it('keeps the card usable when the probe request fails', async () => {
+ listLorasFull.mockResolvedValue([withEffect(null)]);
+ probeLoraEffect.mockRejectedValue(new Error('probe exploded'));
+ renderPage();
+ fireEvent.click(await screen.findByRole('button', { name: 'Check effect of Example LoRA' }));
+ await waitFor(() => expect(probeLoraEffect).toHaveBeenCalled());
+ expect(await screen.findByRole('button', { name: 'Check effect of Example LoRA' })).toBeEnabled();
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 6bc2da439b..5c4829fdf3 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -568,3 +568,10 @@ export const patchLora = (filename, patch) => request(`/loras/${encodeURICompone
body: JSON.stringify(patch),
});
export const deleteLoraFull = (filename, options = {}) => request(`/loras/${encodeURIComponent(filename)}`, { method: 'DELETE', ...options });
+// Adapter-effect diagnostic (#4872) — measures whether a LoRA actually changes
+// anything before a long render commits to it. POST because it spawns the probe
+// and caches the measurement in the sidecar; `force` re-measures a cached one.
+export const probeLoraEffect = (filename, { force = false, ...options } = {}) => request(
+ `/loras/${encodeURIComponent(filename)}/effect${force ? '?force=1' : ''}`,
+ { method: 'POST', ...options },
+);
diff --git a/scripts/lora_effect_probe.py b/scripts/lora_effect_probe.py
new file mode 100644
index 0000000000..9439e5db8b
--- /dev/null
+++ b/scripts/lora_effect_probe.py
@@ -0,0 +1,376 @@
+#!/usr/bin/env python3
+"""Measure how much a LoRA adapter would actually change the weights it fuses into.
+
+PortOS already refuses a LoRA whose *filename*, safetensors structure, key
+layout or runtime is wrong (`server/lib/safetensors.js`,
+`server/services/videoGen/local.js#resolveVideoLoras`). None of those checks
+answers the question a user actually has before committing to a multi-minute
+video render: **does this adapter do anything?** A structurally perfect file can
+still carry all-zero `lora_B` weights (a training run that never stepped), NaN
+deltas (a diverged run saved anyway), or deltas so small the render is
+indistinguishable from the base model.
+
+This probe answers that, per LoRA module, from the file alone — no pipeline, no
+GPU, no model download:
+
+ delta = scale * (B @ A) # what fusing would add to the base weight
+ effect = ||delta||_F / sqrt(n) # RMS magnitude of that addition
+
+The Frobenius norm is computed from the two rank-sized Gram matrices rather than
+the full ``out x in`` product:
+
+ ||B @ A||_F^2 = trace((B^T B) (A A^T))
+
+Both Grams are ``rank x rank`` (rank is 8-256 in practice), so a 4096x4096
+module costs two skinny products instead of materialising a 16M-element matrix.
+The result is exact, not an estimate.
+
+Finite-safety — the whole point of the module, and why it is a probe rather
+than an inline calculation:
+
+ * Warnings are suppressed **only** around the two matrix products. Apple's
+ Accelerate BLAS emits ``RuntimeWarning`` for perfectly ordinary overflow
+ during accumulation; letting that escape onto stderr would put a scary
+ numerical warning next to a user-facing verdict that is in fact fine. The
+ suppression is scoped to the products so a warning raised anywhere else
+ (a genuinely bad read, a numpy deprecation) still surfaces.
+ * A module whose total is NaN or +/-Inf is **skipped**, not folded into the
+ aggregate. One diverged module would otherwise turn every summary statistic
+ into NaN and destroy the report for the modules that are fine.
+ * Median and max are computed over the surviving finite values only, so they
+ are stable: adding a diverged module to a healthy adapter changes the
+ ``skippedNonFinite`` count, never the reported magnitudes.
+
+Verdict (`status`): one of `ok` / `zero` / `nonfinite` / `unreadable` /
+`unmeasurable`. `server/lib/loraEffect.js` is the AUTHORITY on what each one
+means and which one refuses a render — this script only reports what it measured,
+and duplicating the policy here would give it two places to drift. The one detail
+that belongs on this side: `unmeasurable` (no numpy) also exits with code 3, so
+the caller can try another interpreter instead of blaming the adapter.
+
+Deliberately NOT a verdict: "weak". A small median is reported as a number and
+left to the human — there is no defensible threshold below which an adapter is
+"too weak", and inventing one would refuse working stylistic LoRAs.
+
+Import-time cost is stdlib only (numpy is imported inside `measure_lora_effect`)
+so `scripts/generate_ltx2.py` can import this from the ltx-2-mlx venv without
+pulling numpy into a render that never asks for a measurement.
+
+Run standalone: python3 scripts/lora_effect_probe.py <path-to.safetensors>
+Emits a single ``RESULT:<json>`` line on stdout (the PortOS sidecar protocol).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import statistics
+import struct
+import sys
+import warnings
+from pathlib import Path
+
+# Bumped when the measurement or the status vocabulary changes, so a report
+# cached in a LoRA sidecar by an older PortOS is re-probed instead of trusted.
+# Mirrored by LORA_EFFECT_PROBE_VERSION in server/lib/loraEffect.js.
+PROBE_VERSION = 1
+
+# Same sanity bound as readSafetensorsHeader() in server/lib/safetensors.js: a
+# real header is KB to low-MB, anything past this is a corrupt length we refuse
+# to allocate for.
+MAX_HEADER_BYTES = 100 * 1024 * 1024
+
+EXIT_OK = 0
+EXIT_USAGE = 2
+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")
+
+# 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).
+_DTYPES = {
+ "F64": ("<f8", 8),
+ "F32": ("<f4", 4),
+ "F16": ("<f2", 2),
+ "BF16": (None, 2),
+}
+
+
+def read_header(path: Path) -> tuple[dict | None, int]:
+ """Parse the safetensors JSON header. Returns ``(header, payload_offset)``.
+
+ ``(None, 0)`` for anything unreadable — missing file, truncated write, a
+ non-safetensors blob, a garbage header length. Never raises: an unreadable
+ file is a verdict (``unreadable``), not a crash.
+ """
+ try:
+ with open(path, "rb") as handle:
+ raw_len = handle.read(8)
+ if len(raw_len) < 8:
+ return None, 0
+ (header_len,) = struct.unpack("<Q", raw_len)
+ if header_len <= 0 or header_len > MAX_HEADER_BYTES:
+ return None, 0
+ blob = handle.read(header_len)
+ if len(blob) < header_len:
+ return None, 0
+ header = json.loads(blob.decode("utf-8"))
+ except (OSError, ValueError, struct.error):
+ return None, 0
+ return (header, 8 + header_len) if isinstance(header, dict) else (None, 0)
+
+
+def _split_suffix(name: str) -> tuple[str, str] | None:
+ """Map a tensor name to ``(module_prefix, 'down'|'up')``, or None."""
+ for suffix in _DOWN_SUFFIXES:
+ if name.endswith(suffix):
+ return name[: -len(suffix)].rstrip("."), "down"
+ for suffix in _UP_SUFFIXES:
+ if name.endswith(suffix):
+ return name[: -len(suffix)].rstrip("."), "up"
+ return None
+
+
+def pair_lora_modules(header: dict) -> dict[str, dict[str, str]]:
+ """Group tensor names into ``{module: {'down': name, 'up': name, 'alpha': name}}``.
+
+ Covers every layout PortOS classifies: bare and ComfyUI files name the pair
+ ``lora_A``/``lora_B``, kohya/LyCORIS names it ``lora_down``/``lora_up`` and
+ 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.
+ """
+ modules: dict[str, dict[str, str]] = {}
+ for name in header:
+ if name == "__metadata__":
+ continue
+ if name.endswith(".alpha") or name == "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.
+ modules.setdefault(name[: -len("alpha")].rstrip("."), {})["alpha"] = name
+ continue
+ split = _split_suffix(name)
+ if split is None:
+ continue
+ 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}
+
+
+def _read_tensor(np, handle, payload_offset: int, desc, *, 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
+ LoRAs), and descriptors whose byte range does not match their declared
+ shape — a truncated download would otherwise be measured as garbage.
+ """
+ if not isinstance(desc, dict):
+ return None
+ spec = _DTYPES.get(desc.get("dtype"))
+ if spec is None:
+ return None
+ shape = desc.get("shape")
+ if not isinstance(shape, list) or not all(isinstance(d, int) and d >= 0 for d in shape):
+ return None
+ rank = len(shape)
+ if rank != 2 and not (allow_scalar and rank <= 1):
+ return None
+ offsets = desc.get("data_offsets")
+ if not isinstance(offsets, list) or len(offsets) != 2:
+ return None
+ start, end = offsets
+ if not isinstance(start, int) or not isinstance(end, int) or end < start:
+ return None
+ count = math.prod(shape) if shape else 1
+ if (end - start) != count * spec[1]:
+ return None
+ try:
+ handle.seek(payload_offset + start)
+ buf = handle.read(end - start)
+ except OSError:
+ return None
+ if len(buf) != end - start:
+ return None
+ if spec[0] is None:
+ # BF16 -> float32: bfloat16 IS the high half of a float32, so widen by
+ # dropping the stored halves into the high lanes of a zeroed pair array
+ # and viewing it. Shifting a `.astype(np.uint32)` copy would build two
+ # 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)
+ 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
+ # GEMMs below need. The default copy=True would memcpy the entire
+ # adapter for nothing, inline, right before a render claims memory.
+ arr = np.frombuffer(buf, dtype=spec[0]).astype(np.float32, copy=False)
+ return arr.reshape(shape) if shape else arr.reshape(())
+
+
+def _module_rms(np, down, up, scale: float) -> float:
+ """RMS magnitude of ``scale * (up @ down)`` — may be NaN/Inf; caller filters.
+
+ Warning suppression is scoped to exactly the two Gram products and the
+ reduction over them. Accelerate/OpenBLAS raise RuntimeWarning on overflow
+ while accumulating a diverged adapter, which is information we already
+ capture as a non-finite total — it must not reach the user as a warning
+ line next to an otherwise clean verdict.
+ """
+ out_features, rank = up.shape
+ _, in_features = down.shape
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"):
+ gram_up = up.T @ up # (rank, rank), symmetric
+ gram_down = down @ down.T # (rank, rank), symmetric
+ # trace(X @ Y) for symmetric X, Y is the elementwise sum of X * Y.
+ total = float(np.sum(gram_up * gram_down))
+ if not math.isfinite(total):
+ return total
+ # Cancellation in the reduction can push a genuinely-zero adapter a hair
+ # below 0; a negative squared norm is not a measurement, it is float noise.
+ if total < 0.0:
+ total = 0.0
+ elements = out_features * in_features
+ if elements <= 0:
+ return math.nan
+ return scale * math.sqrt(total) / math.sqrt(elements)
+
+
+def measure_lora_effect(path) -> dict:
+ """Measure every LoRA module in ``path`` and summarise the result.
+
+ Returns the report dict the JS side normalises (see
+ server/lib/loraEffect.js#normalizeLoraEffectReport). Never raises for a bad
+ file — an unreadable adapter is a status, not an exception.
+ """
+ report = {
+ "probeVersion": PROBE_VERSION,
+ "status": "unreadable",
+ "modules": 0,
+ "measured": 0,
+ "skippedNonFinite": 0,
+ "skippedUnsupported": 0,
+ "zeroModules": 0,
+ "medianRms": None,
+ "maxRms": None,
+ "reason": None,
+ }
+ try:
+ import numpy as np
+ except ImportError as err: # pragma: no cover - environment-dependent
+ report["status"] = "unmeasurable"
+ report["reason"] = f"numpy is not installed in this interpreter ({err})"
+ return report
+
+ path = Path(path)
+ header, payload_offset = read_header(path)
+ if header is None:
+ report["reason"] = f"{path.name} is not a readable safetensors file"
+ return report
+
+ modules = pair_lora_modules(header)
+ report["modules"] = len(modules)
+ if not modules:
+ report["reason"] = f"{path.name} contains no lora_A/lora_B (or lora_down/lora_up) pairs"
+ return report
+
+ values: list[float] = []
+ try:
+ 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"]))
+ # 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.
+ if down is None or up is None or up.shape[1] != down.shape[0]:
+ report["skippedUnsupported"] += 1
+ continue
+ 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)
+ 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
+ rms = _module_rms(np, down, up, scale)
+ if not math.isfinite(rms):
+ report["skippedNonFinite"] += 1
+ continue
+ values.append(rms)
+
+ report["measured"] = len(values)
+ if not values:
+ if report["skippedNonFinite"]:
+ report["status"] = "nonfinite"
+ report["reason"] = (
+ f"every one of {report['skippedNonFinite']} LoRA module(s) measured NaN or Infinity "
+ "— the adapter's weights are diverged"
+ )
+ else:
+ report["reason"] = (
+ f"none of {report['modules']} LoRA module pair(s) could be measured "
+ "(unsupported dtype, non-2-D shape, or truncated file)"
+ )
+ return report
+
+ 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):
+ report["status"] = "zero"
+ report["reason"] = (
+ f"all {len(values)} measurable LoRA module(s) have exactly zero effect "
+ "— fusing it would change nothing"
+ )
+ else:
+ report["status"] = "ok"
+ return report
+
+
+def format_effect(report: dict) -> str:
+ """One-line human summary, for a render log or a status line."""
+ status = report.get("status")
+ if status not in ("ok", "zero"):
+ return f"{status}: {report.get('reason') or 'no measurement'}"
+ median = report.get("medianRms")
+ peak = report.get("maxRms")
+ parts = [
+ f"median RMS {median:.3e}" if isinstance(median, float) else "median RMS n/a",
+ f"max {peak:.3e}" if isinstance(peak, float) else "max n/a",
+ f"across {report.get('measured', 0)} module(s)",
+ ]
+ skipped = report.get("skippedNonFinite") or 0
+ if skipped:
+ parts.append(f"{skipped} non-finite skipped")
+ return ", ".join(parts)
+
+
+def main(argv: list[str]) -> int:
+ if len(argv) != 2:
+ print("usage: lora_effect_probe.py <path-to.safetensors>", file=sys.stderr)
+ return EXIT_USAGE
+ report = measure_lora_effect(argv[1])
+ print("RESULT:" + json.dumps(report), flush=True)
+ # A distinct code lets the Node caller advance to the next candidate
+ # interpreter instead of reporting a missing numpy as a verdict about the
+ # adapter. Every other status is a real answer and exits 0.
+ return EXIT_NO_NUMPY if report["status"] == "unmeasurable" else EXIT_OK
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv))
diff --git a/scripts/lora_effect_probe_test.py b/scripts/lora_effect_probe_test.py
new file mode 100644
index 0000000000..b3ffb5aff0
--- /dev/null
+++ b/scripts/lora_effect_probe_test.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python3
+"""Standalone tests for lora_effect_probe.py (no pytest; numpy required).
+
+Run: ~/.portos/ltx-2-mlx/.venv/bin/python3 scripts/lora_effect_probe_test.py
+(or any interpreter with numpy — the probe needs it to measure anything).
+Exits non-zero on first failure. Mirrors the runnable-test style of
+scripts/_runner_common_test.py.
+
+Fixtures are synthesised in a temp dir rather than checked in: a real LoRA is
+hundreds of MB, and the interesting cases (all-zero B, NaN weights, BF16
+storage, a truncated payload) are precisely the ones no published adapter
+provides.
+"""
+
+import json
+import math
+import struct
+import sys
+import tempfile
+from pathlib import Path
+
+# ✅/❌ are cp1252-unencodable on a Windows console, which would abort the run
+# before the first result printed.
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from lora_effect_probe import ( # noqa: E402
+ PROBE_VERSION,
+ format_effect,
+ measure_lora_effect,
+ pair_lora_modules,
+ read_header,
+)
+
+try:
+ import numpy as np
+except ImportError: # pragma: no cover - environment-dependent
+ print("SKIP: numpy is not installed in this interpreter")
+ raise SystemExit(0)
+
+FAILS = []
+
+
+def check(name, cond):
+ print(("✅" if cond else "❌") + " " + name)
+ if not cond:
+ FAILS.append(name)
+
+
+_DTYPE_TAGS = {np.dtype("float32"): "F32", np.dtype("float16"): "F16", np.dtype("float64"): "F64"}
+
+
+def write_safetensors(path, tensors, *, truncate_payload=0):
+ """Minimal safetensors writer: {name: ndarray} (or ('BF16', ndarray))."""
+ header = {}
+ blobs = []
+ offset = 0
+ for name, value in tensors.items():
+ if isinstance(value, tuple) and value[0] == "BF16":
+ arr = np.asarray(value[1], dtype=np.float32)
+ # bfloat16 IS the high half of a float32 — store the top 16 bits.
+ raw = (arr.view(np.uint32) >> np.uint32(16)).astype("<u2").tobytes()
+ tag = "BF16"
+ else:
+ arr = np.asarray(value)
+ tag = _DTYPE_TAGS[arr.dtype]
+ raw = arr.astype(arr.dtype.newbyteorder("<")).tobytes()
+ header[name] = {"dtype": tag, "shape": list(arr.shape), "data_offsets": [offset, offset + len(raw)]}
+ blobs.append(raw)
+ offset += len(raw)
+ blob = json.dumps(header).encode("utf-8")
+ payload = b"".join(blobs)
+ if truncate_payload:
+ payload = payload[:-truncate_payload]
+ Path(path).write_bytes(struct.pack("<Q", len(blob)) + blob + payload)
+
+
+def bare_pair(prefix, down, up):
+ return {f"{prefix}.lora_A.weight": down, f"{prefix}.lora_B.weight": up}
+
+
+def run(tmp):
+ # --- header reading -----------------------------------------------------
+ good = tmp / "good.safetensors"
+ write_safetensors(good, bare_pair("blocks.0.attn", np.ones((2, 4), np.float32), np.ones((4, 2), np.float32)))
+ header, offset = read_header(good)
+ check("read_header parses a well-formed file", isinstance(header, dict) and offset > 8)
+
+ junk = tmp / "junk.safetensors"
+ junk.write_bytes(b"not-safetensors-at-all")
+ check("read_header returns None for a non-safetensors blob", read_header(junk) == (None, 0))
+
+ absurd = tmp / "absurd.safetensors"
+ absurd.write_bytes(struct.pack("<Q", 2**40) + b"{}")
+ check("read_header refuses an absurd header length", read_header(absurd) == (None, 0))
+
+ # --- pairing ------------------------------------------------------------
+ paired = 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("kohya alpha is attached to its module", paired["k"].get("alpha") == "k.alpha")
+
+ # --- a healthy adapter --------------------------------------------------
+ rng = np.random.default_rng(7)
+ healthy = tmp / "healthy.safetensors"
+ write_safetensors(healthy, {
+ **bare_pair("blocks.0.attn.to_q", rng.normal(size=(8, 64)).astype(np.float32),
+ rng.normal(size=(64, 8)).astype(np.float32)),
+ **bare_pair("blocks.1.attn.to_q", (rng.normal(size=(8, 64)) * 0.01).astype(np.float32),
+ (rng.normal(size=(64, 8)) * 0.01).astype(np.float32)),
+ })
+ report = measure_lora_effect(healthy)
+ check("healthy adapter reports ok", report["status"] == "ok")
+ check("healthy adapter measured both modules", report["measured"] == 2 and report["modules"] == 2)
+ check("healthy adapter stamps the probe version", report["probeVersion"] == PROBE_VERSION)
+ check("max >= median > 0", report["maxRms"] >= report["medianRms"] > 0)
+ check("no non-finite skips on clean weights", report["skippedNonFinite"] == 0)
+
+ # The Gram-trick result must equal the direct product's RMS.
+ down = rng.normal(size=(4, 32)).astype(np.float32)
+ up = rng.normal(size=(48, 4)).astype(np.float32)
+ exact = tmp / "exact.safetensors"
+ write_safetensors(exact, bare_pair("only", down, up))
+ direct = float(np.sqrt(np.mean((up @ down).astype(np.float64) ** 2)))
+ measured = measure_lora_effect(exact)["maxRms"]
+ check("Gram-trick RMS matches the direct product", math.isclose(measured, direct, rel_tol=1e-4))
+
+ # --- the one refusable case: entirely zero ------------------------------
+ dead = tmp / "dead.safetensors"
+ write_safetensors(dead, {
+ **bare_pair("a", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ **bare_pair("b", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ })
+ report = measure_lora_effect(dead)
+ check("all-zero adapter reports zero", report["status"] == "zero")
+ check("zero adapter counts every module as zero", report["zeroModules"] == report["measured"] == 2)
+ check("zero adapter explains itself", "zero effect" in (report["reason"] or ""))
+
+ # One live module is enough to keep the adapter usable — a partially-zero
+ # adapter must NOT be refused.
+ partial = tmp / "partial.safetensors"
+ write_safetensors(partial, {
+ **bare_pair("a", rng.normal(size=(8, 64)).astype(np.float32), np.zeros((64, 8), np.float32)),
+ **bare_pair("b", rng.normal(size=(8, 64)).astype(np.float32), rng.normal(size=(64, 8)).astype(np.float32)),
+ })
+ report = measure_lora_effect(partial)
+ check("one live module keeps the adapter ok", report["status"] == "ok")
+ check("partial adapter still reports its zero count", report["zeroModules"] == 1)
+
+ # --- non-finite handling ------------------------------------------------
+ nan_up = np.full((64, 8), np.nan, np.float32)
+ diverged = tmp / "diverged.safetensors"
+ write_safetensors(diverged, bare_pair("a", rng.normal(size=(8, 64)).astype(np.float32), nan_up))
+ report = measure_lora_effect(diverged)
+ check("all-NaN adapter reports nonfinite (not zero)", report["status"] == "nonfinite")
+ check("nonfinite adapter has no invented statistics", report["medianRms"] is None and report["maxRms"] is None)
+
+ # A NaN module must be excluded, leaving the healthy module's numbers intact.
+ healthy_down = rng.normal(size=(8, 64)).astype(np.float32)
+ healthy_up = rng.normal(size=(64, 8)).astype(np.float32)
+ clean = tmp / "clean.safetensors"
+ write_safetensors(clean, bare_pair("good", healthy_down, healthy_up))
+ mixed = tmp / "mixed.safetensors"
+ write_safetensors(mixed, {
+ **bare_pair("good", healthy_down, healthy_up),
+ **bare_pair("bad", rng.normal(size=(8, 64)).astype(np.float32), np.full((64, 8), np.inf, np.float32)),
+ })
+ clean_report = measure_lora_effect(clean)
+ mixed_report = measure_lora_effect(mixed)
+ check("a diverged module is skipped, not aggregated", mixed_report["skippedNonFinite"] == 1)
+ check("statistics stay stable when a module is skipped",
+ mixed_report["medianRms"] == clean_report["medianRms"] and mixed_report["status"] == "ok")
+
+ # --- dtype coverage -----------------------------------------------------
+ bf16 = tmp / "bf16.safetensors"
+ bf16_down = np.round(rng.normal(size=(4, 32)) * 4).astype(np.float32) / 256
+ bf16_up = np.round(rng.normal(size=(32, 4)) * 4).astype(np.float32) / 256
+ write_safetensors(bf16, {
+ "m.lora_A.weight": ("BF16", bf16_down),
+ "m.lora_B.weight": ("BF16", bf16_up),
+ })
+ report = measure_lora_effect(bf16)
+ check("BF16 weights are measured", report["status"] == "ok" and report["measured"] == 1)
+
+ fp16 = tmp / "fp16.safetensors"
+ write_safetensors(fp16, bare_pair("m", bf16_down.astype(np.float16), bf16_up.astype(np.float16)))
+ check("F16 weights are measured", measure_lora_effect(fp16)["status"] == "ok")
+
+ # --- kohya alpha scaling ------------------------------------------------
+ k_down = rng.normal(size=(8, 64)).astype(np.float32)
+ k_up = rng.normal(size=(64, 8)).astype(np.float32)
+ no_alpha = tmp / "kohya_plain.safetensors"
+ write_safetensors(no_alpha, {"m.lora_down.weight": k_down, "m.lora_up.weight": k_up})
+ with_alpha = tmp / "kohya_alpha.safetensors"
+ write_safetensors(with_alpha, {
+ "m.lora_down.weight": k_down,
+ "m.lora_up.weight": k_up,
+ "m.alpha": np.asarray(4.0, np.float32),
+ })
+ plain_rms = measure_lora_effect(no_alpha)["maxRms"]
+ alpha_rms = measure_lora_effect(with_alpha)["maxRms"]
+ check("kohya layout is measured too", isinstance(plain_rms, float) and plain_rms > 0)
+ check("alpha/rank scales the measurement", math.isclose(alpha_rms, plain_rms * 0.5, rel_tol=1e-6))
+
+ # --- unmeasurable / unreadable inputs -----------------------------------
+ check("a missing file is unreadable", measure_lora_effect(tmp / "nope.safetensors")["status"] == "unreadable")
+
+ checkpoint = tmp / "checkpoint.safetensors"
+ write_safetensors(checkpoint, {"model.diffusion.weight": np.ones((4, 4), np.float32)})
+ report = measure_lora_effect(checkpoint)
+ check("a checkpoint with no LoRA pairs is unreadable", report["status"] == "unreadable" and report["modules"] == 0)
+
+ conv = tmp / "conv.safetensors"
+ write_safetensors(conv, bare_pair("m", np.ones((2, 4, 1, 1), np.float32), np.ones((4, 2, 1, 1), np.float32)))
+ report = measure_lora_effect(conv)
+ check("4-D (conv) modules are skipped as unsupported", report["skippedUnsupported"] == 1 and report["measured"] == 0)
+
+ mismatched = tmp / "mismatch.safetensors"
+ write_safetensors(mismatched, bare_pair("m", np.ones((2, 4), np.float32), np.ones((4, 3), np.float32)))
+ check("a rank mismatch is skipped, never transposed into a guess",
+ measure_lora_effect(mismatched)["skippedUnsupported"] == 1)
+
+ truncated = tmp / "truncated.safetensors"
+ write_safetensors(truncated, bare_pair("m", np.ones((2, 4), np.float32), np.ones((4, 2), np.float32)),
+ truncate_payload=8)
+ report = measure_lora_effect(truncated)
+ check("a truncated payload is skipped, not measured as garbage", report["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)
+ check("format_effect surfaces a non-ok reason",
+ "unreadable" in format_effect(measure_lora_effect(checkpoint)))
+
+
+with tempfile.TemporaryDirectory() as td:
+ run(Path(td))
+
+print()
+if FAILS:
+ print(f"❌ {len(FAILS)} failed: {', '.join(FAILS)}")
+ raise SystemExit(1)
+print("✅ all lora_effect_probe tests passed")
diff --git a/server/lib/README.md b/server/lib/README.md
index e3d7306935..b224289a35 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -209,6 +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. |
| `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/index.js b/server/lib/index.js
index 418338a9aa..7924e45f51 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -200,6 +200,7 @@ export * from './localMemory.js';
export * from './pgFileFacade.js';
export * from './multipart.js';
export * from './safetensors.js';
+export * from './loraEffect.js';
export * from './assetHash.js';
export * from './pdfImageEmbed.js';
export * from './zipStream.js';
diff --git a/server/lib/loraEffect.js b/server/lib/loraEffect.js
new file mode 100644
index 0000000000..442b5f69e7
--- /dev/null
+++ b/server/lib/loraEffect.js
@@ -0,0 +1,166 @@
+/**
+ * LoRA adapter-effect report — normalization, freshness and verdict rules.
+ *
+ * The measurement itself lives in `scripts/lora_effect_probe.py` (it needs
+ * numpy to multiply the rank matrices); this module owns everything PortOS
+ * decides ABOUT a measurement, so the rules are testable without spawning a
+ * Python child and are identical whether a report arrives fresh from the probe
+ * or is read back out of a LoRA sidecar written by an older install.
+ *
+ * Why a report at all: the existing gates (`assertSafeLoraFilename`,
+ * `verifySafetensorsStructure`, `classifyLoraKeyLayout`, the runtime-capability
+ * probe) all answer "is this file shaped like a LoRA this runtime can load".
+ * None of them answers "does it actually change anything", which is the
+ * question worth answering before a multi-minute video render. A structurally
+ * perfect adapter can still carry all-zero `lora_B` weights or NaN deltas.
+ *
+ * Finite-safety is the contract, in both directions:
+ * - The probe skips non-finite MODULE totals before computing median/max, so
+ * one diverged module cannot NaN out the whole summary.
+ * - This module then refuses to trust a non-finite NUMBER that reaches it
+ * anyway (a hand-edited sidecar, a future probe version, JSON `null`), so
+ * no consumer has to defend against NaN leaking into a UI or a comparison.
+ *
+ * Verdict policy: `zero` — and only `zero` — blocks a render. A `nonfinite`
+ * adapter is reported loudly but not refused, and there is deliberately no
+ * "weak" verdict: a small median is a number for a human to read, not a
+ * threshold to fail on, and inventing one would refuse working subtle LoRAs.
+ */
+
+import { isPlainObject } from './objects.js';
+
+// Bumped in lockstep with PROBE_VERSION in scripts/lora_effect_probe.py. A
+// cached report stamped with a different version is stale by definition — the
+// measurement or the status vocabulary changed under it — so it is dropped and
+// re-probed rather than reinterpreted.
+export const LORA_EFFECT_PROBE_VERSION = 1;
+
+export const LORA_EFFECT_STATUSES = Object.freeze({
+ // At least one finite, non-zero module measurement.
+ OK: 'ok',
+ // Measurements exist and every one is exactly zero — provably inert.
+ ZERO: 'zero',
+ // Modules were found but every measurement was NaN/Infinity.
+ NONFINITE: 'nonfinite',
+ // No measurable LoRA module pairs (not a LoRA, unsupported dtype, truncated).
+ UNREADABLE: 'unreadable',
+ // The probe could not run at all (no interpreter with numpy, timeout, crash).
+ // Never a statement about the adapter — only about this machine.
+ UNMEASURABLE: 'unmeasurable',
+});
+
+export const LORA_EFFECT_STATUS_VALUES = Object.freeze(Object.values(LORA_EFFECT_STATUSES));
+
+export const isKnownLoraEffectStatus = (status) => LORA_EFFECT_STATUS_VALUES.includes(status);
+
+// Non-finite in, `null` out. `Number.isFinite` alone would let a numeric string
+// through as `false` and a boolean `true` through as... also false — so the
+// typeof check is what actually pins the type.
+const finiteOrNull = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
+
+const nonNegativeInt = (value) => {
+ const n = finiteOrNull(value);
+ return n == null || n < 0 ? 0 : Math.floor(n);
+};
+
+/**
+ * Normalize a raw probe payload (or a sidecar-cached one) into the report shape
+ * every consumer reads. Returns `null` for a payload that isn't an object at
+ * 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.
+ */
+export const normalizeLoraEffectReport = (raw, { sizeBytes = null, measuredAt = null } = {}) => {
+ if (!isPlainObject(raw)) return null;
+ const status = isKnownLoraEffectStatus(raw.status) ? raw.status : LORA_EFFECT_STATUSES.UNMEASURABLE;
+ const measured = nonNegativeInt(raw.measured);
+ // 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
+ // refusal.
+ const stat = (value) => (measured > 0 ? finiteOrNull(value) : null);
+ return {
+ probeVersion: nonNegativeInt(raw.probeVersion),
+ status,
+ modules: nonNegativeInt(raw.modules),
+ measured,
+ skippedNonFinite: nonNegativeInt(raw.skippedNonFinite),
+ skippedUnsupported: nonNegativeInt(raw.skippedUnsupported),
+ zeroModules: nonNegativeInt(raw.zeroModules),
+ medianRms: stat(raw.medianRms),
+ maxRms: stat(raw.maxRms),
+ reason: typeof raw.reason === 'string' && raw.reason ? raw.reason : null,
+ sizeBytes: finiteOrNull(sizeBytes),
+ measuredAt: typeof measuredAt === 'string' && measuredAt ? measuredAt : null,
+ };
+};
+
+/**
+ * Is a cached report still about the file on disk right now? Module-private —
+ * `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.
+ */
+const isLoraEffectReportFresh = (report, { sizeBytes } = {}) => {
+ 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;
+};
+
+/**
+ * The report a passive read may surface: a normalized, still-fresh cached one,
+ * 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;
+};
+
+/**
+ * Why this adapter must not be used, as a user-facing phrase — or `null` when
+ * there is no such reason. ONLY a measured, entirely-zero adapter qualifies.
+ *
+ * Everything else is permissive by design: `unmeasurable` says nothing about
+ * the file, `unreadable` is already the key-layout gate's territory, and
+ * `nonfinite` — while a real problem — is a diverged training run the user may
+ * still want to see rendered. Refusing on anything we did not positively
+ * measure would turn a machine without numpy into a machine that cannot render.
+ */
+export const loraEffectIssue = (report) => {
+ if (!report || report.status !== LORA_EFFECT_STATUSES.ZERO) return null;
+ return report.reason
+ || 'every measurable module in it has exactly zero effect, so fusing it would change nothing';
+};
+
+/** One-line human summary for a log line or a card subtitle. */
+export const formatLoraEffect = (report) => {
+ if (!report) return 'not measured';
+ // Both statistics, not just `measured`: normalizeLoraEffectReport nulls a
+ // non-finite value, so a measured report can still arrive with no renderable
+ // number — and `null.toExponential()` inside a render path is a crash.
+ if (report.measured <= 0 || !Number.isFinite(report.medianRms) || !Number.isFinite(report.maxRms)) {
+ return `${report.status}${report.reason ? `: ${report.reason}` : ''}`;
+ }
+ const parts = [
+ `median RMS ${report.medianRms.toExponential(2)}`,
+ `max ${report.maxRms.toExponential(2)}`,
+ `across ${report.measured} module(s)`,
+ ];
+ if (report.skippedNonFinite > 0) parts.push(`${report.skippedNonFinite} non-finite skipped`);
+ if (report.skippedUnsupported > 0) parts.push(`${report.skippedUnsupported} unsupported skipped`);
+ if (report.zeroModules > 0) parts.push(`${report.zeroModules} zero`);
+ return parts.join(', ');
+};
diff --git a/server/lib/loraEffect.parity.test.js b/server/lib/loraEffect.parity.test.js
new file mode 100644
index 0000000000..d36ea2bcf4
--- /dev/null
+++ b/server/lib/loraEffect.parity.test.js
@@ -0,0 +1,98 @@
+/**
+ * Cross-package parity for the LoRA adapter-effect report vocabulary (#4872).
+ *
+ * `server/lib/loraEffect.js` is the source of truth — it decides which verdict
+ * refuses a render and what a measurement is called. `client/src/lib/loraEffect.js`
+ * mirrors the status list and the summary wording so a manager card and a render
+ * log describe one measurement the same way. When they disagree the user reads
+ * one thing on the card and gets another at render time; this suite fails CI
+ * instead of letting that ship.
+ *
+ * It lives server-side because the server module is the authority; both copies
+ * are pure and load fine under the node runner.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ LORA_EFFECT_STATUSES as SERVER_STATUSES,
+ formatLoraEffect as serverFormat,
+ loraEffectIssue,
+ normalizeLoraEffectReport,
+} from './loraEffect.js';
+import {
+ LORA_EFFECT_STATUSES as CLIENT_STATUSES,
+ LORA_EFFECT_BADGES,
+ formatLoraEffect as clientFormat,
+ loraEffectBadge,
+} from '../../client/src/lib/loraEffect.js';
+
+// Every report shape the two formatters must agree on: a plain measurement, one
+// with each skip counter, a partially-zero adapter, and the three "no numbers"
+// cases (never measured, statistics nulled as non-finite, no reason at all).
+const REPORTS = [
+ { status: 'ok', measured: 10, medianRms: 0.0031, maxRms: 0.0184, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null },
+ { status: 'ok', measured: 8, medianRms: 1e-9, maxRms: 2.5e-8, skippedNonFinite: 2, skippedUnsupported: 0, zeroModules: 0, reason: null },
+ { status: 'ok', measured: 8, medianRms: 0.004, maxRms: 0.02, skippedNonFinite: 0, skippedUnsupported: 5, zeroModules: 0, reason: null },
+ { status: 'ok', measured: 4, medianRms: 0.004, maxRms: 0.02, skippedNonFinite: 1, skippedUnsupported: 2, zeroModules: 3, reason: null },
+ { status: 'zero', measured: 6, medianRms: 0, maxRms: 0, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 6, reason: 'all 6 measurable LoRA module(s) have exactly zero effect' },
+ { status: 'unreadable', measured: 0, medianRms: null, maxRms: null, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: 'contains no lora_A/lora_B pairs' },
+ { status: 'nonfinite', measured: 0, medianRms: null, maxRms: null, skippedNonFinite: 12, skippedUnsupported: 0, zeroModules: 0, reason: 'every module measured NaN' },
+ { status: 'unmeasurable', measured: 0, medianRms: null, maxRms: null, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null },
+ { status: 'ok', measured: 3, medianRms: null, maxRms: 0.2, skippedNonFinite: 0, skippedUnsupported: 0, zeroModules: 0, reason: null },
+];
+
+describe('loraEffect parity — server vs client', () => {
+ it('mirrors the status vocabulary exactly', () => {
+ expect(CLIENT_STATUSES).toEqual(SERVER_STATUSES);
+ });
+
+ it('gives every status a badge, so a new verdict can never render as a bare slug', () => {
+ expect(Object.keys(LORA_EFFECT_BADGES).sort()).toEqual(Object.values(SERVER_STATUSES).sort());
+ for (const status of Object.values(SERVER_STATUSES)) {
+ expect(loraEffectBadge(status).label).toBeTruthy();
+ expect(loraEffectBadge(status).tone).toBeTruthy();
+ }
+ });
+
+ it('styles exactly the refusing verdict as an error', () => {
+ // The client must not invent a second blocking-looking status: whichever
+ // statuses `loraEffectIssue` refuses on are the ones allowed error styling.
+ const refused = Object.values(SERVER_STATUSES)
+ .filter((status) => loraEffectIssue({ status, reason: 'x' }) !== null);
+ const errorStyled = Object.entries(LORA_EFFECT_BADGES)
+ .filter(([, badge]) => badge.tone.includes('port-error'))
+ .map(([status]) => status);
+ expect(errorStyled).toEqual(refused);
+ expect(refused).toEqual([SERVER_STATUSES.ZERO]);
+ });
+
+ it('formats a measured report identically to the server', () => {
+ // Whenever the server prints statistics, the two must be byte-identical —
+ // that is the drift this suite exists to catch.
+ for (const raw of REPORTS) {
+ const report = normalizeLoraEffectReport(raw);
+ if (report.measured <= 0 || report.medianRms === null || report.maxRms === null) continue;
+ expect(clientFormat(report)).toBe(serverFormat(report));
+ expect(clientFormat(report)).toContain('median RMS');
+ }
+ });
+
+ it('drops to the reason (never the badge word) where the server prints its status', () => {
+ // The server's no-statistics fallback is `status[: reason]`, but the client
+ // already renders the status as a badge beside this text — echoing it would
+ // read "Unreadable — Unreadable". So the client contributes the reason, or
+ // nothing at all, and the card omits the separator.
+ for (const raw of REPORTS) {
+ const report = normalizeLoraEffectReport(raw);
+ if (report.measured > 0 && report.medianRms !== null && report.maxRms !== null) continue;
+ expect(serverFormat(report).startsWith(report.status)).toBe(true);
+ expect(clientFormat(report)).toBe(report.reason);
+ expect(clientFormat(report)).not.toBe(loraEffectBadge(report.status).label);
+ }
+ });
+
+ it('agrees that a null report has nothing to format', () => {
+ expect(clientFormat(null)).toBeNull();
+ expect(serverFormat(null)).toBe('not measured');
+ });
+});
diff --git a/server/lib/loraEffect.test.js b/server/lib/loraEffect.test.js
new file mode 100644
index 0000000000..517ec431cc
--- /dev/null
+++ b/server/lib/loraEffect.test.js
@@ -0,0 +1,184 @@
+/**
+ * LoRA adapter-effect report rules (#4872).
+ *
+ * The measurement lives in Python; everything asserted here is the JS-side
+ * policy that decides what a measurement MEANS — which is what a render, a
+ * sidecar cache and a UI badge all depend on being identical.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ LORA_EFFECT_PROBE_VERSION,
+ LORA_EFFECT_STATUSES,
+ LORA_EFFECT_STATUS_VALUES,
+ formatLoraEffect,
+ isKnownLoraEffectStatus,
+ loraEffectIssue,
+ normalizeLoraEffectReport,
+ readCachedLoraEffectReport,
+} from './loraEffect.js';
+
+const okPayload = {
+ probeVersion: LORA_EFFECT_PROBE_VERSION,
+ status: 'ok',
+ modules: 12,
+ measured: 10,
+ skippedNonFinite: 2,
+ skippedUnsupported: 0,
+ zeroModules: 1,
+ medianRms: 0.0031,
+ maxRms: 0.0184,
+ reason: null,
+};
+
+describe('normalizeLoraEffectReport', () => {
+ it('returns null for anything that is not a payload object', () => {
+ for (const raw of [null, undefined, 'ok', 42, [okPayload]]) {
+ expect(normalizeLoraEffectReport(raw)).toBeNull();
+ }
+ });
+
+ 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' });
+ 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',
+ });
+ });
+
+ it('degrades an unrecognized status to unmeasurable rather than propagating it', () => {
+ // A sidecar written by a future PortOS (or hand-edited) must not smuggle a
+ // status word past the verdict rules — least of all one that could be read
+ // as a refusal.
+ expect(normalizeLoraEffectReport({ ...okPayload, status: 'catastrophic' }).status)
+ .toBe(LORA_EFFECT_STATUSES.UNMEASURABLE);
+ expect(normalizeLoraEffectReport({ ...okPayload, status: undefined }).status)
+ .toBe(LORA_EFFECT_STATUSES.UNMEASURABLE);
+ });
+
+ it('nulls every non-finite statistic instead of leaking NaN/Infinity to consumers', () => {
+ const report = normalizeLoraEffectReport({
+ ...okPayload, medianRms: NaN, maxRms: Infinity
+ });
+ expect(report.medianRms).toBeNull();
+ expect(report.maxRms).toBeNull();
+ });
+
+ it('rejects a numeric-looking non-number statistic', () => {
+ expect(normalizeLoraEffectReport({ ...okPayload, medianRms: '0.5' }).medianRms).toBeNull();
+ expect(normalizeLoraEffectReport({ ...okPayload, maxRms: true }).maxRms).toBeNull();
+ });
+
+ it('drops statistics entirely when nothing was measured', () => {
+ // The trap this closes: a payload claiming `measured: 0, medianRms: 0`
+ // would otherwise read as "measured, and it is 0.0" — which is the exact
+ // shape `zero` uses, and `zero` is the one status that refuses a render.
+ const report = normalizeLoraEffectReport({ ...okPayload, measured: 0, medianRms: 0, maxRms: 0 });
+ expect(report.measured).toBe(0);
+ expect(report.medianRms).toBeNull();
+ expect(report.maxRms).toBeNull();
+ });
+
+ it('floors negative and fractional counts to sane non-negative integers', () => {
+ const report = normalizeLoraEffectReport({ ...okPayload, modules: -5, measured: 3.7, skippedNonFinite: NaN });
+ expect(report.modules).toBe(0);
+ expect(report.measured).toBe(3);
+ expect(report.skippedNonFinite).toBe(0);
+ });
+
+ it('normalizes an empty reason to null', () => {
+ expect(normalizeLoraEffectReport({ ...okPayload, reason: '' }).reason).toBeNull();
+ expect(normalizeLoraEffectReport({ ...okPayload, reason: 7 }).reason).toBeNull();
+ });
+});
+
+describe('isKnownLoraEffectStatus', () => {
+ it('accepts exactly the five statuses and nothing else', () => {
+ expect(LORA_EFFECT_STATUS_VALUES).toEqual(['ok', 'zero', 'nonfinite', 'unreadable', 'unmeasurable']);
+ for (const s of LORA_EFFECT_STATUS_VALUES) expect(isKnownLoraEffectStatus(s)).toBe(true);
+ for (const s of ['weak', 'OK', '', null, undefined]) expect(isKnownLoraEffectStatus(s)).toBe(false);
+ });
+});
+
+describe('readCachedLoraEffectReport', () => {
+ const cached = { ...okPayload, sizeBytes: 4096, measuredAt: '2026-08-23T00:00:00.000Z' };
+
+ 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('drops a report whose file has changed size underneath it', () => {
+ expect(readCachedLoraEffectReport(cached, 8192)).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();
+ });
+
+ 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('returns null for a missing sidecar field rather than a hollow report', () => {
+ expect(readCachedLoraEffectReport(undefined, 4096)).toBeNull();
+ });
+});
+
+describe('loraEffectIssue', () => {
+ it('refuses a measured entirely-zero adapter, carrying the probe reason', () => {
+ const report = normalizeLoraEffectReport({
+ ...okPayload, status: 'zero', measured: 4, zeroModules: 4,
+ medianRms: 0, maxRms: 0, reason: 'all 4 measurable LoRA module(s) have exactly zero effect',
+ });
+ expect(loraEffectIssue(report)).toMatch(/zero effect/);
+ });
+
+ it('still refuses a zero verdict that arrived without a reason', () => {
+ expect(loraEffectIssue({ status: 'zero' })).toMatch(/zero effect/);
+ });
+
+ 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();
+ }
+ expect(loraEffectIssue(null)).toBeNull();
+ expect(loraEffectIssue(undefined)).toBeNull();
+ });
+
+ it('does not invent a "too weak" refusal for a tiny but non-zero measurement', () => {
+ const weak = normalizeLoraEffectReport({ ...okPayload, medianRms: 1e-12, maxRms: 1e-11, zeroModules: 0 });
+ expect(loraEffectIssue(weak)).toBeNull();
+ });
+});
+
+describe('formatLoraEffect', () => {
+ it('summarizes a measurement with both statistics and the skip counts', () => {
+ const text = formatLoraEffect(normalizeLoraEffectReport(okPayload));
+ expect(text).toContain('median RMS 3.10e-3');
+ expect(text).toContain('max 1.84e-2');
+ expect(text).toContain('across 10 module(s)');
+ expect(text).toContain('2 non-finite skipped');
+ expect(text).toContain('1 zero');
+ });
+
+ it('falls back to status + reason when there is nothing measured', () => {
+ const report = normalizeLoraEffectReport({
+ ...okPayload, status: 'unreadable', measured: 0, reason: 'contains no lora_A/lora_B pairs',
+ });
+ expect(formatLoraEffect(report)).toBe('unreadable: contains no lora_A/lora_B pairs');
+ });
+
+ it('handles a null report', () => {
+ expect(formatLoraEffect(null)).toBe('not measured');
+ });
+
+ it('falls back to the status line rather than crashing on a nulled statistic', () => {
+ // normalizeLoraEffectReport turns a non-finite median into null while
+ // leaving `measured` intact, so `measured > 0` alone is not proof there is
+ // a number to format — and this runs inside a render path.
+ expect(formatLoraEffect({ status: 'ok', measured: 3, medianRms: null, maxRms: 0.2, reason: null }))
+ .toBe('ok');
+ });
+});
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index ef5344d797..c26a43a909 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -524,6 +524,26 @@ export const HF_HUB_PYTHON_RESOLVERS = Object.freeze([
resolveMinimaxMusic3MlxPython,
]);
+// Every venv PortOS provisions that carries numpy, in preference order — the
+// interpreter pool for numpy-only sidecars like scripts/lora_effect_probe.py,
+// which needs to run wherever the user happens to have set up a runtime (a bare
+// system python3 usually has no numpy at all).
+//
+// Kept HERE rather than in the consuming service for exactly the reason spelled
+// out above HF_HUB_PYTHON_RESOLVERS: a list assembled inside a consumer is a
+// list every new engine forgets. ADDING A RUNTIME: if its setup-image-video.sh
+// block installs numpy (torch, mlx and diffusers all pull it in, so this is
+// nearly every runtime), add its resolver here.
+//
+// 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.
+export const NUMPY_PYTHON_RESOLVERS = Object.freeze([
+ resolveFlux2Python,
+ resolveMfluxPython,
+ ...HF_HUB_PYTHON_RESOLVERS,
+]);
+
// MuScriptor (audio → MIDI transcription for the Rounds workbench + Music Video
// parsing, #reference-audio-to-midi) runs in its own venv at
// ~/.portos/venv-muscriptor — the `muscriptor` pip package pulls its own torch
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 0595495951..8bc884b013 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -20,6 +20,7 @@ import {
listLoras,
patchLoraSidecar,
} from '../services/loras.js';
+import { probeLoraEffect } from '../services/loraEffectProbe.js';
import { getSuggestions, searchLorasInFamily } from '../services/civitaiSuggestions.js';
import { getVideoSuggestions } from '../services/videoLoraSuggestions.js';
import { findLorasByCharacter } from '../services/characterLoraResolver.js';
@@ -30,6 +31,10 @@ import { openSseStream } from '../lib/sseDownload.js';
const router = Router();
+// `?force=1` / `?force=true` busts a server-side cache. Shared by the suggestions
+// refresh and the LoRA effect re-check so the two can't drift on what counts.
+const forceRequested = (req) => req.query.force === '1' || req.query.force === 'true';
+
// Backward-compatible by default: returns the full LoRA array. When a client
// passes `limit`/`offset`, the response becomes the bounded
// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.
@@ -47,7 +52,7 @@ router.get('/', asyncHandler(async (req, res) => {
// Default 4 cards per family — enough to show breadth without overwhelming the
// panel; users can paste a URL for anything specific.
router.get('/suggestions', asyncHandler(async (req, res) => {
- const force = req.query.force === '1' || req.query.force === 'true';
+ const force = forceRequested(req);
const { limit } = parsePagination(req.query, { defaultLimit: 4, maxLimit: 24 });
const [civitai, video] = await Promise.all([
getSuggestions({ force, limit }),
@@ -220,6 +225,19 @@ router.get('/:filename', asyncHandler(async (req, res) => {
res.json(lora);
}));
+// Adapter-effect diagnostic (#4872) — the explicit, user-triggered inspection
+// path. Answers "does this LoRA actually change anything" by measuring the
+// rank matrices in the file, so a dead adapter is caught here rather than after
+// a multi-minute video render. Deliberately a POST: it spawns a Python child
+// and writes the measurement back to the sidecar, so it is not a cacheable GET.
+// `?force=1` re-measures instead of returning the stored report. Never 500s on
+// a probe failure — an unmeasurable verdict is a legitimate answer about this
+// machine, and the response carries its reason.
+router.post('/:filename/effect', asyncHandler(async (req, res) => {
+ const force = forceRequested(req);
+ res.json(await probeLoraEffect(req.params.filename, { force }));
+}));
+
const patchSchema = z.object({
// Only user-editable fields. Civitai-derived blocks (`civitai`, `file`,
// `runnerFamily`, `triggerWords`) are not patchable through this surface
diff --git a/server/routes/loras.test.js b/server/routes/loras.test.js
index d7ef4f9fe2..071ee1b858 100644
--- a/server/routes/loras.test.js
+++ b/server/routes/loras.test.js
@@ -18,6 +18,11 @@ vi.mock('../services/loras.js', () => ({
patchLoraSidecar: vi.fn(),
resolveCivitaiKey: vi.fn(async () => null),
}));
+// The effect probe spawns a Python child and writes the LoRA sidecar; the route
+// layer only has to hand it the filename and the force flag.
+vi.mock('../services/loraEffectProbe.js', () => ({
+ probeLoraEffect: vi.fn(async () => ({ status: 'ok', measured: 4, medianRms: 0.01, maxRms: 0.02 })),
+}));
vi.mock('../services/civitaiSuggestions.js', () => ({
getSuggestions: vi.fn(async () => ({ curated: [], runners: {}, fetchedAt: 'now' })),
searchLorasInFamily: vi.fn(async ({ runnerFamily, query, cursor, limit }) => ({
@@ -41,6 +46,7 @@ vi.mock('../services/settings.js', () => ({
const { default: lorasRoutes } = await import('./loras.js');
const { searchLorasInFamily } = await import('../services/civitaiSuggestions.js');
const { installFromHuggingface, listLoras } = await import('../services/loras.js');
+const { probeLoraEffect } = await import('../services/loraEffectProbe.js');
// Parse an SSE response body into an array of decoded frame objects.
const parseSseFrames = (text) => text
@@ -202,3 +208,40 @@ describe('GET /api/loras/suggestions', () => {
expect(res.body.video[0].repo).toBe('fal/ltx2.3-audio-reactive-lora');
});
});
+
+describe('POST /api/loras/:filename/effect', () => {
+ it('runs the probe for the named LoRA and returns its report', async () => {
+ vi.mocked(probeLoraEffect).mockClear();
+ const res = await request(makeApp()).post('/api/loras/style.safetensors/effect');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ status: 'ok', measured: 4 });
+ expect(probeLoraEffect).toHaveBeenCalledWith('style.safetensors', { force: false });
+ });
+
+ it('passes ?force=1 through so an explicit re-check bypasses the sidecar cache', async () => {
+ vi.mocked(probeLoraEffect).mockClear();
+ await request(makeApp()).post('/api/loras/style.safetensors/effect?force=1');
+ expect(probeLoraEffect).toHaveBeenCalledWith('style.safetensors', { force: true });
+ await request(makeApp()).post('/api/loras/style.safetensors/effect?force=true');
+ expect(probeLoraEffect).toHaveBeenLastCalledWith('style.safetensors', { force: true });
+ });
+
+ it('decodes an encoded filename rather than probing the escape sequence', async () => {
+ vi.mocked(probeLoraEffect).mockClear();
+ await request(makeApp()).post(`/api/loras/${encodeURIComponent('my style.safetensors')}/effect`);
+ expect(probeLoraEffect).toHaveBeenCalledWith('my style.safetensors', { force: false });
+ });
+
+ it('returns an unmeasurable verdict as a 200, not a 500 — it is an answer', async () => {
+ vi.mocked(probeLoraEffect).mockResolvedValueOnce({ status: 'unmeasurable', measured: 0, reason: 'numpy is not installed' });
+ const res = await request(makeApp()).post('/api/loras/style.safetensors/effect');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ status: 'unmeasurable', reason: 'numpy is not installed' });
+ });
+
+ it('surfaces an unsafe filename as a 400, not a probe run', async () => {
+ vi.mocked(probeLoraEffect).mockRejectedValueOnce(Object.assign(new Error('LoRA filename must end with .safetensors'), { status: 400, code: 'INVALID_INPUT' }));
+ const res = await request(makeApp()).post('/api/loras/evil.txt/effect');
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/server/services/loraEffectProbe.js b/server/services/loraEffectProbe.js
new file mode 100644
index 0000000000..8af743947a
--- /dev/null
+++ b/server/services/loraEffectProbe.js
@@ -0,0 +1,186 @@
+/**
+ * User-triggered LoRA adapter-effect diagnostic.
+ *
+ * Spawns `scripts/lora_effect_probe.py` against one installed LoRA and answers
+ * the question none of the existing gates do: does this adapter actually change
+ * anything? See `server/lib/loraEffect.js` for the verdict policy and
+ * `scripts/lora_effect_probe.py` for the measurement.
+ *
+ * Three properties this module exists to guarantee:
+ *
+ * 1. **Never on a passive read.** `listLoras()` surfaces a CACHED report and
+ * never calls in here. The probe runs only from the explicit inspection
+ * 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.
+ *
+ * 3. **Never fatal.** Every failure path — no interpreter, no numpy, spawn
+ * error, timeout, malformed output — resolves to an `unmeasurable` report.
+ * 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.
+ */
+
+import { existsSync } from 'fs';
+import { stat } from 'fs/promises';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
+import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';
+import { withAbortTimeout } from '../lib/abortTimeout.js';
+import {
+ LORA_EFFECT_STATUSES,
+ normalizeLoraEffectReport,
+ readCachedLoraEffectReport,
+} from '../lib/loraEffect.js';
+import { detectPython, NUMPY_PYTHON_RESOLVERS } from '../lib/pythonSetup.js';
+import { LTX2_VENV_PYTHON, LTX25_VENV_PYTHON } from './videoGen/runtimes.js';
+import { assertSafeLoraFilename, patchLoraSidecar, readSidecar } from './loras.js';
+
+export const LORA_EFFECT_PROBE_SCRIPT = join(PATHS.root, 'scripts', 'lora_effect_probe.py');
+
+// The measurement is CPU-trivial but I/O-bound: the rank matrices are scattered
+// through the file, so a cold-cache read touches most of it. A 1 GB video LoRA
+// measures in about a second; a 12 GB one took ~55s cold on a local SSD. This
+// 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.
+const PROBE_TIMEOUT_MS = 300_000;
+
+const installedCandidates = (paths) => [
+ ...new Set(paths.filter((p) => typeof p === 'string' && p && existsSync(p))),
+];
+
+// The probe needs numpy and nothing else, so it runs on whichever provisioned
+// venv exists — NUMPY_PYTHON_RESOLVERS (lib/pythonSetup.js) owns that roster so
+// a newly-provisioned runtime is added in one place. The LTX-2.x video venvs go
+// first because they are the runtimes that actually fuse video LoRAs, and their
+// paths live in videoGen/runtimes.js rather than pythonSetup.
+//
+// Ordered rather than single because a venv can exist without numpy; the probe
+// reports that with a distinct exit code so the loop advances to the next
+// interpreter instead of blaming the adapter.
+const probeInterpreterCandidates = async () => {
+ // `existsSync` here (rather than trusting the resolvers) keeps a spawn ENOENT
+ // out of the common path; a resolver that already checked pays only a stat.
+ const installed = installedCandidates([
+ LTX2_VENV_PYTHON,
+ LTX25_VENV_PYTHON,
+ ...NUMPY_PYTHON_RESOLVERS.map((resolve) => resolve()),
+ ]);
+ // detectPython() is awaited ONLY when no provisioned venv exists. It execs
+ // every system interpreter to read its arch (or shells out to `which`), which
+ // is several process launches — wasted on any machine that can actually fuse a
+ // video LoRA, since such a machine has one of the venvs above by definition.
+ if (installed.length) return installed;
+ return installedCandidates([await detectPython()]);
+};
+
+const unmeasurable = (reason) => normalizeLoraEffectReport({
+ status: LORA_EFFECT_STATUSES.UNMEASURABLE,
+ reason,
+});
+
+// One measurement per file at a time. A user mashing the inspect button, or a
+// render that selected the same LoRA twice, shares one child rather than
+// spawning a pile of interpreters against the same weights.
+const inFlight = createSingleFlight();
+
+const runProbeOnce = async (bin, filePath) => {
+ // 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
+ // `spawn` can still throw synchronously on a malformed argv, which rejects the
+ // promise it never catches. Letting that escape would take down a render over
+ // a diagnostic. withAbortTimeout owns the timer lifecycle and clears it on
+ // both settle paths.
+ let result;
+ try {
+ result = await withAbortTimeout(PROBE_TIMEOUT_MS, (signal) => runSidecarProcess({
+ bin,
+ args: [LORA_EFFECT_PROBE_SCRIPT, filePath],
+ signal,
+ }));
+ } catch (err) {
+ return 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'})`);
+};
+
+// 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 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');
+ }
+ // A cold read of a multi-GB adapter takes real time (see PROBE_TIMEOUT_MS),
+ // 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)`);
+ let last = null;
+ for (const bin of candidates) {
+ last = await runProbeOnce(bin, filePath);
+ // 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;
+ }
+ if (last.status === LORA_EFFECT_STATUSES.UNMEASURABLE) {
+ console.log(`⚠️ LoRA effect probe unavailable for ${filename}: ${last.reason || 'unknown'}`);
+ return last;
+ }
+ const report = normalizeLoraEffectReport(last, { sizeBytes, 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.
+ await patchLoraSidecar(filename, { effectReport: report }).catch((err) => {
+ console.log(`⚠️ Could not cache LoRA effect report for ${filename}: ${err?.message || err}`);
+ });
+ return report;
+};
+
+/**
+ * Measure one installed LoRA's adapter effect.
+ *
+ * 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.
+ */
+export const probeLoraEffect = async (filename, { force = false } = {}) => {
+ assertSafeLoraFilename(filename);
+ 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`);
+ }
+ const sizeBytes = fileStat.size;
+
+ if (!force) {
+ const cached = readCachedLoraEffectReport((await readSidecar(filename))?.effectReport, sizeBytes);
+ if (cached) return cached;
+ }
+
+ // The one catch that makes "never fatal" true for everything downstream of
+ // the cache check: an interpreter resolver that throws, a sidecar write that
+ // 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)
+ .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
new file mode 100644
index 0000000000..d767960337
--- /dev/null
+++ b/server/services/loraEffectProbe.test.js
@@ -0,0 +1,238 @@
+/**
+ * LoRA effect probe service (#4872) — spawn, fallback, cache, and the
+ * never-fatal contract.
+ *
+ * The Python measurement has its own runnable suite
+ * (scripts/lora_effect_probe_test.py). What matters here is everything AROUND
+ * it: that a passive read never lands in this module, that a missing numpy
+ * advances to the next interpreter instead of becoming a verdict about the
+ * adapter, and that no failure path can throw into a render.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const MOCK_LORAS_DIR = '/mock/loras';
+
+const state = vi.hoisted(() => ({
+ statResult: { size: 4096, isFile: () => true },
+ statThrows: false,
+ sidecar: null,
+ patched: [],
+ patchThrows: false,
+ existing: new Set(),
+ runs: [],
+ // filename -> { stdout, ok, canceled, reason }
+ responses: [],
+}));
+
+vi.mock('fs', () => ({ existsSync: vi.fn((p) => state.existing.has(p)) }));
+vi.mock('fs/promises', () => ({
+ stat: vi.fn(async () => {
+ if (state.statThrows) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
+ return state.statResult;
+ }),
+}));
+vi.mock('../lib/fileUtils.js', () => ({ PATHS: { root: '/mock/root', loras: MOCK_LORAS_DIR } }));
+
+vi.mock('../lib/sidecarProcess.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ runSidecarProcess: vi.fn(async ({ bin, args }) => {
+ state.runs.push({ bin, args });
+ return state.responses.shift() || { ok: true, stdout: '' };
+ }),
+}));
+
+vi.mock('../lib/pythonSetup.js', () => ({
+ detectPython: vi.fn(async () => '/usr/bin/python3'),
+ NUMPY_PYTHON_RESOLVERS: [() => '/venv/flux2/bin/python3', () => null, () => '/venv/music/bin/python3'],
+}));
+
+vi.mock('./videoGen/runtimes.js', () => ({
+ LTX2_VENV_PYTHON: '/venv/ltx2/bin/python3',
+ LTX25_VENV_PYTHON: '/venv/ltx25/bin/python3',
+}));
+
+vi.mock('./loras.js', () => ({
+ assertSafeLoraFilename: vi.fn((f) => {
+ if (!f || !f.endsWith('.safetensors')) throw new Error('LoRA filename must end with .safetensors');
+ }),
+ readSidecar: vi.fn(async () => state.sidecar),
+ patchLoraSidecar: vi.fn(async (filename, patch) => {
+ if (state.patchThrows) throw new Error('EACCES');
+ state.patched.push({ filename, patch });
+ return patch;
+ }),
+}));
+
+const resultLine = (payload) => `STAGE:measure\nRESULT:${JSON.stringify(payload)}\n`;
+
+const OK_PAYLOAD = {
+ probeVersion: 1, status: 'ok', modules: 4, measured: 4, skippedNonFinite: 0,
+ skippedUnsupported: 0, zeroModules: 0, medianRms: 0.002, maxRms: 0.01, minRms: 0.001, reason: null,
+};
+
+let probeLoraEffect;
+let LORA_EFFECT_PROBE_SCRIPT;
+
+beforeEach(async () => {
+ vi.resetModules();
+ state.statResult = { size: 4096, isFile: () => true };
+ state.statThrows = false;
+ state.sidecar = null;
+ state.patched = [];
+ state.patchThrows = false;
+ state.runs = [];
+ state.responses = [];
+ state.existing = new Set(['/venv/ltx2/bin/python3', '/venv/ltx25/bin/python3', '/usr/bin/python3']);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ ({ probeLoraEffect, LORA_EFFECT_PROBE_SCRIPT } = await import('./loraEffectProbe.js'));
+});
+
+describe('probeLoraEffect — happy path', () => {
+ it('spawns the shared probe against the resolved LoRA path and returns a normalized report', async () => {
+ state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs[0]).toEqual({
+ bin: '/venv/ltx2/bin/python3',
+ args: [LORA_EFFECT_PROBE_SCRIPT, `${MOCK_LORAS_DIR}/style.safetensors`],
+ });
+ expect(report).toMatchObject({ status: 'ok', measured: 4, medianRms: 0.002, sizeBytes: 4096 });
+ expect(report.measuredAt).toEqual(expect.any(String));
+ });
+
+ it('caches the measurement into the sidecar keyed by the file size', 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 }) },
+ });
+ });
+
+ it('returns the cached report without spawning anything', async () => {
+ state.sidecar = { effectReport: { ...OK_PAYLOAD, sizeBytes: 4096, 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.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.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);
+ expect(report.status).toBe('zero');
+ });
+});
+
+describe('probeLoraEffect — interpreter fallback', () => {
+ it('advances to the next interpreter when one has no numpy, and stops on a real answer', async () => {
+ state.responses = [
+ { ok: false, reason: 'exit 3', stdout: resultLine({ status: 'unmeasurable', reason: 'numpy is not installed in this interpreter' }) },
+ { ok: true, stdout: resultLine(OK_PAYLOAD) },
+ ];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs.map((r) => r.bin)).toEqual(['/venv/ltx2/bin/python3', '/venv/ltx25/bin/python3']);
+ expect(report.status).toBe('ok');
+ });
+
+ it('never tries a second interpreter once one gave a verdict about the file', async () => {
+ state.responses = [{ ok: true, stdout: resultLine({ ...OK_PAYLOAD, status: 'unreadable', measured: 0, modules: 0 }) }];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs).toHaveLength(1);
+ expect(report.status).toBe('unreadable');
+ });
+
+ it('skips interpreters that are not installed', async () => {
+ state.existing = new Set(['/usr/bin/python3']);
+ state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
+ await probeLoraEffect('style.safetensors');
+ expect(state.runs.map((r) => r.bin)).toEqual(['/usr/bin/python3']);
+ });
+
+ it('reports unmeasurable — never throws — when no interpreter exists at all', async () => {
+ state.existing = new Set();
+ const report = await probeLoraEffect('style.safetensors');
+ expect(state.runs).toHaveLength(0);
+ expect(report.status).toBe('unmeasurable');
+ expect(report.reason).toMatch(/no Python interpreter/i);
+ });
+});
+
+describe('probeLoraEffect — never fatal, never a false verdict', () => {
+ it('reports unmeasurable when every interpreter fails, and caches nothing', async () => {
+ state.responses = [
+ { ok: false, reason: 'spawn failed: ENOENT', stdout: '' },
+ { ok: false, reason: 'spawn failed: ENOENT', stdout: '' },
+ { ok: false, reason: 'spawn failed: ENOENT', stdout: '' },
+ ];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(report.status).toBe('unmeasurable');
+ // An environment failure must not be frozen into the sidecar — the next
+ // attempt (after the venv is installed) has to be able to succeed.
+ expect(state.patched).toHaveLength(0);
+ });
+
+ it('reports unmeasurable on a timeout rather than surfacing a cancel', async () => {
+ state.responses = [{ ok: false, canceled: true, reason: 'cancelled (SIGTERM)', stdout: '' }];
+ 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);
+ });
+
+ it('reports unmeasurable for malformed probe output instead of a hollow verdict', async () => {
+ state.existing = new Set(['/venv/ltx2/bin/python3']);
+ state.responses = [{ ok: true, stdout: 'RESULT:{not json\n' }];
+ const report = await probeLoraEffect('style.safetensors');
+ expect(report.status).toBe('unmeasurable');
+ });
+
+ 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 () => {
+ state.statThrows = true;
+ await expect(probeLoraEffect('gone.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
+ state.statThrows = false;
+ state.statResult = { size: 0, isFile: () => false };
+ await expect(probeLoraEffect('dir.safetensors')).resolves.toMatchObject({ status: 'unmeasurable' });
+ expect(state.runs).toHaveLength(0);
+ });
+
+ it('still refuses an unsafe filename — path validation is not part of "never fatal"', async () => {
+ await expect(probeLoraEffect('../../etc/passwd')).rejects.toThrow(/safetensors/i);
+ });
+
+ it('reports unmeasurable when the spawn itself throws instead of rejecting into a render', async () => {
+ // runSidecarProcess models its failures as resolutions, but the underlying
+ // spawn can still throw synchronously — and a render awaits this.
+ const { runSidecarProcess } = await import('../lib/sidecarProcess.js');
+ vi.mocked(runSidecarProcess).mockRejectedValueOnce(new Error('ERR_INVALID_ARG_VALUE'));
+ state.responses = [{ ok: true, stdout: resultLine(OK_PAYLOAD) }];
+ state.existing = new Set(['/venv/ltx2/bin/python3']);
+ const report = await probeLoraEffect('style.safetensors');
+ expect(report.status).toBe('unmeasurable');
+ expect(report.reason).toMatch(/could not be started/i);
+ });
+
+ 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([
+ probeLoraEffect('style.safetensors', { force: true }),
+ probeLoraEffect('style.safetensors', { force: true }),
+ ]);
+ expect(state.runs).toHaveLength(1);
+ expect(a).toEqual(b);
+ });
+});
diff --git a/server/services/loras.js b/server/services/loras.js
index c74c538513..c32abac92b 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -28,6 +28,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { atomicWrite, assertSafeFilename, ensureDir, listDirectoryByExtension, sha256File, PATHS } from '../lib/fileUtils.js';
import { verifySafetensorsStructure } from '../lib/hfCache.js';
import { isPlainObject } from '../lib/objects.js';
+import { readCachedLoraEffectReport } from '../lib/loraEffect.js';
import {
applyDownloadToken,
baseModelToRunner,
@@ -223,6 +224,13 @@ export const listLoras = async () => {
source: sidecar?.source || null,
character: sidecar?.character || null,
trainedFromDatasetId: sidecar?.datasetId || null,
+ // Adapter-effect diagnostic (#4872). CACHED ONLY — listing the library
+ // must never fan out into one Python child per installed LoRA, so this
+ // surfaces whatever the explicit probe last measured and drops it when
+ // 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),
};
},
});
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index 96615b9ac0..38ff63f820 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -202,6 +202,58 @@ describe('listLoras', () => {
});
});
+// Adapter-effect diagnostic (#4872). listLoras is a PASSIVE read — a library
+// page with 40 installed LoRAs must never fan out into 40 Python children — so
+// 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 fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, filename), Buffer.alloc(bytes, 1));
+ 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) });
+ 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' });
+ const [lora] = await lorasService.listLoras();
+ expect(lora.effectReport).toBeNull();
+ });
+
+ 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) });
+ 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 } });
+ 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 },
+ });
+ const [lora] = await lorasService.listLoras();
+ expect(lora.effectReport).toMatchObject({ status: 'unmeasurable', medianRms: null, maxRms: null });
+ });
+});
+
describe('deleteLora', () => {
it('removes file + sidecar', async () => {
const fs = await import('fs/promises');
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 7fe1db63d5..306d95c7b2 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -269,7 +269,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// missing/typo'd LoRA fails with a clean 400 before any GPU work. buildArgs
// rejects LoRAs on non-ltx2 runtimes (the route also guards), so this is a
// no-op there.
- const resolvedLoras = await resolveVideoLoras(loras);
+ const resolvedLoras = await resolveVideoLoras(loras, { probeEffect: true });
// `model` was decorated from a SYNC cache read, which is false on a cold
// cache. Resolve the probe and re-decorate from the settled verdict before
// buildArgs reads it off the snapshot — otherwise the first LoRA render after
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 7fc4a50f28..029c189a6f 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -307,6 +307,17 @@ vi.mock('../loras.js', () => ({
)),
}));
+// Adapter-effect gate (#4872). generateVideo opts every render into the probe,
+// so it has to be stubbed here — the shared child_process mock resolves every
+// spawn successfully, which would report a fabricated measurement. Default
+// verdict is 'unmeasurable' (the permissive one: no interpreter on the box),
+// so every pre-existing LoRA render test reaches the spawn path unchanged; the
+// 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', () => ({
+ probeLoraEffect: vi.fn(async (filename) => loraEffectState.reportByFilename[filename] || loraEffectState.defaultReport),
+}));
+
vi.mock('fs/promises', () => ({
unlink: vi.fn(async () => {}),
writeFile: vi.fn(async () => {}),
@@ -4305,6 +4316,85 @@ describe('resolveVideoLoras — safetensors key-layout gate', () => {
});
});
+describe('resolveVideoLoras — adapter-effect gate (#4872)', () => {
+ let resolveVideoLoras;
+ let probeLoraEffect;
+ beforeEach(async () => {
+ vi.resetModules();
+ loraLayoutState.layout = 'comfyui';
+ loraEffectState.reportByFilename = {};
+ loraEffectState.defaultReport = { status: 'unmeasurable', measured: 0, reason: 'no numpy' };
+ ({ resolveVideoLoras } = await import('./local.js'));
+ ({ probeLoraEffect } = await import('../loraEffectProbe.js'));
+ vi.mocked(probeLoraEffect).mockClear();
+ });
+ afterEach(() => {
+ loraLayoutState.layout = null;
+ loraEffectState.reportByFilename = {};
+ });
+
+ it('does NOT probe unless the caller opts in — a passive resolve stays free', async () => {
+ await resolveVideoLoras([{ filename: 'style.safetensors' }]);
+ expect(probeLoraEffect).not.toHaveBeenCalled();
+ });
+
+ it('probes every selected LoRA once the caller opts in', async () => {
+ await resolveVideoLoras(
+ [{ filename: 'a.safetensors' }, { filename: 'b.safetensors' }],
+ { probeEffect: true },
+ );
+ expect(vi.mocked(probeLoraEffect).mock.calls.map(([f]) => f)).toEqual(['a.safetensors', 'b.safetensors']);
+ });
+
+ it('refuses a measured entirely-zero adapter with an actionable 400', async () => {
+ loraEffectState.reportByFilename['dead.safetensors'] = {
+ status: 'zero', measured: 6, zeroModules: 6,
+ reason: 'all 6 measurable LoRA module(s) have exactly zero effect — fusing it would change nothing',
+ };
+ await expect(resolveVideoLoras([{ filename: 'dead.safetensors' }], { probeEffect: true }))
+ .rejects.toMatchObject({ status: 400, code: 'LORA_EFFECT_ZERO' });
+ await expect(resolveVideoLoras([{ filename: 'dead.safetensors' }], { probeEffect: true }))
+ .rejects.toThrow(/dead\.safetensors.*zero effect/s);
+ });
+
+ it('refuses the whole render when ANY selected LoRA measures zero', async () => {
+ loraEffectState.reportByFilename = {
+ 'ok.safetensors': { status: 'ok', measured: 4, medianRms: 0.01, maxRms: 0.02 },
+ 'dead.safetensors': { status: 'zero', measured: 4, zeroModules: 4, reason: 'zero effect' },
+ };
+ await expect(resolveVideoLoras(
+ [{ filename: 'ok.safetensors' }, { filename: 'dead.safetensors' }],
+ { probeEffect: true },
+ )).rejects.toMatchObject({ code: 'LORA_EFFECT_ZERO' });
+ });
+
+ it('lets every other verdict through — the probe is a diagnostic, not a second gate', async () => {
+ // A machine with no numpy, an adapter the probe cannot parse, and one whose
+ // modules all diverged must all render exactly as they did before this
+ // existed. Refusing on anything we did not positively measure would turn a
+ // missing dependency into an un-renderable install.
+ for (const report of [
+ { status: 'unmeasurable', measured: 0, reason: 'numpy is not installed' },
+ { status: 'unreadable', measured: 0, reason: 'no lora_A/lora_B pairs' },
+ { status: 'nonfinite', measured: 0, skippedNonFinite: 8, reason: 'every module measured NaN' },
+ { status: 'ok', measured: 8, medianRms: 1e-9, maxRms: 1e-8 },
+ null,
+ ]) {
+ loraEffectState.defaultReport = report;
+ const resolved = await resolveVideoLoras([{ filename: 'x.safetensors', scale: 0.6 }], { probeEffect: true });
+ expect(resolved).toEqual([
+ { path: join(MOCK_PATHS.loras, 'x.safetensors'), strength: 0.6, filename: 'x.safetensors' },
+ ]);
+ }
+ });
+
+ it('never probes a LoRA the key-layout gate already refused', async () => {
+ loraLayoutState.layout = 'kohya';
+ await expect(resolveVideoLoras([{ filename: 'style.safetensors' }], { probeEffect: true })).rejects.toThrow();
+ expect(probeLoraEffect).not.toHaveBeenCalled();
+ });
+});
+
describe('generateVideo — MiniMax H3 CUDA contract', () => {
// Same license gate as the MLX entry: it is the same weights under the same
// terms, so acceptance is recorded once and honored by both runtimes.
diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.js
index 4007cd2ca7..24fc964b2e 100644
--- a/server/services/videoGen/renderArgs.js
+++ b/server/services/videoGen/renderArgs.js
@@ -15,7 +15,9 @@ import {
} from '../../lib/videoReferenceModes.js';
import { extendLatentFrames } from '../../lib/videoContinuity.js';
import { videoLoraLayoutIssue } from '../../lib/safetensors.js';
+import { formatLoraEffect, loraEffectIssue } from '../../lib/loraEffect.js';
import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
+import { LORA_EFFECT_PROBE_BUDGET_MS, probeLoraEffect } from '../loraEffectProbe.js';
import { videoLoraFamily, isLtx2FamilyRuntime } from '../../lib/runners.js';
import {
isIcLoraMode, icLoraSpecForMode, assertIcReferenceCount, icResolutionIssue,
@@ -161,9 +163,13 @@ export const resolveT2vTwoStageOverride = ({
// lora_up) or diffusers/PEFT-prefixed file matches nothing: the render burns
// minutes of GPU time and comes back as an un-LoRA'd (or noisy) clip with no
// error anywhere. Refuse it up front with the layout named.
-export const resolveVideoLoras = async (loras) => {
+export const resolveVideoLoras = async (loras, { probeEffect = false } = {}) => {
if (!Array.isArray(loras) || loras.length === 0) return [];
const out = [];
+ // ONE budget for every selected adapter, not one each. This runs before
+ // generateVideo mints a job id, so anything spent here is silence in the UI —
+ // a 4-LoRA render must not be able to stall for four full probe budgets.
+ const effectDeadline = probeEffect ? Date.now() + LORA_EFFECT_PROBE_BUDGET_MS : null;
for (const l of loras) {
assertSafeLoraFilename(l?.filename);
const path = join(PATHS.loras, l.filename);
@@ -181,6 +187,29 @@ export const resolveVideoLoras = async (loras) => {
if (layout == null) {
console.log(`⚠️ LoRA key layout undetermined for ${l.filename} — fusing anyway`);
}
+ // Adapter-effect gate (#4872). Opt-in — a passive library read must never
+ // spawn a probe — and the render path opts in, because this is the last
+ // moment before GPU minutes are spent on weights that may be inert. The
+ // measurement is cached in the sidecar, so this costs a Python child once
+ // per LoRA file and nothing thereafter.
+ //
+ // Only a POSITIVE measurement of entirely-zero effect refuses. A probe that
+ // could not run (no numpy anywhere), an unreadable adapter, or one whose
+ // modules all measured NaN, all render exactly as they did before this
+ // gate existed — see loraEffectIssue().
+ if (probeEffect) {
+ const report = await probeLoraEffect(l.filename, { deadline: effectDeadline });
+ const effectIssue = loraEffectIssue(report);
+ if (effectIssue) {
+ throw new ServerError(
+ `LoRA "${l.filename}" can't be used for video: ${effectIssue}.`,
+ { status: 400, code: 'LORA_EFFECT_ZERO' },
+ );
+ }
+ if (report?.measured > 0) {
+ console.log(`🔬 LoRA effect ${l.filename}: ${formatLoraEffect(report)}`);
+ }
+ }
const strength = Number.isFinite(l?.scale) ? l.scale : 1.0;
out.push({ path, strength, filename: l.filename });
}