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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: implement the LTX-2.5 generative upscale runner on the macOS MLX backend (#6512)
[._.]/ Adam Eivy88266587e27b
diff --git a/client/src/components/media/VideoUpscaleDrawer.jsx b/client/src/components/media/VideoUpscaleDrawer.jsxindex 2e5aa38d0e..c9418fd4fb 100644--- a/client/src/components/media/VideoUpscaleDrawer.jsx+++ b/client/src/components/media/VideoUpscaleDrawer.jsx@@ -61,7 +61,13 @@ export default function VideoUpscaleDrawer({ item, onClose, onUpscaled }) {const runtimeReady = plan?.runtime?.installed === true;const adapterReady = plan?.adapter?.cached === true;- const generativeReady = runtimeReady && adapterReady;+ // The base checkpoint is a third readiness axis (#6512): the venv and the+ // 327 MB adapter can both be present while the ~68 GB LTX-2.5 pack is not,+ // and the runner is handed a resolved snapshot path rather than resolving+ // (and silently downloading) one itself. Without this the button would read+ // ready for a job the dispatch refuses.+ const baseModelReady = plan?.baseModel?.cached === true;+ const generativeReady = runtimeReady && adapterReady && baseModelReady;const adapterMissing = !!plan && runtimeReady && !adapterReady;const generativeDisabledReason = !plan? null@@ -69,7 +75,9 @@ export default function VideoUpscaleDrawer({ item, onClose, onUpscaled }) {? plan.runtime.reason: !adapterReady? `The ${plan.adapter?.label || 'generative upscale'} adapter is not downloaded yet.`- : null;+ : !baseModelReady+ ? plan.baseModel?.reason || 'The LTX-2.5 model pack for this backend is not downloaded yet.'+ : null;// Inline adapter download (#6510 item 4) — the same provisioning surface// every IC-LoRA weight rides (#3100), just triggered from here instead of adiff --git a/client/src/components/media/VideoUpscaleDrawer.test.jsx b/client/src/components/media/VideoUpscaleDrawer.test.jsxindex 9cf271a9c4..17f1c01b7c 100644--- a/client/src/components/media/VideoUpscaleDrawer.test.jsx+++ b/client/src/components/media/VideoUpscaleDrawer.test.jsx@@ -36,6 +36,10 @@ const READY_PLAN = {key: 'pixel-upscale', label: 'Pixel Spatial Upscaler', repo: 'Lightricks/example', filename: 'weight.safetensors',sizeBytes: 327_322_640, gated: true, cached: true,},+ baseModel: {+ id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8', repo: 'Example/ltx25-mlx-q8', revision: 'abc1234',+ path: '/cache/ltx25-mlx-q8', cached: true, reason: null,+ },};const missingAdapterPlan = () => ({@@ -43,6 +47,16 @@ const missingAdapterPlan = () => ({adapter: { ...READY_PLAN.adapter, cached: false },});+const missingBaseModelPlan = () => ({+ ...READY_PLAN,+ baseModel: {+ ...READY_PLAN.baseModel,+ path: null,+ cached: false,+ reason: 'LTX-2.5 MLX Q8 is not downloaded — download or repair it in Video Gen.',+ },+});+const unsupportedRuntimePlan = () => ({...READY_PLAN,runtime: { id: null, label: null, supported: false, installed: false, reason: 'No generative upscale backend exists for this platform.' },@@ -125,4 +139,16 @@ describe('VideoUpscaleDrawer', () => {expect(getUpscalePlan).not.toHaveBeenCalled();expect(screen.queryByRole('dialog')).toBeFalsy();});++ // #6512: the base pack is a third, independent download. Before this the+ // drawer read ready off runtime + adapter alone and offered a button for a+ // job the dispatch refuses with UPSCALE_BASE_MODEL_UNRESOLVED.+ it('disables the generative method when the base model pack is missing', async () => {+ getUpscalePlan.mockResolvedValue({ plan: missingBaseModelPlan() });+ render(<VideoUpscaleDrawer item={ITEM} onClose={vi.fn()} onUpscaled={vi.fn()} />);+ await waitFor(() => expect(getUpscalePlan).toHaveBeenCalled());++ expect(screen.getByLabelText(/LTX-2\.5 generative/i).disabled).toBe(true);+ expect(screen.getByText(/is not downloaded/i)).toBeTruthy();+ });});diff --git a/scripts/upscale_ltx25.py b/scripts/upscale_ltx25.pynew file mode 100755index 0000000000..e960bc56cf--- /dev/null+++ b/scripts/upscale_ltx25.py@@ -0,0 +1,427 @@+#!/usr/bin/env python3+"""Generative 2x video upscale on the LTX-2.5 MLX runtime (#6512).++The pass fuses the gated LTX-2.5 Pixel Spatial Upscaler IC-LoRA into the+distilled transformer and conditions on the clip being upscaled, so it is an+IC-LoRA render whose single reference IS the source. That is why the argv is+the IC flag alphabet `renderArgs.buildLtxUpscaleArgs()` already emits rather+than a second vocabulary, and why the reference-count bounds arrive as flags:+`server/lib/icLoraWeights.js` is the single source of truth across both+languages, and a Python-side default would be a second table free to drift.++Everything this runner needs was READ off the pinned runtime+(`~/.portos/ltx-2.5-mlx`, `LTX25_EXPECTED_REVISION`), not inferred from the+gated model card:++ - The 2.5 fork ships its OWN `ltx_pipelines_mlx.ic_lora.ICLoraPipeline`, so+ there is nothing to compose with `generate_ltx2.py`'s 2.3 encoder-shim /+ unified-weight-filter machinery. This runner talks to the 2.5 pipeline+ directly and imports none of it.+ - The correct text encoder is the gemma4 conditioner the 2.5 pack ships under+ `<model_dir>/text_encoder/`. `PromptEncoder._text_encoder_source()` prefers+ it and otherwise falls back to the remote 2.3 Gemma 3 id — a wrong encoder+ AND an unannounced multi-GB download — so `validate_model_dir` refuses a+ pack that lacks it instead of letting that fallback happen.+ - The schedule is the fixed distilled one: `DISTILLED_SIGMAS` is 8 steps and+ `STAGE_2_SIGMAS` is 3. Passing no step counts selects exactly those, which+ is why this runner exposes no steps flag.+ - Quantization-safe fusion is the runtime's own contract: `apply_loras()`+ dequantizes an int4/int8 weight, adds the delta, and re-quantizes. What it+ does NOT do is complain when an adapter addresses keys the transformer does+ not have — every delta is simply missing, the fusion is a silent no-op, and+ the render is the plain base model. `assert_adapter_fuses` is the guard for+ that: it is the "loads but produces garbage" case #6512 names.+ - `reference_downscale_factor` is read from the adapter's safetensors+ `__metadata__` (`iclora_utils.read_lora_reference_downscale_factor`) and+ enforced against the STAGE-1 dims, which are half the output. It is+ reported on stderr so the value is recorded rather than guessed.++Phosphene's fast source-latent refinement is deliberately NOT ported — #6502+rules it fork-specific, and the current pins take no such arguments.+"""++from __future__ import annotations++import argparse+import json+import platform+import struct+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import emit_runtime_fingerprint, heartbeat # noqa: E402++# The 2.5 pack's own prompt conditioner. Its absence is a hard refusal rather+# than a fallback — see the module docstring.+TEXT_ENCODER_DIRNAME = "text_encoder"++# The LTX-2.5 two-stage grid, mirrored from `LTX_GRID` in+# `server/services/videoGen/upscalePlan.js` and confirmed against the runtime:+# Stage 1 renders at `height // 2` / `width // 2` and the video VAE's spatial+# compression is 32 (`compute_video_latent_shape`), so the OUTPUT axis must be+# divisible by 64. The temporal compression is 8 and the reference encoder+# needs a (1 + 8k)-frame input, so `frames % 8 == 1` with a floor of 9.+SPATIAL_MULTIPLE = 64+FRAME_MODULUS = 8+FRAME_REMAINDER = 1+MIN_FRAMES = 9++# Stage 1 renders at half the requested output, and it is those halved dims the+# IC encoder divides by `reference_downscale_factor`.+STAGE1_DIVISOR = 2++# The upscale contract carries no prompt (#6511): the source clip is the whole+# conditioning signal, and inventing text steering would push synthesized+# detail toward content the user never asked for. The empty string is the+# neutral choice — the distilled schedule runs no CFG, so the prompt is pure+# conditioning rather than a guidance pole. `--prompt` exists so #6514's+# verification matrix can probe the effect without changing the argv contract.+DEFAULT_PROMPT = ""++# Full reference conditioning: unlike a control/pose IC render, the reference+# here is the picture itself, so there is nothing to attenuate.+REFERENCE_STRENGTH = 1.0++FINGERPRINT_PACKAGES = ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"]++# A real safetensors header is a few KB to low-MB; anything past this is a+# corrupt length we refuse to allocate for. Mirrors the same bound in+# `server/lib/safetensors.js`.+MAX_HEADER_BYTES = 100 * 1024 * 1024+++def log(message: str) -> None:+ print(message, file=sys.stderr, flush=True)+++def parse_args(argv: "list[str] | None" = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="LTX-2.5 MLX generative video upscale")+ parser.add_argument("--model", required=True,+ help="local snapshot directory of the pinned LTX-2.5 MLX pack "+ "(resolved cache-only by PortOS; never a repo id)")+ parser.add_argument("--ic-lora-path", required=True,+ help="local .safetensors of the Pixel Spatial Upscaler adapter")+ parser.add_argument("--ic-reference", action="append", default=[],+ help="the clip being upscaled, already aligned to the model grid")+ parser.add_argument("--ic-min-references", type=int, required=True)+ parser.add_argument("--ic-max-references", type=int, required=True)+ parser.add_argument("--width", type=int, required=True)+ parser.add_argument("--height", type=int, required=True)+ parser.add_argument("--num-frames", type=int, required=True)+ parser.add_argument("--fps", type=float, required=True)+ parser.add_argument("--seed", type=int, required=True)+ parser.add_argument("--prompt", default=DEFAULT_PROMPT)+ parser.add_argument("--output", required=True)+ return parser.parse_args(argv)+++def read_safetensors_header(path: str) -> "dict | None":+ """Parse a safetensors JSON header with the stdlib alone.++ Deliberately not `safetensors.safe_open`: this runs during validation, in a+ bare interpreter, before any runtime import — which is what keeps the whole+ argument contract testable without an MLX wheel. Returns None for a missing,+ truncated, or non-safetensors file rather than raising, so the caller states+ the refusal in its own words.+ """+ try:+ with open(path, "rb") as handle:+ raw_len = handle.read(8)+ if len(raw_len) < 8:+ return None+ header_len = struct.unpack("<Q", raw_len)[0]+ if header_len <= 0 or header_len > MAX_HEADER_BYTES:+ return None+ raw = handle.read(header_len)+ if len(raw) < header_len:+ return None+ parsed = json.loads(raw.decode("utf-8"))+ return parsed if isinstance(parsed, dict) else None+ except (OSError, ValueError, struct.error):+ return None+++def reference_downscale_factor(header: "dict | None") -> int:+ """The adapter's declared `reference_downscale_factor`, defaulting to 1.++ Matches `iclora_utils.read_lora_reference_downscale_factor`, which the+ pipeline uses as the real value. Read here too so the resolution rule can be+ stated BEFORE a multi-minute render commits to it — and so PortOS can record+ the measured factor rather than the `null` its registry honestly holds for a+ gated weight nobody has opened yet.+ """+ metadata = (header or {}).get("__metadata__")+ if not isinstance(metadata, dict):+ return 1+ try:+ scale = int(metadata.get("reference_downscale_factor", 1))+ except (TypeError, ValueError):+ return 1+ return scale if scale >= 1 else 1+++def lora_target_keys(names) -> "set[str]":+ """Base-weight keys an adapter can fuse into, from its ALREADY-RENAMED names.++ `apply_loras` pairs `<prefix>.lora_A.weight` with `<prefix>.lora_B.weight`+ and skips a prefix missing either half, so a half-pair contributes nothing+ and must not count as coverage. Takes renamed names rather than raw ones on+ purpose: the ComfyUI rename table belongs to the runtime+ (`LTXV_LORA_COMFY_RENAMING_MAP`), and copying it here would be a second+ table free to drift from the one that actually fuses.+ """+ prefixes = {"lora_A": set(), "lora_B": set()}+ for name in names:+ for half, bucket in prefixes.items():+ suffix = f".{half}.weight"+ if isinstance(name, str) and name.endswith(suffix):+ bucket.add(name[: -len(suffix)])+ return {f"{prefix}.weight" for prefix in prefixes["lora_A"] & prefixes["lora_B"]}+++def validate_host(system: str, machine: str) -> None:+ """Capability gate: this runner is Apple-Silicon-only.++ MLX has no non-Metal backend, so an Intel Mac or a Linux box reaching here+ is a routing bug in `ltxUpscaleRuntimeId()`. Named explicitly so the queue+ shows the actionable reason rather than an import traceback.+ """+ if system != "Darwin" or machine != "arm64":+ raise SystemExit(+ f"The LTX-2.5 MLX upscale runner needs Apple Silicon; this host reports {system}/{machine}. "+ "Use the CUDA backend on an NVIDIA machine instead."+ )+++def validate_args(args: argparse.Namespace) -> None:+ """Everything checkable before a GPU is committed.++ Mirrors `validate_args` in `scripts/generate_ltx25_cuda.py` on the grid so+ both backends refuse the same sources, and mirrors `run_ic_lora` on the+ reference contract so a direct/script caller gets the same guard the queue+ does. Every refusal is a `SystemExit` string the queue surfaces verbatim.+ """+ if args.width % SPATIAL_MULTIPLE or args.height % SPATIAL_MULTIPLE:+ raise SystemExit(+ f"The two-stage LTX-2.5 pipeline requires width and height divisible by {SPATIAL_MULTIPLE}; "+ f"got {args.width}x{args.height}."+ )+ if args.num_frames < MIN_FRAMES or args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:+ raise SystemExit(+ f"LTX-2.5 num-frames must be at least {MIN_FRAMES} and satisfy "+ f"frames % {FRAME_MODULUS} == {FRAME_REMAINDER}; got {args.num_frames}."+ )+ if not args.fps > 0:+ raise SystemExit(f"--fps must be positive; got {args.fps}.")+ if args.seed < 0:+ raise SystemExit(f"--seed must be non-negative; got {args.seed}.")++ lo, hi = args.ic_min_references, args.ic_max_references+ if lo < 1 or hi < lo:+ raise SystemExit(+ f"--ic-min-references/--ic-max-references must satisfy 1 <= min <= max; got {lo}/{hi}"+ )+ references = list(args.ic_reference or [])+ if not (lo <= len(references) <= hi):+ expected = f"exactly {lo}" if lo == hi else f"{lo}-{hi}"+ raise SystemExit(+ f"The upscale adapter needs {expected} --ic-reference clip(s); got {len(references)}"+ )+ for reference in references:+ if not Path(reference).is_file():+ raise SystemExit(f"--ic-reference does not exist: {reference}")++ # A path, never a repo id. `ICLoraPipeline._resolve_lora_path` falls back to+ # `snapshot_download` for anything that is not an existing file, which for+ # this gated adapter is a 401 deep inside a render — and for any repo, a pull+ # PortOS never announced. The download surface owns every fetch.+ if not Path(args.ic_lora_path).is_file():+ raise SystemExit(+ f"The Pixel Spatial Upscaler adapter is not on disk at {args.ic_lora_path} — "+ "download it from the Video Gen model panel before upscaling."+ )+++def validate_model_dir(model_dir: str) -> Path:+ """Resolve the pinned LTX-2.5 pack, refusing a pack without its conditioner.++ PortOS resolves the snapshot cache-only and hands over a directory, so a+ missing one means the pack was never downloaded (or was deleted underneath a+ queued job). The `text_encoder/` check is the load-bearing half: without it+ `PromptEncoder` silently falls back to the remote LTX-2.3 Gemma 3 id, which+ is both the wrong conditioner for these weights and an unannounced download.+ """+ root = Path(model_dir)+ if not root.is_dir():+ raise SystemExit(+ f"The LTX-2.5 MLX model pack is not cached at {model_dir} — "+ "download or repair it in Video Gen before upscaling."+ )+ if not (root / TEXT_ENCODER_DIRNAME / "config.json").is_file():+ raise SystemExit(+ f"The LTX-2.5 pack at {model_dir} is missing {TEXT_ENCODER_DIRNAME}/config.json, so the "+ "pipeline would fall back to the LTX-2.3 Gemma 3 conditioner and fetch it at render time. "+ "Repair the model in Video Gen."+ )+ return root+++def assert_reference_scale_fits(scale: int, width: int, height: int) -> None:+ """Enforce the adapter's own resolution rule on the STAGE-1 dimensions.++ `append_ic_lora_reference_video_conditionings` divides the dims it is HANDED+ by the factor, and `ICLoraPipeline.generate` hands it `height // 2` /+ `width // 2`. Stating the rule in OUTPUT terms is what makes the message+ actionable — the user picked an output size, not a stage size.+ """+ if scale <= 1:+ return+ stage_h, stage_w = height // STAGE1_DIVISOR, width // STAGE1_DIVISOR+ if stage_h % scale == 0 and stage_w % scale == 0:+ return+ required = scale * STAGE1_DIVISOR+ raise SystemExit(+ f"This adapter downscales its reference by {scale}, so the output dimensions must be "+ f"divisible by {required}; got {width}x{height}."+ )+++def resolve_transformer_path(model_dir: Path) -> "Path | None":+ """The DiT weight file `ICLoraPipeline.load()` would pick, or None.++ Mirrors that method exactly: the plain `transformer.safetensors` wins, else+ `BasePipeline._resolve_safetensors(model_dir, "transformer-distilled")`+ takes the lexicographically last versioned file and falls back to the+ unversioned name.+ """+ plain = model_dir / "transformer.safetensors"+ if plain.is_file():+ return plain+ versioned = sorted(model_dir.glob("transformer-distilled-*.safetensors"))+ if versioned:+ return versioned[-1]+ fallback = model_dir / "transformer-distilled.safetensors"+ return fallback if fallback.is_file() else None+++def transformer_weight_keys(transformer_path: Path) -> "set[str]":+ """The transformer's fusable parameter names, read from its header alone.++ `load_transformer` loads the file through+ `load_split_safetensors(path, prefix="transformer.")`, which keeps only the+ prefixed keys and strips the prefix — so the model's parameter names are a+ deterministic function of the file's header, with no tensor I/O and no+ model in memory. Only `.weight` keys matter: `_prepare_deltas` addresses a+ weight by `<prefix>.weight`, and a quantized pack's sibling+ `.scales`/`.biases` are carried along with it rather than fused into.+ """+ header = read_safetensors_header(str(transformer_path))+ if not header:+ return set()+ prefix = "transformer."+ return {+ name[len(prefix):]+ for name in header+ if name != "__metadata__" and name.startswith(prefix) and name.endswith(".weight")+ }+++def assert_adapter_fuses(adapter_path: str, model_keys, rename) -> int:+ """Refuse an adapter whose tensors address none of the transformer's weights.++ This is the failure #6512 calls out: `apply_loras` reports nothing when a+ key does not match — every delta is simply absent, the fusion is a silent+ no-op, and the render is the un-adapted base model dressed as an upscale.+ Only headers are read, so the check costs no tensor I/O and runs BEFORE the+ pipeline loads anything.++ Returns the number of weights the adapter will actually fuse into, so the+ render records real coverage instead of "it loaded".+ """+ header = read_safetensors_header(adapter_path)+ if not header:+ raise SystemExit(+ f"Could not read the adapter's safetensors header at {adapter_path} — "+ "the file is truncated or is not a safetensors weight. Repair it in Video Gen."+ )+ if not model_keys:+ raise SystemExit(+ "Could not read the LTX-2.5 transformer's weight names, so there is no way to tell whether "+ "the upscale adapter would fuse into anything. Repair the model in Video Gen."+ )+ renamed = [rename(name) for name in header if name != "__metadata__"]+ matched = lora_target_keys(name for name in renamed if name) & set(model_keys)+ if not matched:+ raise SystemExit(+ "The upscale adapter's tensors do not address any weight in this transformer, so fusing it "+ "would be a no-op and the 'upscale' would be an un-adapted render. The adapter and the "+ "LTX-2.5 pack are mismatched — repair both in Video Gen."+ )+ return len(matched)+++def main() -> None:+ args = parse_args()+ validate_host(platform.system(), platform.machine())+ validate_args(args)+ model_dir = validate_model_dir(args.model)++ header = read_safetensors_header(args.ic_lora_path)+ scale = reference_downscale_factor(header)+ assert_reference_scale_fits(scale, args.width, args.height)+ # Recorded rather than guessed: `icLoraWeights.js` holds `null` for this+ # gated weight precisely because nobody had opened it, and this line is the+ # measurement (#6508's registry note points here).+ log(f"UPSCALE_REFERENCE_DOWNSCALE:{scale}")++ log("STAGE:verify-adapter")+ from ltx_core_mlx.loader import LTXV_LORA_COMFY_RENAMING_MAP+ from ltx_pipelines_mlx.ic_lora import ICLoraPipeline++ emit_runtime_fingerprint("ltx25", FINGERPRINT_PACKAGES)++ # Both sides of the coverage check are header reads, so a mismatched pair+ # fails in milliseconds — before Gemma, before the DiT, before a GPU. Do NOT+ # move this behind a `pipe.load()`: `generate()` deliberately loads the text+ # encoder, encodes, frees it, and only THEN loads the transformer, so+ # pre-loading would hold a multi-GB DiT resident through prompt encoding.+ transformer_path = resolve_transformer_path(model_dir)+ if transformer_path is None:+ raise SystemExit(+ f"The LTX-2.5 pack at {model_dir} has no transformer weight file. Repair the model in Video Gen."+ )+ fused = assert_adapter_fuses(+ args.ic_lora_path,+ transformer_weight_keys(transformer_path),+ LTXV_LORA_COMFY_RENAMING_MAP.apply_to_key,+ )+ log(f"STATUS:Adapter fuses into {fused} transformer weights")++ log("STAGE:load-pipeline")+ log(f"STATUS:Loading LTX-2.5 MLX upscale pipeline ({args.width}x{args.height}, {args.num_frames} frames)")+ pipe = ICLoraPipeline(model_dir=str(model_dir), lora_paths=[(args.ic_lora_path, 1.0)])++ output = Path(args.output)+ output.parent.mkdir(parents=True, exist_ok=True)+ log("STAGE:inference")+ with heartbeat("ltx25-upscale-inference"):+ # No stage step counts: `DISTILLED_SIGMAS` / `STAGE_2_SIGMAS` ARE the+ # distilled schedule (8 + 3), and passing a count would truncate them.+ pipe.generate_and_save(+ prompt=args.prompt,+ output_path=str(output),+ video_conditioning=[(reference, REFERENCE_STRENGTH) for reference in args.ic_reference],+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ frame_rate=args.fps,+ seed=args.seed,+ )+ if not output.is_file():+ raise SystemExit(f"The LTX-2.5 upscale completed but did not write {output}.")+ log(f"STATUS:Upscaled {output.name} ({args.width}x{args.height}, {args.num_frames} frames)")+++if __name__ == "__main__":+ main()diff --git a/scripts/upscale_ltx25.test.js b/scripts/upscale_ltx25.test.jsnew file mode 100644index 0000000000..618d706e69--- /dev/null+++ b/scripts/upscale_ltx25.test.js@@ -0,0 +1,288 @@+import { execFileSync } from 'node:child_process';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const script = join(dirname(fileURLToPath(import.meta.url)), 'upscale_ltx25.py');++// Probe for an interpreter that actually RUNS rather than assuming a name — on+// Windows a bare `python` can be a Store alias STUB that exists and exits+// non-zero. Null when there is genuinely none, so the suite skips. Everything+// exercised here is import-free by design (stdlib only): the whole point of+// #6512's contract is that the argument and capability gates are testable on a+// machine with no MLX wheel, no 68 GB model pack, and no gated adapter.+const pyBin = resolveTestPython();+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], { encoding: 'utf8' });++const importRunner = [+ 'import importlib.util, sys',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1])',+ 'spec = importlib.util.spec_from_file_location("upscale_ltx25", script)',+ 'runner = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(runner)',+].join('\n');++// Python on Windows writes CRLF, so a trailing carriage return would otherwise+// ride along on every comparison below.+const trimmed = (output) => output.trim().split('\n').map((line) => line.trimEnd()).join('\n');++// A scratch tree the fixtures live in — never a path from the developer's+// install, and never inside the repo.+const scratch = mkdtempSync(join(tmpdir(), 'portos-upscale-runner-'));+const REFERENCE = join(scratch, 'source.mp4');+const ADAPTER = join(scratch, 'adapter.safetensors');+writeFileSync(REFERENCE, 'not really a video');++// A real safetensors file: 8-byte little-endian header length, then the JSON+// header. Written rather than mocked because the header parse IS the thing+// under test — the runner reads `reference_downscale_factor` off this exact+// layout, which is how the gated weight's factor gets MEASURED instead of+// guessed (the registry entry deliberately holds null).+const writeSafetensors = (path, header) => {+ const json = Buffer.from(JSON.stringify(header), 'utf8');+ const len = Buffer.alloc(8);+ len.writeBigUInt64LE(BigInt(json.length));+ writeFileSync(path, Buffer.concat([len, json]));+};+writeSafetensors(ADAPTER, { __metadata__: { reference_downscale_factor: '2' } });++// Drive validate_args through a real argparse Namespace so the test exercises+// the object main() builds, not a hand-rolled stand-in free to omit a field.+const ARG_DEFAULTS = {+ width: 1728,+ height: 1024,+ num_frames: 121,+ fps: 24,+ seed: 4242,+ ic_min_references: 1,+ ic_max_references: 1,+};+const validate = (overrides = {}) => {+ const fields = { ...ARG_DEFAULTS, ...overrides };+ const references = Object.hasOwn(overrides, 'ic_reference') ? overrides.ic_reference : [REFERENCE];+ const loraPath = Object.hasOwn(overrides, 'ic_lora_path') ? overrides.ic_lora_path : ADAPTER;+ return trimmed(runPython(`${importRunner}\n${[+ 'import argparse, json',+ `args = argparse.Namespace(**json.loads(${JSON.stringify(JSON.stringify(fields))}))`,+ `args.ic_reference = json.loads(${JSON.stringify(JSON.stringify(references))})`,+ `args.ic_lora_path = json.loads(${JSON.stringify(JSON.stringify(loraPath))})`,+ 'try:',+ ' runner.validate_args(args)',+ ' print("OK")',+ 'except SystemExit as exc:',+ ' print(f"REJECTED:{exc}")',+ ].join('\n')}`));+};++const call = (expression) => trimmed(runPython(`${importRunner}\n${[+ 'try:',+ ` print(${expression})`,+ 'except SystemExit as exc:',+ ' print(f"REJECTED:{exc}")',+].join('\n')}`));++describe.skipIf(!pyBin)('upscale_ltx25.py — argument contract (#6512)', () => {+ it('accepts the argv renderArgs.buildLtxUpscaleArgs emits', () => {+ expect(validate()).toBe('OK');+ });++ // The grid is `LTX_GRID` in upscalePlan.js, and it was read off the pinned+ // runtime rather than the gated card: Stage 1 renders at half the output and+ // the video VAE compresses spatially by 32, so the OUTPUT axis must divide by+ // 64. A source that "nearly" fits must be refused here, not silently resized.+ it.each([+ ['a width off the 64 grid', { width: 1700 }],+ ['a height off the 64 grid', { height: 1000 }],+ ])('refuses %s', (_label, overrides) => {+ expect(validate(overrides)).toMatch(/^REJECTED:.*divisible by 64/);+ });++ it.each([+ ['a frame count off the 8n+1 grid', { num_frames: 120 }],+ ['a frame count under the floor', { num_frames: 5 }],+ ])('refuses %s', (_label, overrides) => {+ expect(validate(overrides)).toMatch(/^REJECTED:.*frames % 8 == 1/);+ });++ it('refuses an unmeasured frame rate rather than defaulting one', () => {+ expect(validate({ fps: 0 })).toMatch(/^REJECTED:.*--fps must be positive/);+ });++ // The bounds are the weight registry's contract, carried across languages as+ // flags. A wrong reference count renders plausible-looking garbage rather+ // than erroring, so the helper enforces them even for a direct caller.+ it('refuses a reference count outside the weight registry bounds', () => {+ expect(validate({ ic_reference: [] })).toMatch(/^REJECTED:.*exactly 1 --ic-reference/);+ expect(validate({ ic_reference: [REFERENCE, REFERENCE] })).toMatch(/^REJECTED:.*exactly 1 --ic-reference/);+ });++ it('refuses inverted or sub-1 bounds instead of silently clamping them', () => {+ expect(validate({ ic_min_references: 2 })).toMatch(/^REJECTED:.*1 <= min <= max/);+ expect(validate({ ic_min_references: 0, ic_max_references: 0 })).toMatch(/^REJECTED:.*1 <= min <= max/);+ });++ it('refuses a reference clip that is not on disk', () => {+ expect(validate({ ic_reference: [join(scratch, 'missing.mp4')] })).toMatch(/^REJECTED:.*does not exist/);+ });++ // The pipeline's own `_resolve_lora_path` turns anything it cannot stat into a+ // `snapshot_download` — for this gated adapter a 401 deep inside a render, and+ // for any repo a pull PortOS never announced. The download surface owns fetching.+ it('refuses a repo id in place of a downloaded adapter file', () => {+ expect(validate({ ic_lora_path: 'Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler' }))+ .toMatch(/^REJECTED:.*download it from the Video Gen model panel/);+ });+});++describe.skipIf(!pyBin)('upscale_ltx25.py — capability gate (#6512)', () => {+ // MLX has no non-Metal backend, so reaching this runner off Apple Silicon is a+ // routing bug. It must name the reason the queue can show, not die on an+ // import traceback minutes later.+ it.each([+ ['an Intel Mac', 'Darwin', 'x86_64'],+ ['a Linux host', 'Linux', 'x86_64'],+ ['Windows', 'Windows', 'AMD64'],+ ])('refuses %s with an actionable message', (_label, system, machine) => {+ expect(call(`runner.validate_host(${JSON.stringify(system)}, ${JSON.stringify(machine)}) or "OK"`))+ .toMatch(/^REJECTED:.*Apple Silicon/);+ });++ it('accepts Apple Silicon', () => {+ expect(call('runner.validate_host("Darwin", "arm64") or "OK"')).toBe('OK');+ });++ // Without `text_encoder/` the pipeline silently falls back to the remote+ // LTX-2.3 Gemma 3 id — the wrong conditioner for these weights AND an+ // unannounced multi-GB download. That fallback is why this is a refusal.+ it('refuses a model pack missing its own text encoder', () => {+ const pack = mkdtempSync(join(tmpdir(), 'portos-ltx25-pack-'));+ expect(call(`runner.validate_model_dir(${JSON.stringify(pack)})`))+ .toMatch(/^REJECTED:.*text_encoder\/config\.json/);+ });++ it('refuses a model directory that does not exist', () => {+ expect(call(`runner.validate_model_dir(${JSON.stringify(join(scratch, 'no-such-pack'))})`))+ .toMatch(/^REJECTED:.*not cached/);+ });+});++describe.skipIf(!pyBin)('upscale_ltx25.py — adapter metadata (#6512)', () => {+ // The registry holds `null` for this gated weight because nobody in the repo+ // can open it. The runner reads the real value off the file the user+ // downloaded, which is the whole "read, not guessed" contract.+ it('reads reference_downscale_factor off the weight, defaulting to 1 when absent', () => {+ const plain = join(scratch, 'plain.safetensors');+ writeSafetensors(plain, { 'transformer_blocks.0.attn1.to_q.lora_A.weight': {} });+ expect(call(`runner.reference_downscale_factor(runner.read_safetensors_header(${JSON.stringify(ADAPTER)}))`)).toBe('2');+ expect(call(`runner.reference_downscale_factor(runner.read_safetensors_header(${JSON.stringify(plain)}))`)).toBe('1');+ // An unreadable header is not a measurement of 1 either — but the caller+ // refuses on the None, so the factor helper stays total.+ expect(call('runner.reference_downscale_factor(None)')).toBe('1');+ });++ it('returns None for a file that is not safetensors rather than raising', () => {+ expect(call(`repr(runner.read_safetensors_header(${JSON.stringify(REFERENCE)}))`)).toBe('None');+ expect(call(`repr(runner.read_safetensors_header(${JSON.stringify(join(scratch, 'nope.safetensors'))}))`)).toBe('None');+ });++ // The rule the pipeline enforces applies to the STAGE-1 dims, which are half+ // the output — so a factor of 2 really demands an output divisible by 4. The+ // message has to speak in output terms because that is what the user chose.+ it('enforces the adapter factor against the half-resolution stage dims', () => {+ expect(call('runner.assert_reference_scale_fits(2, 1728, 1024) or "OK"')).toBe('OK');+ expect(call('runner.assert_reference_scale_fits(1, 100, 100) or "OK"')).toBe('OK');+ expect(call('runner.assert_reference_scale_fits(4, 1028, 1024) or "OK"'))+ .toMatch(/^REJECTED:.*divisible by 8/);+ });++ // `apply_loras` pairs lora_A with lora_B per weight and skips a prefix missing+ // either half — so a half-pair contributes nothing and must not be counted as+ // coverage, or the no-op guard would pass on an adapter that fuses nothing.+ it('counts only complete lora_A/lora_B pairs as fusable targets', () => {+ const names = JSON.stringify([+ 'transformer_blocks.0.attn1.to_q.lora_A.weight',+ 'transformer_blocks.0.attn1.to_q.lora_B.weight',+ 'transformer_blocks.1.ff.proj_in.lora_A.weight',+ ]);+ expect(call(`sorted(runner.lora_target_keys(${names}))`))+ .toBe("['transformer_blocks.0.attn1.to_q.weight']");+ expect(call('sorted(runner.lora_target_keys([]))')).toBe('[]');+ });++ // The failure #6512 names: an adapter whose keys address nothing fuses no+ // deltas, raises nothing, and renders the plain base model dressed as an+ // upscale. Only the header is read, so the guard costs no tensor I/O.+ it('refuses an adapter that would fuse into nothing, and reports coverage when it would', () => {+ const foreign = join(scratch, 'foreign.safetensors');+ writeSafetensors(foreign, {+ 'some.other.model.layer.lora_A.weight': {},+ 'some.other.model.layer.lora_B.weight': {},+ });+ const modelKeys = JSON.stringify(['transformer_blocks.0.attn1.to_q.weight']);+ // `rename` is the runtime's own SDOps map in production; identity here keeps+ // the test off the MLX wheel while exercising the same intersection.+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(foreign)}, ${modelKeys}, lambda name: name)`))+ .toMatch(/^REJECTED:.*do not address any weight/);++ const matching = join(scratch, 'matching.safetensors');+ writeSafetensors(matching, {+ 'transformer_blocks.0.attn1.to_q.lora_A.weight': {},+ 'transformer_blocks.0.attn1.to_q.lora_B.weight': {},+ });+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(matching)}, ${modelKeys}, lambda name: name)`)).toBe('1');+ });++ // An unreadable transformer means the guard cannot answer its own question.+ // Reporting "fuses into nothing" would blame the adapter; reporting success+ // would defeat the guard — so it refuses on its own blindness instead.+ it('refuses when the transformer weight names could not be read at all', () => {+ const matching = join(scratch, 'matching.safetensors');+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(matching)}, set(), lambda name: name)`))+ .toMatch(/^REJECTED:.*Could not read the LTX-2\.5 transformer/);+ });+});++// The guard reads the model's parameter names off the DiT header rather than+// loading it, because `ICLoraPipeline.generate` loads Gemma, encodes, frees it+// and only THEN loads the transformer — a pre-load to inspect parameters would+// hold a multi-GB DiT resident through prompt encoding.+describe.skipIf(!pyBin)('upscale_ltx25.py — transformer header (#6512)', () => {+ it('strips the transformer. prefix load_split_safetensors strips, and keeps only weights', () => {+ const dit = join(scratch, 'transformer.safetensors');+ writeSafetensors(dit, {+ 'transformer.transformer_blocks.0.attn1.to_q.weight': {},+ // A quantized pack's siblings ride along with their weight rather than+ // being fused into, so they are not fusable targets.+ 'transformer.transformer_blocks.0.attn1.to_q.scales': {},+ 'transformer.transformer_blocks.0.attn1.to_q.biases': {},+ // Not under the prefix — load_split_safetensors drops it outright.+ 'vae.encoder.conv_in.weight': {},+ });+ expect(call(`sorted(runner.transformer_weight_keys(__import__("pathlib").Path(${JSON.stringify(dit)})))`))+ .toBe("['transformer_blocks.0.attn1.to_q.weight']");+ });++ it('returns an empty set for an unreadable file rather than raising', () => {+ expect(call(`runner.transformer_weight_keys(__import__("pathlib").Path(${JSON.stringify(REFERENCE)}))`))+ .toBe('set()');+ });++ // Mirrors BasePipeline._resolve_safetensors: plain name wins, else the+ // lexicographically last versioned file, else None so the caller can say so.+ it('resolves the same transformer file the pipeline would', () => {+ const pack = mkdtempSync(join(tmpdir(), 'portos-ltx25-dit-'));+ const resolve = (dir) => call(`repr(runner.resolve_transformer_path(__import__("pathlib").Path(${JSON.stringify(dir)})) and runner.resolve_transformer_path(__import__("pathlib").Path(${JSON.stringify(dir)})).name)`);+ expect(resolve(pack)).toBe('None');++ writeFileSync(join(pack, 'transformer-distilled-1.0.safetensors'), '');+ writeFileSync(join(pack, 'transformer-distilled-1.1.safetensors'), '');+ expect(resolve(pack)).toBe("'transformer-distilled-1.1.safetensors'");++ writeFileSync(join(pack, 'transformer.safetensors'), '');+ expect(resolve(pack)).toBe("'transformer.safetensors'");+ });+});diff --git a/server/lib/icLoraWeights.js b/server/lib/icLoraWeights.jsindex 716863fe53..c85654cab7 100644--- a/server/lib/icLoraWeights.js+++ b/server/lib/icLoraWeights.js@@ -29,6 +29,7 @@// without an HF token.import { findCachedRepoFile } from './hfCache.js';+import { readSafetensorsHeader } from './safetensors.js';// The base model the MLX `ICLoraPipeline` remix path is pinned to. A weight// whose `baseModel` is anything else is registered here for PROVISIONING only —@@ -169,13 +170,19 @@ export const IC_LORA_MODES = Object.freeze({revision: '5863fdef3eaa8b2d69fa22e259a1d75fede215dd',// Exact, from the repo's blob listing — not an estimate. Do not round it.sizeBytes: 327_322_640,- // UNKNOWN, deliberately. Every other entry's factor was read from the- // weight's safetensors `__metadata__`, and this weight's file is gated —- // so there is nothing to read yet. `null` means "no constraint asserted",- // which icResolutionIssue treats as "impose no rule" rather than guessing- // a factor and either rejecting valid resolutions or green-lighting bad- // ones. Fill it in from the real metadata once an install with accepted- // terms can read the header (#6512).+ // UNKNOWN, deliberately, and it STAYS unknown here. Every other entry's+ // factor was read from the weight's safetensors `__metadata__`; this+ // weight's file is gated, so there is nothing for the repo to read. `null`+ // means "no constraint asserted", which icResolutionIssue treats as "impose+ // no rule" rather than guessing a factor and either rejecting valid+ // resolutions or green-lighting bad ones.+ //+ // #6512 resolved this by MEASURING instead of transcribing: an install that+ // has accepted the terms and downloaded the weight reads the real value out+ // of the file it holds (`readIcLoraReferenceDownscaleFactor` below, and+ // `reference_downscale_factor` in `scripts/upscale_ltx25.py`, which enforces+ // it). Hardcoding a number here would put a value nobody in this repo can+ // verify ahead of the one every user can — so leave it null.referenceDownscaleFactor: null,// The clip being upscaled is the single reference.minReferences: 1,@@ -322,6 +329,38 @@ export const icResolutionIssue = (spec, width, height) => {return `${spec.label} mode needs a resolution divisible by ${scale} (its reference encoder downscales by ${scale}); got ${width}×${height}.`;};+/**+ * The reference downscale factor a spec's DOWNLOADED weight actually declares.+ *+ * `referenceDownscaleFactor` on the registry entry is what this repo could+ * verify when the entry was written; for a gated weight that is `null`. This+ * reads the truth off the file an install holds — the same+ * `__metadata__.reference_downscale_factor` the MLX pipeline itself reads+ * (`iclora_utils.read_lora_reference_downscale_factor`) — so the resolution+ * rule can be stated before a render commits to it.+ *+ * Returns `{ factor, measured }`: `measured` is true only when the value came+ * off a real local file. When nothing is cached (or the header is unreadable)+ * it falls back to the registry value, which may itself be `null` — absent and+ * "declared 1" must stay distinguishable, so this never coerces one into the+ * other.+ */+export const readIcLoraReferenceDownscaleFactor = async (spec) => {+ const declared = typeof spec?.referenceDownscaleFactor === 'number' ? spec.referenceDownscaleFactor : null;+ const cached = spec ? await findCachedIcLoraWeight(spec) : null;+ if (!cached) return { factor: declared, measured: false };+ const header = await readSafetensorsHeader(cached.path);+ const raw = header?.__metadata__?.reference_downscale_factor;+ const factor = Number.parseInt(raw, 10);+ // The key is absent on a weight that imposes no rule, which the pipeline+ // reads as 1 — so an absent key is a real measurement of "no rule", while an+ // unreadable header is not a measurement at all.+ if (!header) return { factor: declared, measured: false };+ return Number.isInteger(factor) && factor >= 1+ ? { factor, measured: true }+ : { factor: 1, measured: true };+};+// Locate a spec's weight in the local HF cache. Walks every candidate (official// repo, then the un-gated mirror) and pins the EXACT filename inside the newest// snapshot rather than letting the pipeline glob-pick among severaldiff --git a/server/lib/icLoraWeights.test.js b/server/lib/icLoraWeights.test.jsindex 55c73d1f88..b9a64f491c 100644--- a/server/lib/icLoraWeights.test.js+++ b/server/lib/icLoraWeights.test.js@@ -5,18 +5,23 @@ import { join } from 'node:path';// cache and existsSync probes the pinned weight file. Mock them so these tests// cover the registry + resolution logic rather than the user's ~/.cache layout// (hfCache.test.js already covers the cache walk).-const { mockFindCachedRepoFile } = vi.hoisted(() => ({ mockFindCachedRepoFile: vi.fn() }));+const { mockFindCachedRepoFile, mockReadSafetensorsHeader } = vi.hoisted(() => ({+ mockFindCachedRepoFile: vi.fn(), mockReadSafetensorsHeader: vi.fn(),+}));vi.mock('./hfCache.js', () => ({ findCachedRepoFile: mockFindCachedRepoFile }));+vi.mock('./safetensors.js', () => ({ readSafetensorsHeader: mockReadSafetensorsHeader }));const {IC_LORA_MODES, IC_LORA_MODE_VALUES, IC_LORA_WEIGHT_KEYS, IC_LORA_REMIX_BASE_MODEL,isIcLoraMode, icLoraSpecForMode, icLoraSpecByKey, icLoraWeightKey, icLoraProbesExactFile,icLoraRepos, listIcLoraWeights, listIcLoraRemixModes, icLoraWeightCandidates,findCachedIcLoraWeight, resolveIcLoraWeight, resolveIcLoraWeightByKey, icResolutionIssue,+ readIcLoraReferenceDownscaleFactor,} = await import('./icLoraWeights.js');beforeEach(() => {mockFindCachedRepoFile.mockReset();+ mockReadSafetensorsHeader.mockReset();});describe('IC-LoRA registry', () => {@@ -405,3 +410,53 @@ describe('the LTX-2.5 Pixel Spatial Upscaler weight (#6502)', () => {expect(mockFindCachedRepoFile).not.toHaveBeenCalled();});});++// #6512. The Pixel Spatial Upscaler entry holds `referenceDownscaleFactor: null`+// because its file is gated and nobody in this repo can read it — so the value+// is MEASURED off the weight an install downloaded rather than transcribed from+// a card. `measured` is what keeps "the weight declares 1" apart from "nobody+// has read it yet": both impose no rule, but only one is a fact.+describe('readIcLoraReferenceDownscaleFactor', () => {+ const upscaler = () => icLoraSpecByKey('pixel-upscale');++ it('falls back to the registry value when nothing is cached, without reading a file', async () => {+ mockFindCachedRepoFile.mockResolvedValue(null);+ expect(await readIcLoraReferenceDownscaleFactor(upscaler()))+ .toEqual({ factor: null, measured: false });+ expect(mockReadSafetensorsHeader).not.toHaveBeenCalled();+ });++ it('reads the declared factor off the downloaded weight', async () => {+ mockFindCachedRepoFile.mockResolvedValue('/cache/upscaler.safetensors');+ mockReadSafetensorsHeader.mockResolvedValue({ __metadata__: { reference_downscale_factor: '2' } });+ expect(await readIcLoraReferenceDownscaleFactor(upscaler()))+ .toEqual({ factor: 2, measured: true });+ expect(mockReadSafetensorsHeader).toHaveBeenCalledWith('/cache/upscaler.safetensors');+ });++ // An ABSENT key is a real measurement — the pipeline reads it as 1, and a+ // weight that imposes no rule is exactly what that looks like on disk.+ it('treats an absent metadata key on a real file as a measured 1', async () => {+ mockFindCachedRepoFile.mockResolvedValue('/cache/upscaler.safetensors');+ mockReadSafetensorsHeader.mockResolvedValue({ 'transformer_blocks.0.attn1.to_q.weight': {} });+ expect(await readIcLoraReferenceDownscaleFactor(upscaler()))+ .toEqual({ factor: 1, measured: true });+ });++ // An UNREADABLE header is not a measurement of anything. Collapsing it into a+ // measured 1 would assert a rule off a file we failed to open.+ it('does not claim a measurement when the header cannot be read', async () => {+ mockFindCachedRepoFile.mockResolvedValue('/cache/truncated.safetensors');+ mockReadSafetensorsHeader.mockResolvedValue(null);+ expect(await readIcLoraReferenceDownscaleFactor(upscaler()))+ .toEqual({ factor: null, measured: false });+ });++ // A 2.3 weight already carries a verified number, so a cached read must agree+ // with it rather than quietly overriding the registry with junk.+ it('reports a declared 2.3 factor as declared until the file is read', async () => {+ mockFindCachedRepoFile.mockResolvedValue(null);+ expect(await readIcLoraReferenceDownscaleFactor(IC_LORA_MODES.control))+ .toEqual({ factor: 2, measured: false });+ });+});diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex 2e01566c61..dab947e376 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -993,13 +993,17 @@ const LTX_UPSCALE_RUNNERS = Object.freeze({* There is deliberately no model id here. The base LTX-2.5 checkpoint is the* runner's own pinned dependency (#6512 / #6513), not a user-selectable render* model, so naming one would invite an upscale conditioned on a checkpoint the- * adapter was never trained against.+ * adapter was never trained against. `baseModelPath` is that pinned checkpoint+ * already RESOLVED to a local snapshot by the dispatch — a located dependency,+ * not a choice — because the runner must never resolve it itself: every LTX+ * pipeline's loader falls back to `snapshot_download` for a path it cannot+ * stat, which for a ~68 GB pack is an unannounced pull mid-render.** `width`/`height`/`numFrames` are the ALIGNED target the caller already padded* its source up to, so this builder asserts the grid rather than re-deriving it.*/export const buildLtxUpscaleArgs = ({- runtime, sourceVideoPath, icLoraWeightPath, icMinReferences, icMaxReferences,+ runtime, sourceVideoPath, baseModelPath, icLoraWeightPath, icMinReferences, icMaxReferences,width, height, numFrames, fps, seed, outputPath,}) => {const runner = LTX_UPSCALE_RUNNERS[runtime];@@ -1010,6 +1014,12 @@ export const buildLtxUpscaleArgs = ({);}assertByovRuntimeInstalled(runtime);+ if (!baseModelPath) {+ throw new ServerError(+ 'The LTX-2.5 model pack this backend renders against is not cached — download or repair it in Video Gen first.',+ { status: 400, code: 'UPSCALE_BASE_MODEL_UNRESOLVED' },+ );+ }if (!icLoraWeightPath) {throw new ServerError('The Pixel Spatial Upscaler weight is not downloaded — download it from the model panel first.',@@ -1050,6 +1060,7 @@ export const buildLtxUpscaleArgs = ({bin: runner.bin,args: [runner.script,+ '--model', baseModelPath,'--ic-lora-path', icLoraWeightPath,'--ic-reference', sourceVideoPath,'--ic-min-references', bound(icMinReferences, '--ic-min-references'),diff --git a/server/services/videoGen/renderArgsUpscale.test.js b/server/services/videoGen/renderArgsUpscale.test.jsindex 89e583e537..09bf88ad3b 100644--- a/server/services/videoGen/renderArgsUpscale.test.js+++ b/server/services/videoGen/renderArgsUpscale.test.js@@ -26,6 +26,7 @@ const REFERENCE = fileURLToPath(import.meta.url);const upscale = (extra = {}) => ({runtime: 'ltx25',sourceVideoPath: REFERENCE,+ baseModelPath: '/fixture/cache/ltx25-mlx-q8',icLoraWeightPath: '/fixture/cache/pixel-spatial-upscaler.safetensors',icMinReferences: 1,icMaxReferences: 1,@@ -43,6 +44,7 @@ describe('buildLtxUpscaleArgs (#6511)', () => {bin: '/fixture/ltx-2.5-mlx/.venv/bin/python3',args: ['/fixture/scripts/upscale_ltx25.py',+ '--model', '/fixture/cache/ltx25-mlx-q8','--ic-lora-path', '/fixture/cache/pixel-spatial-upscaler.safetensors','--ic-reference', REFERENCE,'--ic-min-references', '1',@@ -76,6 +78,14 @@ describe('buildLtxUpscaleArgs (#6511)', () => {.toThrow(expect.objectContaining({ code: 'IC_LORA_REFERENCE_BOUNDS_MISSING' }));});+ // Same reason as the adapter refusal below, one layer up: the runner is handed+ // a RESOLVED snapshot dir, and every LTX loader turns an unstattable path into+ // `snapshot_download` — a ~68 GB pull nobody announced (#6512).+ it('refuses an un-cached base checkpoint rather than letting the runner resolve one', () => {+ expect(() => buildLtxUpscaleArgs({ ...upscale({ baseModelPath: null }), outputPath: '/fixture/out.mp4' }))+ .toThrow(expect.objectContaining({ code: 'UPSCALE_BASE_MODEL_UNRESOLVED' }));+ });+it('refuses an un-downloaded adapter rather than handing the pipeline a repo id', () => {expect(() => buildLtxUpscaleArgs({ ...upscale({ icLoraWeightPath: null }), outputPath: '/fixture/out.mp4' })).toThrow(expect.objectContaining({ code: 'IC_LORA_WEIGHT_UNRESOLVED' }));diff --git a/server/services/videoGen/upscaleJob.js b/server/services/videoGen/upscaleJob.jsindex 6d3bc014b5..5d0087eb12 100644--- a/server/services/videoGen/upscaleJob.js+++ b/server/services/videoGen/upscaleJob.js@@ -66,9 +66,9 @@ const upscaledPrompt = (prompt) => (prompt ? `${prompt} (2×)` : '(upscaled 2×)/*** Validate an upscale request and queue it. Everything that can be known* before a GPU is committed is checked HERE — an unsupported/uninstalled- * runtime, a missing adapter, and a source the model grid cannot take without- * losing duration — so a refusal is an immediate 4xx/501 rather than a job that- * fails minutes later.+ * runtime, a missing adapter, a missing base checkpoint, and a source the model+ * grid cannot take without losing duration — so a refusal is an immediate+ * 4xx/501 rather than a job that fails minutes later.*/export async function enqueueLtxUpscale(historyId) {const plan = await planUpscaleHistoryItem(historyId, { method: 'ltx' });@@ -91,6 +91,16 @@ export async function enqueueLtxUpscale(historyId) {{ status: 400, code: 'IC_LORA_WEIGHT_UNRESOLVED' },);}+ // The runner is never allowed to resolve its own checkpoint: every LTX loader+ // falls back to `snapshot_download` for a path it cannot stat, which for this+ // pack is an unannounced ~68 GB pull inside a render. Resolved here, cache-only,+ // so a missing pack is a refusal before the GPU is committed.+ if (!plan.baseModel?.cached || !plan.baseModel.path) {+ throw new ServerError(+ plan.baseModel?.reason || 'The LTX-2.5 model pack for this backend is not downloaded.',+ { status: 400, code: 'UPSCALE_BASE_MODEL_UNRESOLVED' },+ );+ }const blocker = ltxAlignmentBlocker(plan.alignment);if (blocker) {throw new ServerError(blocker, { status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' });@@ -121,6 +131,8 @@ export async function enqueueLtxUpscale(historyId) {runtime: plan.runtime.id,adapterKey: plan.adapter.key,adapterPath: adapter.path,+ // The resolved snapshot directory, not the repo id — see the refusal above.+ baseModelPath: plan.baseModel.path,// Explicit, from the weight registry — the Python helper is never allowed// to carry its own copy of these bounds (see buildLtxUpscaleArgs).icMinReferences: adapter.spec.minReferences,@@ -244,7 +256,7 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {* distinguish them on the wire.*/export async function runVideoUpscale({- jobId, historyId, sourceFilename, runtime, adapterPath, adapterKey,+ jobId, historyId, sourceFilename, runtime, adapterPath, adapterKey, baseModelPath,icMinReferences, icMaxReferences, seed, source, alignment, target,}) {const entry = { canceled: false, proc: null, abort: new AbortController() };@@ -315,6 +327,7 @@ export async function runVideoUpscale({upscale: {runtime,sourceVideoPath: referencePath,+ baseModelPath,icLoraWeightPath: adapterPath,icMinReferences,icMaxReferences,diff --git a/server/services/videoGen/upscaleJob.test.js b/server/services/videoGen/upscaleJob.test.jsindex 1c1863d9ce..df0b576e87 100644--- a/server/services/videoGen/upscaleJob.test.js+++ b/server/services/videoGen/upscaleJob.test.js@@ -109,6 +109,11 @@ const conformingPlan = () => ({},runtime: { id: 'ltx25', label: 'LTX-2.5 MLX', supported: true, installed: true, reason: null },adapter: { key: 'pixel-upscale', label: 'Pixel Spatial Upscaler', cached: true },+ baseModel: {+ id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8', repo: 'MrMofer/ltx-2.5-mlx-q8',+ revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ path: '/cache/ltx25-mlx-q8', cached: true, reason: null,+ },});const sourceRow = (extra = {}) => ({@@ -132,6 +137,7 @@ const jobParams = (overrides = {}) => ({runtime: 'ltx25',adapterPath: '/cache/pixel-upscale.safetensors',adapterKey: 'pixel-upscale',+ baseModelPath: '/cache/ltx25-mlx-q8',icMinReferences: 1,icMaxReferences: 1,seed: 4242,@@ -189,6 +195,7 @@ describe('enqueueLtxUpscale', () => {runtime: 'ltx25',adapterKey: 'pixel-upscale',adapterPath: '/cache/pixel-upscale.safetensors',+ baseModelPath: '/cache/ltx25-mlx-q8',icMinReferences: 1,icMaxReferences: 1,seed: expect.any(Number),@@ -250,6 +257,22 @@ describe('enqueueLtxUpscale', () => {expect(enqueueJob).not.toHaveBeenCalled();});+ // #6512: the ~68 GB base pack is a THIRD download, independent of the venv and+ // the adapter. The runner is handed a resolved snapshot path precisely so it+ // never resolves one itself — every LTX loader falls back to+ // `snapshot_download` for a path it cannot stat, which here would be an+ // unannounced 68 GB pull in the middle of a render.+ it('refuses when the base LTX-2.5 pack is not downloaded, even with runtime and adapter ready', async () => {+ state.plan.baseModel = {+ id: 'ltx25_mlx_q8', name: 'LTX-2.5 MLX Q8', repo: 'MrMofer/ltx-2.5-mlx-q8',+ revision: 'f1b56e7dc89f71a9af2cddac787b89ed22a8b7fc',+ path: null, cached: false, reason: 'LTX-2.5 MLX Q8 is not downloaded — download or repair it in Video Gen.',+ };+ await expect(enqueueLtxUpscale(SOURCE_ID))+ .rejects.toMatchObject({ status: 400, code: 'UPSCALE_BASE_MODEL_UNRESOLVED' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });+it('keeps the already-upscaled guard, matching the inline path', async () => {state.plan.alreadyUpscaled = true;await expect(enqueueLtxUpscale(SOURCE_ID))diff --git a/server/services/videoGen/upscalePlan.js b/server/services/videoGen/upscalePlan.jsindex 20881c8065..6f3db359ac 100644--- a/server/services/videoGen/upscalePlan.js+++ b/server/services/videoGen/upscalePlan.js@@ -38,11 +38,33 @@ export const ltxUpscaleRuntimeId = (platform = process.platform) => (LTX_UPSCALE_RUNTIME_BY_PLATFORM[platform] || null);+// The base checkpoint each generative backend renders against. #6511 keeps the+// model out of the REQUEST on purpose — the adapter was trained against one+// LTX-2.5 checkpoint, so letting a user pick another would condition an upscale+// on weights it was never trained for. It is still a dependency that has to be+// LOCATED, so the runtime names its own pin here and the dispatch resolves it+// cache-only, exactly like every other pinned LTX entry (generateVideo.js).+export const LTX_UPSCALE_BASE_MODEL_BY_RUNTIME = Object.freeze({+ ltx25: 'ltx25_mlx_q8',+ ltx25_cuda: 'ltx25_cuda_distilled',+});++export const ltxUpscaleBaseModelId = (runtime) => (+ LTX_UPSCALE_BASE_MODEL_BY_RUNTIME[runtime] || null+);+// The LTX-2.5 two-stage grid, mirrored from `validate_args` in// `scripts/generate_ltx25_cuda.py`: output dimensions must be divisible by 64-// and the frame count must satisfy `frames % 8 == 1` with a floor of 9. The-// MLX runner (#6512) must establish the same rule from the model card; if it-// turns out to differ, this constant is the single place both read.+// and the frame count must satisfy `frames % 8 == 1` with a floor of 9.+//+// #6512 confirmed the MLX backend imposes the SAME rule, and read it off the+// pinned runtime rather than the gated model card: `ICLoraPipeline.generate`+// renders Stage 1 at `height // 2` / `width // 2`, and+// `compute_video_latent_shape` compresses spatially by 32 — so the OUTPUT axis+// must divide by 64. Temporal compression is 8 and the IC reference encoder+// needs a (1 + 8k)-frame input, which is the frame rule. Both runners now read+// the rule from here; `scripts/upscale_ltx25.py` mirrors the numbers with a+// comment pointing back, the way the CUDA runner already does.export const LTX_GRID = Object.freeze({spatialMultiple: 64,frameModulus: 8,diff --git a/server/services/videoGen/upscaleVideo.js b/server/services/videoGen/upscaleVideo.jsindex 34d49792bf..d97707d1a0 100644--- a/server/services/videoGen/upscaleVideo.js+++ b/server/services/videoGen/upscaleVideo.js@@ -11,11 +11,16 @@ import {} from '../../lib/ffmpeg.js';import { loadHistory, mutateVideoHistory } from './history.js';import { omitRenderTiming, renderTimingFields } from '../../lib/renderTiming.js';-import { resolveIcLoraWeightByKey, icLoraSpecByKey, icLoraWeightKey } from '../../lib/icLoraWeights.js';+import {+ resolveIcLoraWeightByKey, icLoraSpecByKey, icLoraWeightKey, readIcLoraReferenceDownscaleFactor,+} from '../../lib/icLoraWeights.js';+import { getVideoModels } from '../../lib/mediaModels.js';+import { inspectModelCache } from '../../lib/hfCache.js';import { BYOV_RUNTIME_INFO, isByovRuntimeInstalled } from './runtimes.js';import {UPSCALE_METHODS, DEFAULT_UPSCALE_METHOD, UPSCALE_SCALE, LANCZOS_RUNTIME_ID,- LTX_UPSCALE_WEIGHT_KEY, ltxUpscaleRuntimeId, planLtxAlignment, planTargetDimensions,+ LTX_UPSCALE_WEIGHT_KEY, ltxUpscaleRuntimeId, ltxUpscaleBaseModelId,+ planLtxAlignment, planTargetDimensions,} from './upscalePlan.js';export * from './upscalePlan.js';@@ -87,6 +92,12 @@ const describeLtxRuntime = () => {const describeLtxAdapter = async () => {const spec = icLoraSpecByKey(LTX_UPSCALE_WEIGHT_KEY);const resolved = await resolveIcLoraWeightByKey(LTX_UPSCALE_WEIGHT_KEY);+ // Read off the downloaded file when there is one, so the registry's honest+ // `null` for this gated weight resolves to the real number on the installs+ // that actually hold it (#6512). `measured` keeps "the weight declares 1"+ // apart from "nobody has read it yet" — both impose no rule, but only one is+ // a fact.+ const { factor, measured } = await readIcLoraReferenceDownscaleFactor(spec);return {key: icLoraWeightKey(spec),label: spec?.label ?? null,@@ -95,6 +106,39 @@ const describeLtxAdapter = async () => {sizeBytes: spec?.sizeBytes ?? null,gated: spec?.gated === true,cached: resolved?.cached === true,+ referenceDownscaleFactor: factor,+ referenceDownscaleMeasured: measured,+ };+};++// The pinned base checkpoint the backend renders against (#6512). It is a+// THIRD readiness axis alongside the runtime and the adapter: a host can have+// the venv and the 327 MB adapter and still be missing the ~68 GB pack, and+// without this the drawer would show a ready button for a job that dies minutes+// later. Cache-only by construction — `inspectModelCache` reads the local HF+// cache and never fetches, which is what keeps the plan endpoint read-only.+const describeLtxBaseModel = async (runtimeId) => {+ const id = ltxUpscaleBaseModelId(runtimeId);+ const model = id ? getVideoModels().find((m) => m.id === id) || null : null;+ if (!model) {+ return {+ id, name: null, repo: null, revision: null, path: null, cached: false,+ reason: `No base LTX-2.5 checkpoint is registered for the ${runtimeId || 'unknown'} backend.`,+ };+ }+ const cache = await inspectModelCache(model.repo, { revision: model.revision || undefined });+ const cached = !!(cache.cached && cache.snapshotPath);+ return {+ id: model.id,+ name: model.name,+ repo: model.repo,+ revision: model.revision ?? null,+ // The resolved snapshot directory the runner is handed as `--model`. Null+ // until it is cached, so a caller cannot mistake "not downloaded" for a+ // path that happens to be missing on disk.+ path: cached ? cache.snapshotPath : null,+ cached,+ reason: cached ? null : `${model.name} is not downloaded — download or repair it in Video Gen.`,};};@@ -136,7 +180,9 @@ export async function planUpscaleHistoryItem(historyId, options = {}) {const runtime = method === 'ltx'? describeLtxRuntime(): { id: LANCZOS_RUNTIME_ID, label: 'ffmpeg (Lanczos)', supported: true, installed: true, reason: null };- const adapter = method === 'ltx' ? await describeLtxAdapter() : null;+ const [adapter, baseModel] = method === 'ltx'+ ? await Promise.all([describeLtxAdapter(), describeLtxBaseModel(runtime.id)])+ : [null, null];return {id: item.id,@@ -148,6 +194,7 @@ export async function planUpscaleHistoryItem(historyId, options = {}) {alignment,runtime,adapter,+ baseModel,};}diff --git a/server/services/videoGen/upscaleVideo.test.js b/server/services/videoGen/upscaleVideo.test.jsindex 25844c9fe8..72b4f4bfc1 100644--- a/server/services/videoGen/upscaleVideo.test.js+++ b/server/services/videoGen/upscaleVideo.test.js@@ -21,6 +21,10 @@ const state = vi.hoisted(() => ({hasAudio: false,runtimeInstalled: true,adapterCached: true,+ baseModelCached: true,+ // What the adapter's own safetensors metadata says. `null` is the registry's+ // honest "nobody has opened this gated weight"; a number is a real read.+ referenceDownscale: { factor: 2, measured: true },}));const mutated = vi.hoisted(() => ({ calls: 0 }));@@ -54,6 +58,17 @@ vi.mock('../../lib/icLoraWeights.js', () => ({})),icLoraWeightKey: vi.fn((spec) => spec?.id ?? null),resolveIcLoraWeightByKey: vi.fn(async () => ({ path: state.adapterCached ? '/cache/weight.safetensors' : null, cached: state.adapterCached })),+ readIcLoraReferenceDownscaleFactor: vi.fn(async () => state.referenceDownscale),+}));++// The base checkpoint is the third readiness axis (#6512). Mocked at the cache+// layer rather than the registry so the plan still resolves the real+// `ltx25_mlx_q8` entry — a wrong id here would otherwise pass silently.+vi.mock('../../lib/hfCache.js', () => ({+ inspectModelCache: vi.fn(async () => (state.baseModelCached+ ? { cached: true, snapshotPath: '/cache/ltx25-mlx-q8' }+ : { cached: false, snapshotPath: null })),+ findCachedRepoFile: vi.fn(async () => null),}));const { upscaleHistoryItem, planUpscaleHistoryItem } = await import('./upscaleVideo.js');@@ -80,6 +95,8 @@ beforeEach(() => {state.hasAudio = false;state.runtimeInstalled = true;state.adapterCached = true;+ state.baseModelCached = true;+ state.referenceDownscale = { factor: 2, measured: true };mutated.calls = 0;vi.clearAllMocks();});@@ -205,10 +222,14 @@ describe('planUpscaleHistoryItem', () => {expect(plan.source.hasAudio).toBe(true);});- it('reports runtime and adapter readiness for the generative method', async () => {+ it('reports runtime, adapter and base-model readiness for the generative method', async () => {const ready = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });expect(ready.runtime).toMatchObject({ supported: true, installed: true, reason: null });expect(ready.adapter).toMatchObject({ key: 'pixel-upscale', cached: true, gated: true });+ // Three INDEPENDENT axes: the venv, the 327 MB adapter and the ~68 GB pack+ // are separate downloads, so a plan that only reported two would show a+ // ready button for a job the dispatch refuses (#6512).+ expect(ready.baseModel).toMatchObject({ id: 'ltx25_mlx_q8', cached: true, path: '/cache/ltx25-mlx-q8', reason: null });state.runtimeInstalled = false;state.adapterCached = false;@@ -218,6 +239,29 @@ describe('planUpscaleHistoryItem', () => {expect(unready.adapter.cached).toBe(false);});+ it('reports a missing base checkpoint as its own unready axis, with a path of null', async () => {+ state.baseModelCached = false;+ const plan = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ // Runtime + adapter both ready — only the pack is missing, which is exactly+ // the state a two-axis readiness check would have called ready.+ expect(plan.runtime.installed).toBe(true);+ expect(plan.adapter.cached).toBe(true);+ expect(plan.baseModel).toMatchObject({ cached: false, path: null });+ expect(plan.baseModel.reason).toMatch(/not downloaded/i);+ });++ // The registry holds `null` for this gated weight on purpose. An install that+ // HAS the file knows better than the repo does, so the plan reports the read+ // value and flags it as measured rather than transcribed (#6512).+ it('reports the adapter factor read off the downloaded weight, flagged as measured', async () => {+ const measured = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(measured.adapter).toMatchObject({ referenceDownscaleFactor: 2, referenceDownscaleMeasured: true });++ state.referenceDownscale = { factor: null, measured: false };+ const unread = await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });+ expect(unread.adapter).toMatchObject({ referenceDownscaleFactor: null, referenceDownscaleMeasured: false });+ });+it('queues no job, runs no ffmpeg pass and writes no history row', async () => {await planUpscaleHistoryItem(SOURCE_ID, { method: 'ltx' });await planUpscaleHistoryItem(SOURCE_ID, { method: 'lanczos' });