"""Shared test infrastructure for the LTX-2.5 Studio spec suite. Every fixture here obeys the hard constraint from PLAN §9.1: **no GPU, no network, no model weights**. Nothing in this file imports torch, diffusers, safetensors or gradio. Two deliberate choices worth knowing about: 1. **safetensors files are synthesised byte-for-byte in pure Python.** The format is trivial and documented: an 8-byte little-endian ``u64`` header length, that many bytes of UTF-8 JSON, then the tensor payload. Writing it ourselves (rather than via ``safetensors.torch.save_file``) means the LoRA suite runs on a bare venv, and — more importantly — it lets us craft the *malformed* files that PLAN §4.3 stage 3 requires: a truncated header, a corrupt header length, a payload that is never read. A torch-based writer cannot produce those. ``test_lora_inspect.py`` cross-checks the synthesised bytes against the real ``safetensors`` library when it happens to be installed, so the fixtures cannot quietly drift from the real format. 2. **Fakes mirror the *failure modes* of the real objects, not just their happy path.** ``fake_pipeline`` sets ``peft_config`` on a zero-attach load, exactly as peft does, because an implementation that checks ``peft_config`` instead of counting attached modules is the silent-garbage bug PLAN §4.3 stage 7 exists to catch. The fake must be able to express the bug or the test is theatre. """ from __future__ import annotations import builtins import io import json import struct from pathlib import Path from types import SimpleNamespace import pytest # -------------------------------------------------------------------------- # process-lifetime caches — reset between specs # -------------------------------------------------------------------------- @pytest.fixture(autouse=True) def _drop_resident_enhancer(): """Empty ``enhance._ENHANCER`` around every test in the suite. The enhancer is deliberately **resident for the life of the worker process** (``enhance.py``, and the +30.78 s per-call reload that bought). A pytest session is one process, so without this the first spec to call ``enhance()`` would serve its fake model to every spec that followed — cross-test contamination that reads as a mysterious unrelated failure. Autouse and global rather than local to ``test_enhance.py``: the cache is reachable from anything that calls ``generate()`` without injecting an ``enhancer=`` seam, so scoping the reset to the file that happens to use it today is a trap for whoever adds the next caller. Imported inside the fixture so ``conftest``'s own import surface stays as light as its docstring claims. """ from ltx25_studio import enhance _drop(enhance) yield _drop(enhance) def _drop(enhance): """``clear_enhancer_cache()``, but it can never be the thing that fails a test. The real free imports torch when the cached model reports a CUDA device, and a spec that installed a *fake* cuda-reporting model has usually had its fake ``sys.modules['torch']`` undone by ``monkeypatch`` before this teardown runs — autouse fixtures tear down last. On a machine with no torch that import then raises during cleanup and reports as an error in an unrelated test. So: attempt the real free, because that is what exercises the production path, and fall back to emptying the dict, because isolation is this fixture's only job. ``test_dropping_the_resident_enhancer_gives_the_vram_back`` is what actually holds the free honest. """ try: enhance.clear_enhancer_cache() except Exception: # noqa: BLE001 - cleanup must not fail somebody else's test enhance._ENHANCER.clear() # -------------------------------------------------------------------------- # safetensors synthesis (pure Python — no torch, no safetensors) # -------------------------------------------------------------------------- DTYPE_SIZES = { "F64": 8, "F32": 4, "F16": 2, "BF16": 2, "I64": 8, "I32": 4, "I16": 2, "U8": 1, "I8": 1, "BOOL": 1, } #: Key prefixes verified against real LTX-2.5 adapters (PLAN §4.1, §4.2). NATIVE_PREFIX = "diffusion_model." DIFFUSERS_PREFIX = "transformer." NATIVE_CONNECTOR_PREFIX = "text_embedding_projection." DIFFUSERS_CONNECTOR_PREFIX = "connectors." ALL_PREFIXES = ( NATIVE_PREFIX, DIFFUSERS_PREFIX, NATIVE_CONNECTOR_PREFIX, DIFFUSERS_CONNECTOR_PREFIX, ) #: Module paths the fake transformer exposes, with ``(in_features, out_features)``. #: #: The dimensions are the measured ones from PLAN §4.5: the transformer carries #: **two streams** — video at 4096 and audio at 2048, each with a 4x feed-forward #: expansion. That is why stage 6.5 compares per module: "contains 2048" is not a #: signal, "2048 at a module that expects 4096" is. TRANSFORMER_MODULE_DIMS = { "transformer_blocks.0.attn1.to_q": (4096, 4096), "transformer_blocks.0.attn1.to_k": (4096, 4096), "transformer_blocks.0.attn1.to_v": (4096, 4096), "transformer_blocks.1.attn1.to_q": (4096, 4096), "transformer_blocks.0.ff.net.2": (16384, 4096), "transformer_blocks.0.audio_ff.net.0.proj": (2048, 8192), "transformer_blocks.0.audio_ff.net.2": (8192, 2048), } #: Adapter keys that resolve to one of these are what "attached" means. TRANSFORMER_MODULE_PATHS = tuple(TRANSFORMER_MODULE_DIMS) CONNECTOR_MODULE_DIMS = { "layers.0.proj": (4096, 4096), "layers.1.proj": (4096, 4096), } CONNECTOR_MODULE_PATHS = tuple(CONNECTOR_MODULE_DIMS) #: Every module dimension the fake pipeline knows about, in one lookup. MODULE_DIMS = {**TRANSFORMER_MODULE_DIMS, **CONNECTOR_MODULE_DIMS} #: What an unmapped module is assumed to be — the video stream's hidden dim. DEFAULT_MODULE_DIMS = (4096, 4096) #: Rank of the synthetic adapters. The real ones range from 32 to 450. DEFAULT_RANK = 32 #: The official adapter's metadata, read from its real header (PLAN §4.2). OFFICIAL_METADATA = { "lora_rank": "450", "lora_alpha": "450", "model_version": "2.5.0", "license": "LTX-2.5 Community License", } def build_safetensors_bytes( tensors, metadata=None, *, header_length_override=None, payload_bytes_override=None, align_header=True, ): """Return the bytes of a safetensors file. ``tensors`` maps tensor name -> ``(dtype, shape)``. The payload is zero-filled; nothing here ever needs to be a real tensor, which is the whole point of PLAN §4.3 stage 2 (header-only parsing). ``header_length_override`` writes a deliberately wrong 8-byte length prefix (the "corrupt header length" case). ``payload_bytes_override`` writes fewer payload bytes than the header declares. """ header: dict[str, object] = {} offset = 0 for name, (dtype, shape) in tensors.items(): count = 1 for dim in shape: count *= dim nbytes = count * DTYPE_SIZES[dtype] header[name] = { "dtype": dtype, "shape": list(shape), "data_offsets": [offset, offset + nbytes], } offset += nbytes if metadata is not None: header["__metadata__"] = {str(k): str(v) for k, v in metadata.items()} blob = json.dumps(header).encode("utf-8") if align_header: pad = (8 - (len(blob) % 8)) % 8 blob += b" " * pad declared = len(blob) if header_length_override is None else header_length_override payload_len = offset if payload_bytes_override is None else payload_bytes_override return struct.pack(" Path: """The session's directory for real input files, under pytest's base temp. pytest keeps only its last few base temps, so these never pile up in the system temp folder. Outside pytest, a temp folder removed at exit. """ if not _MEDIA_DIR: factory = getattr(_CONFIG[-1], "_tmp_path_factory", None) if _CONFIG else None if factory is not None: _MEDIA_DIR.append(factory.mktemp("ltx25-inputs")) else: import atexit import shutil import tempfile path = Path(tempfile.mkdtemp(prefix="ltx25-inputs-")) atexit.register(shutil.rmtree, path, ignore_errors=True) _MEDIA_DIR.append(path) return _MEDIA_DIR[0] _AUDIO_FILES: dict = {} def audio_file(seconds: float = 121 / 24.0, *, rate: int = STUB_SAMPLING_RATE) -> str: """A real stereo 16-bit WAV of ``seconds`` of silence. Built once per length. The default length matches ``STUB_WAVEFORM``, so the file the web-side probe measures and the waveform the stubbed loader hands the worker agree. """ key = (round(float(seconds), 6), int(rate)) if key not in _AUDIO_FILES: import av import numpy as np path = _media_dir() / f"audio-{key[0]}s-{key[1]}hz.wav" samples = max(round(seconds * rate), 1) with av.open(str(path), "w", format="wav") as container: stream = container.add_stream("pcm_s16le", rate=rate, layout="stereo") frame = av.AudioFrame.from_ndarray( np.zeros((1, samples * 2), dtype=np.int16), format="s16", layout="stereo" ) frame.sample_rate = rate for packet in stream.encode(frame): container.mux(packet) for packet in stream.encode(): container.mux(packet) _AUDIO_FILES[key] = str(path) return _AUDIO_FILES[key] _VIDEO_FILES: dict = {} def video_file(frames: int = 1, *, size: int = 64, rate: int = 24) -> str: """A real, decodable h264 mp4 of ``frames`` black frames. Built once per shape.""" key = (int(frames), int(size), int(rate)) if key not in _VIDEO_FILES: from fractions import Fraction import av import numpy as np path = _media_dir() / f"video-{frames}f-{size}px-{rate}fps.mp4" with av.open(str(path), "w") as container: stream = container.add_stream("h264", rate=rate) stream.width = stream.height = size stream.pix_fmt = "yuv420p" for index in range(frames): frame = av.VideoFrame.from_ndarray( np.zeros((size, size, 3), dtype=np.uint8), format="rgb24" ) frame.pts, frame.time_base = index, Fraction(1, rate) for packet in stream.encode(frame): container.mux(packet) for packet in stream.encode(): container.mux(packet) _VIDEO_FILES[key] = str(path) return _VIDEO_FILES[key] def image_input(size: int = 64): """A PIL image, as ``gr.Image(type="pil")`` hands one over.""" from PIL import Image return Image.new("RGB", (size, size)) INPUT_PROMPT = "a lighthouse in heavy fog, slow dolly in" def inputs_for(mode_id: str) -> dict: """The request fields that satisfy ``mode_id``'s REQUIRED inputs, and no others. Read off the registry, so a mode whose inputs change gets matching inputs here with no edit. Audio is a real WAV; pair it with ``audio_input_ready`` where the worker side must also load it without torch. """ from ltx25_studio import modes makers = { "text": lambda: {"prompt": INPUT_PROMPT}, "image": lambda: {"image": image_input()}, "video": lambda: {"video": video_file()}, "audio": lambda: {"audio": audio_file()}, } fields: dict = {} for kind in modes.get_mode(mode_id).inputs: fields.update(makers[kind]()) return fields class FakePipeline: """Duck-types the bits of an ``LTX2*Pipeline`` that ``lora/apply.py`` touches. ``load_lora_weights`` reproduces upstream behaviour *including its hole*: * the only validation is the ``'lora'`` substring test (PLAN §4.2); * ``peft_config`` is populated whether or not anything attached — so code that checks ``peft_config`` instead of counting modules still sees a "successful" load. That is the silent-garbage path stage 7 must close. """ _lora_loadable_modules = ["transformer", "connectors"] def __init__(self, transformer_paths=None, connector_paths=None, dims=None): # The real pipeline carries one, and `generate._prepared_audio` unwraps # to `.pipeline` to find it. A fake without it made the audio-input # modes look like they had nothing to encode with. self.audio_vae = FakeAudioVae() self.transformer = FakeComponent( TRANSFORMER_MODULE_PATHS if transformer_paths is None else transformer_paths, dims=dims, ) self.connectors = FakeComponent( CONNECTOR_MODULE_PATHS if connector_paths is None else connector_paths, dims=dims, ) self.calls: list[dict] = [] self.fuse_calls: list[dict] = [] self.unfuse_calls: list[dict] = [] # -- upstream conversion table (PLAN §4.1) ---------------------------- _ROUTES = { NATIVE_PREFIX: "transformer", DIFFUSERS_PREFIX: "transformer", NATIVE_CONNECTOR_PREFIX: "connectors", DIFFUSERS_CONNECTOR_PREFIX: "connectors", } def load_lora_weights(self, source, *args, adapter_name="default", **kwargs): self.calls.append({"source": source, "adapter_name": adapter_name, "kwargs": kwargs}) header = read_safetensors_header(source) keys = [k for k in header if k != "__metadata__"] # The one and only upstream check, quoted verbatim from diffusers. if not all("lora" in k for k in keys): raise ValueError( "Invalid LoRA checkpoint. Make sure all LoRA param names contain " "`'lora'` substring." ) # The pinned loader reads lora_A/lora_B names only: with lora_down/lora_up it # finds no rank and fails like this (tests/test_lora_apply.py measures it, F59). if any(".lora_down." in k or ".lora_up." in k for k in keys): raise IndexError("list index out of range") attached = 0 for key in keys: component_name = None stripped = key for prefix, route in self._ROUTES.items(): if key.startswith(prefix): component_name = route stripped = key[len(prefix) :] break if component_name is None: continue module_path = stripped for suffix in (".lora_A.weight", ".lora_B.weight"): if module_path.endswith(suffix): module_path = module_path[: -len(suffix)] break component = getattr(self, component_name) module = component.get_module(module_path) if module is None: continue lora_a = getattr(module, "lora_A", None) if lora_a is None: lora_a = {} module.lora_A = lora_a module.lora_B = {} if adapter_name not in lora_a: lora_a[adapter_name] = object() module.lora_B[adapter_name] = object() attached += 1 # THE TRAP: peft records the adapter config even when nothing attached. for component_name in self._lora_loadable_modules: component = getattr(self, component_name, None) if component is not None: component.peft_config[adapter_name] = {"r": 450, "lora_alpha": 450} return attached def get_list_adapters(self): """Also optimistic: reports the adapter whether or not anything attached.""" return { name: list(getattr(self, name).peft_config) for name in self._lora_loadable_modules if getattr(self, name, None) is not None } def set_adapters(self, *args, **kwargs): self.calls.append({"set_adapters": (args, kwargs)}) def delete_adapters(self, adapter_names): """Mirrors ``LoraBaseMixin.delete_adapters``: drop the named adapters from every loadable component. Added when ``generate()`` grew its unload step -- the real pipeline has this, and a fake without it turns the lifecycle's cannot-detach refusal into a false alarm.""" names = [adapter_names] if isinstance(adapter_names, str) else list(adapter_names) self.calls.append({"delete_adapters": names}) for name in names: for component_name in self._lora_loadable_modules: component = getattr(self, component_name, None) if component is None: continue component.peft_config.pop(name, None) for _, module in component.named_modules(): lora_a = getattr(module, "lora_A", None) if lora_a is not None: lora_a.pop(name, None) module.lora_B.pop(name, None) def fuse_lora(self, *args, **kwargs): self.fuse_calls.append({"args": args, "kwargs": kwargs}) def unfuse_lora(self, *args, **kwargs): self.unfuse_calls.append({"args": args, "kwargs": kwargs}) @pytest.fixture def fake_pipeline(): return FakePipeline() @pytest.fixture def make_pipeline(): def _make(transformer_paths=None, connector_paths=None, dims=None): return FakePipeline(transformer_paths, connector_paths, dims=dims) return _make @pytest.fixture def fake_transformer(): """Just the transformer, for the stage 6.5 dimension checks.""" return FakeComponent(TRANSFORMER_MODULE_PATHS) # -------------------------------------------------------------------------- # byte-counting read spy — proof of PLAN §4.3 stage 2 # -------------------------------------------------------------------------- class _CountingFile: def __init__(self, wrapped, spy): self._wrapped = wrapped self._spy = spy def read(self, *args, **kwargs): chunk = self._wrapped.read(*args, **kwargs) self._spy.bytes_read += len(chunk) return chunk def readinto(self, buf): n = self._wrapped.readinto(buf) self._spy.bytes_read += n or 0 return n def readline(self, *args, **kwargs): chunk = self._wrapped.readline(*args, **kwargs) self._spy.bytes_read += len(chunk) return chunk def __enter__(self): self._wrapped.__enter__() return self def __exit__(self, *exc): return self._wrapped.__exit__(*exc) def __iter__(self): return iter(self._wrapped) def __getattr__(self, name): return getattr(self._wrapped, name) class ReadSpy: def __init__(self): self.bytes_read = 0 self.opens = 0 self.watched: set[str] = set() def watch(self, path): self.watched.add(str(Path(path).resolve())) @pytest.fixture def read_spy(monkeypatch): """Counts bytes read from watched files via ``open()`` / ``io.open()``. Both names are patched: ``pathlib.Path.open`` and ``Path.read_bytes`` route through ``io.open``, not ``builtins.open``, so patching only one leaves a hole a header parser could slip through. """ spy = ReadSpy() real_open = builtins.open def fake_open(file, mode="r", *args, **kwargs): handle = real_open(file, mode, *args, **kwargs) try: resolved = str(Path(file).resolve()) except (TypeError, ValueError, OSError): return handle if resolved in spy.watched and "b" in mode and "w" not in mode and "a" not in mode: spy.opens += 1 return _CountingFile(handle, spy) return handle monkeypatch.setattr(builtins, "open", fake_open) monkeypatch.setattr(io, "open", fake_open) return spy # -------------------------------------------------------------------------- # generation request factory # -------------------------------------------------------------------------- def request_fields(**overrides): """Every field a mode kwarg-builder could plausibly read, with legal defaults. Deliberately a plain namespace: PLAN §7.2 says the mode registry is data and the builders are pure, so they must not require a concrete class from another module. If a builder only works with the real ``GenerationRequest``, that is a coupling the registry should not have. """ fields = { "mode": "text_to_video", "prompt": "a cat playing a grand piano, cinematic", "negative_prompt": "", "width": 704, "height": 480, "num_frames": 121, "seed": 1234, "image": None, "video": None, "audio": None, "audio_latents": None, "noise_scale": 0.5, "conditions": (), "strength": 0.8, "guidance_scale": 1.0, "num_inference_steps": 8, "loras": (), } fields.update(overrides) return SimpleNamespace(**fields) @pytest.fixture def make_request(): return request_fields # -------------------------------------------------------------------------- # source-file helpers for the architecture specs # -------------------------------------------------------------------------- REPO_ROOT = Path(__file__).resolve().parent.parent PACKAGE_ROOT = REPO_ROOT / "ltx25_studio" def code_string_constants(path): """Yield ``(lineno, value)`` for every string literal that is not a docstring. Comments are invisible to ``ast`` by construction, and module/class/function docstrings are filtered explicitly — so this sees prose nowhere and code everywhere, which is what the architecture rules want to police. """ import ast tree = ast.parse(Path(path).read_text()) docstrings = set() for node in ast.walk(tree): if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): body = getattr(node, "body", None) if ( body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str) ): docstrings.add(id(body[0].value)) for node in ast.walk(tree): if isinstance(node, ast.Constant) and isinstance(node.value, str): if id(node) in docstrings: continue yield node.lineno, node.value def code_tokens(path): """Every code token in a file, with comments and string literals dropped.""" import io as _io import tokenize as _tokenize source = Path(path).read_text() for token in _tokenize.generate_tokens(_io.StringIO(source).readline): if token.type in (_tokenize.COMMENT, _tokenize.STRING, _tokenize.NL, _tokenize.NEWLINE): continue if token.string.strip(): yield token.string def package_python_files(exclude=()): excluded = {str(PACKAGE_ROOT / name) for name in exclude} return sorted( p for p in PACKAGE_ROOT.rglob("*.py") if "__pycache__" not in p.parts and str(p) not in excluded )