Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Enforce the interface's video resolutions in the API too (#8159)

Daniel Han56d410fe16be
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 4e5a9892898..20a75088305 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -95,6 +95,7 @@ from .video_families import (
snap_num_frames,
snap_video_size,
supported_video_family_names,
+ validate_video_request_shape,
)
from utils.hardware import clear_gpu_cache
@@ -1597,6 +1598,18 @@ class VideoBackend:
# ── generation ───────────────────────────────────────────────────────────
+ def loaded_family(self) -> Optional[VideoFamily]:
+ """The resident pipeline's family, or None when nothing is loaded.
+
+ The generate route reads it to enforce that family's shape rules (resolution
+ presets + frame lattice) at the API boundary, before the request reaches the
+ worker. ``getattr`` rather than ``state.family`` on purpose: a state object
+ that carries no family degrades to the old snapping path instead of raising.
+ """
+ with self._lock:
+ state = self._state
+ return getattr(state, "family", None) if state is not None else None
+
@staticmethod
def _reset_step_cache(pipe: Any) -> None:
"""Clear FBCache residuals on the resident DiT(s) before a generation.
@@ -1649,6 +1662,14 @@ class VideoBackend:
raise RuntimeError(VIDEO_NOT_LOADED_MSG)
if self._generate_job_active:
raise RuntimeError(VIDEO_GENERATION_BUSY_MSG)
+ # Under the SAME lock that reserves the state this job will run against. A load
+ # commits its new state here too, so judging the shape from a separate earlier read
+ # could accept a size for the family being replaced and then denoise it with the new
+ # one, or reject a size the new family supports. getattr, so a state carrying no
+ # family degrades to the old snapping rather than raising.
+ fam = getattr(self._state, "family", None)
+ if fam is not None:
+ validate_video_request_shape(fam, width = width, height = height, num_frames = num_frames)
self._generate_job_active = True
# Register BEFORE the worker starts so a cancel/unload in the spawn window still stops the run.
self._active_generate_cancel = cancel
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 07f3c990cb6..a6b709dc36b 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -21,6 +21,11 @@ import re
from dataclasses import dataclass, field
from typing import Optional
+# The request model's ceiling on num_frames, declared HERE so the shape gate and the bound cannot
+# drift: the gate's refusal names the lattice point above the request, and suggesting one the
+# request model would itself reject is a dead end. VideoGenerateRequest imports this for its `le`.
+MAX_VIDEO_NUM_FRAMES = 1024
+
# Runtime->route contract: routes match these EXACTLY for a 409 instead of a 500.
VIDEO_NOT_LOADED_MSG = "No video model is loaded."
VIDEO_CANCELLED_MSG = "Video generation was cancelled."
@@ -265,6 +270,81 @@ def snap_video_size(fam: VideoFamily, width: int, height: int) -> tuple[int, int
return snap(width), snap(height)
+def format_video_resolution_presets(fam: VideoFamily) -> str:
+ """The family's presets as '768x512, 1216x704, ...' for messages and logs."""
+ return ", ".join(f"{w}x{h}" for w, h in fam.resolution_presets)
+
+
+class VideoShapeError(ValueError):
+ """A shape this family cannot render. A ValueError subclass so the existing
+ ``except ValueError`` callers keep catching it, and a distinct type so the generate
+ route can answer 422 (the body is in range, the shape is not supported) without
+ widening the 400 it gives every other bad-input ValueError."""
+
+
+def validate_video_request_shape(
+ fam: VideoFamily,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ num_frames: Optional[int] = None,
+) -> None:
+ """Raise ``ValueError`` when a request asks for a shape ``fam`` does not support.
+
+ The generate route calls this at the API boundary so HTTP enforces exactly the
+ rules the Desktop interface offers: its resolution select lists only
+ ``resolution_presets`` and its duration select only lattice frame counts, while
+ the API took anything inside the coarse request bounds and then SNAPPED it. The
+ snap is silent and floors, so a 256x256 request survived untouched (256 divides
+ both 16 and 32) and denoised at a size no checkpoint was ever trained for.
+
+ This is a separate, explicit check rather than a change to ``snap_video_size`` /
+ ``snap_num_frames``, which internal callers still need. It stays silent for
+ anything it cannot judge -- a family that declares no presets keeps the old SIZE
+ snapping, since there is no table to judge a size against -- and ``None`` means
+ "use the family default", which is valid by construction. The frame lattice is
+ deliberately NOT part of that escape hatch: every family declares a ``frame_step``
+ whether or not it declares presets, so an off-lattice count is always refused.
+ """
+ # Normalised to int pairs so membership holds however a family spelled its presets (the status payload
+ # hands them out as lists, and a round-trip through it must not silently stop matching).
+ presets = tuple((int(w), int(h)) for w, h in fam.resolution_presets)
+ # No declared presets: no table to judge a SIZE against, so leave that to the snap (unusual/custom
+ # families). The frame check below still runs either way -- frame_step is always declared.
+ if presets and (width is not None or height is not None):
+ # Resolve a half-specified request against the default preset first, as generate() does, then judge the pair.
+ # Keyed on None, where generate() keys on falsiness: a 0 is judged as 0 here rather than
+ # replaced by the default. The route cannot deliver one (the request model bounds it at 32),
+ # and refusing an explicit 0 beats silently rendering something else, so the two agree on
+ # every value that can actually arrive.
+ want_w = presets[0][0] if width is None else int(width)
+ want_h = presets[0][1] if height is None else int(height)
+ if (want_w, want_h) not in presets:
+ raise VideoShapeError(
+ f"{want_w}x{want_h} is not a supported resolution for {fam.name}. "
+ f"Supported resolutions: {format_video_resolution_presets(fam)}."
+ )
+ if num_frames is not None:
+ step = max(1, fam.frame_step)
+ count = int(num_frames)
+ if count < 1 or (count - 1) % step != 0:
+ # The two lattice points straddling the request say more than a prefix of the lattice would, and stay short.
+ below = snap_num_frames(fam, count)
+ above = below + step
+ # ...but only name the upper one if the request model would accept it. Near the ceiling
+ # (1018-1024 on an 8-step family) it lands past `le`, and advising a count that answers
+ # with a second, differently-shaped 422 is worse than naming one that works.
+ nearest = (
+ f"the nearest supported counts are {below} and {above}"
+ if above <= MAX_VIDEO_NUM_FRAMES
+ else f"the nearest supported count is {below}"
+ )
+ raise VideoShapeError(
+ f"{count} is not a supported frame count for {fam.name}. Its VAE compresses time by "
+ f"{step}, so a frame count must be k * {step} + 1; {nearest} "
+ f"(the default is {fam.default_num_frames})."
+ )
+
+
# Default (steps, guidance) per checkpoint variant, matched by substring (picked id then base repo), most specific first.
_VIDEO_GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (
("distilled", 8, 1.0),
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 539494788e3..0310fff96af 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -19,6 +19,7 @@ from pydantic import (
)
from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN
+from core.inference.video_families import MAX_VIDEO_NUM_FRAMES
from picker.schemas import MAX_CHAT_TEMPLATE_BYTES
@@ -3194,18 +3195,28 @@ class VideoGenerateRequest(BaseModel):
negative_prompt: Optional[str] = Field(
None, description = "What to avoid (if the model supports it)"
)
- # Width/height/num_frames/fps default per loaded family (the backend snaps them to its lattice), so they are optional here.
+ # Width/height/num_frames/fps default per loaded family, so they are optional here. These bounds stay a COARSE outer
+ # guard only -- they are family-agnostic, and a request that clears them can still be one no checkpoint can render. The
+ # enforced rule is the LOADED family's own (its resolution presets and k * frame_step + 1 lattice), which the generate
+ # route checks with validate_video_request_shape and rejects with a 422 naming the supported shapes. Nothing tighter
+ # belongs here: with no model loaded there is no family to judge against, and that path must keep snapping as before.
width: Optional[int] = Field(
- None, ge = 32, le = 2048, description = "Frame width in pixels (family multiple)"
+ None,
+ ge = 32,
+ le = 2048,
+ description = "Frame width in pixels (a resolution preset of the loaded family)",
)
height: Optional[int] = Field(
- None, ge = 32, le = 2048, description = "Frame height in pixels (family multiple)"
+ None,
+ ge = 32,
+ le = 2048,
+ description = "Frame height in pixels (a resolution preset of the loaded family)",
)
num_frames: Optional[int] = Field(
None,
ge = 1,
- le = 1024,
- description = "Number of frames; snapped to the family's temporal lattice",
+ le = MAX_VIDEO_NUM_FRAMES,
+ description = "Number of frames; must lie on the family's temporal lattice (k * frame_step + 1)",
)
fps: Optional[int] = Field(
None, ge = 1, le = 120, description = "Playback frame rate (default per family)"
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 0bb0d65a118..f4db80d5725 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -211,9 +211,19 @@ async def generate_video(
generate + gallery-persist pipeline; the terminal outcome (completed with the
saved record / failed with a client-safe error) arrives via generate-progress."""
from core.inference.video import get_video_backend
- from core.inference.video_families import VIDEO_GENERATION_BUSY_MSG, VIDEO_NOT_LOADED_MSG
+ from core.inference.video_families import (
+ VIDEO_GENERATION_BUSY_MSG,
+ VIDEO_NOT_LOADED_MSG,
+ VideoShapeError,
+ )
backend = get_video_backend()
+ # The request bounds on VideoGenerateRequest are a coarse outer guard; the real rule is the LOADED
+ # family's (its presets and frame lattice), and begin_generate applies it under the same lock that
+ # reserves the state the job will run against, so a load committing concurrently cannot leave the
+ # shape judged against one family and denoised by another. Unloaded still falls through to the
+ # not-loaded 409; a family with no declared presets keeps the old SIZE snapping, though its frame
+ # lattice is enforced either way (frame_step is declared regardless).
try:
await asyncio.to_thread(
backend.begin_generate,
@@ -228,6 +238,10 @@ async def generate_video(
guidance_2 = request.guidance_2,
seed = request.seed,
)
+ except VideoShapeError as exc:
+ # 422 before the 400 below, and it must stay first: VideoShapeError IS a ValueError. The body
+ # parses and is in range, but the shape is not one this model can render.
+ raise HTTPException(status_code = 422, detail = str(exc))
except ValueError as exc:
# Bad client input -- a 400 with the reason, not a generic 500.
raise HTTPException(status_code = 400, detail = str(exc))
diff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.py
new file mode 100644
index 00000000000..3af3bdc24e3
--- /dev/null
+++ b/studio/backend/tests/test_video_shape_validation.py
@@ -0,0 +1,396 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The /video/generate shape gate: the API must enforce the rules the interface offers.
+
+The Desktop resolution select is populated from the loaded family's
+``resolution_presets`` and its duration select from that family's k*frame_step+1
+lattice, but the API accepted anything inside the coarse request bounds and then
+SNAPPED it silently. 256x256 is divisible by both 16 and 32, so it survived the
+snap untouched and denoised at a size no checkpoint was ever trained for. These
+tests pin the family-aware rejection (422) and, just as importantly, the
+fallbacks: nothing loaded, or a family declaring no presets, keeps snapping.
+
+The pure-function half needs no torch/GPU; the route half swaps in a fake
+backend that INHERITS the real begin_generate / job machinery, so the gate is
+exercised where it actually lives (the route, before the worker starts).
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from dataclasses import replace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import core.inference.video as video_module
+import core.inference.video_families as video_families_module
+import core.inference.video_gallery as gallery_module
+from auth.authentication import get_current_subject
+from core.inference.video_families import (
+ _FAMILIES,
+ MAX_VIDEO_NUM_FRAMES,
+ VIDEO_NOT_LOADED_MSG,
+ detect_video_family,
+ format_video_resolution_presets,
+ snap_num_frames,
+ snap_video_size,
+ validate_video_request_shape,
+)
+from routes.video import router as video_router
+
+# LTX-2 is the reference family for the single-family cases: 4 presets and frame_step 8.
+LTX2 = detect_video_family("Lightricks/LTX-2")
+# Wan is the contrast family: 704x1216 is an LTX-2 preset and is not one of Wan's.
+WAN_TI2V_5B = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers")
+
+
+# ── the validator itself ──────────────────────────────────────────────────────
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_every_declared_preset_is_accepted(fam):
+ """Whatever the interface can offer, the API must take: the resolution select
+ is built from exactly this tuple, so a rejection here is a dead UI control."""
+ for width, height in fam.resolution_presets:
+ validate_video_request_shape(
+ fam, width = width, height = height, num_frames = fam.default_num_frames
+ )
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_256x256_is_rejected_and_the_message_names_the_real_presets(fam):
+ """The QA report's case. 256 divides both 16 and 32, so the snap left it alone;
+ no family lists it, so every family must now refuse it by name."""
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(fam, width = 256, height = 256)
+ message = str(excinfo.value)
+ assert "256x256" in message
+ assert fam.name in message
+ # The message must quote sizes that actually exist, not a generic "unsupported".
+ for width, height in fam.resolution_presets:
+ assert f"{width}x{height}" in message
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_the_default_frame_count_is_on_its_own_lattice(fam):
+ validate_video_request_shape(fam, num_frames = fam.default_num_frames)
+
+
+def test_off_lattice_frame_count_is_rejected_with_the_straddling_counts():
+ # 100 sits between 97 (12*8+1) and 105 on LTX-2's step-8 lattice.
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(LTX2, num_frames = 100)
+ message = str(excinfo.value)
+ assert "97" in message and "105" in message
+ assert str(LTX2.default_num_frames) in message
+ # On-lattice neighbours of the same request are fine.
+ validate_video_request_shape(LTX2, num_frames = 97)
+ validate_video_request_shape(LTX2, num_frames = 105)
+
+
+def test_the_refusal_never_suggests_a_count_past_the_request_ceiling():
+ """Near the top of the range the upper straddling point falls outside the request
+ model's own `le`, so naming it sends the user into a second, differently-shaped 422.
+ On LTX-2's step-8 lattice the whole band 1018-1024 is affected (1017 + 8 = 1025)."""
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(LTX2, num_frames = 1024)
+ message = str(excinfo.value)
+ assert "1017" in message
+ assert "1025" not in message
+ assert "the nearest supported count is" in message
+ # The ceiling itself is on no family's lattice, but the point below it is loadable.
+ validate_video_request_shape(LTX2, num_frames = 1017)
+ # Away from the ceiling both points are still named.
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(LTX2, num_frames = 100)
+ assert "the nearest supported counts are" in str(excinfo.value)
+
+
+def test_the_request_ceiling_and_the_gate_share_one_constant():
+ """A drifted pair would silently reintroduce the dead-end suggestion above."""
+ from models.inference import VideoGenerateRequest
+
+ field = VideoGenerateRequest.model_fields["num_frames"]
+ ceiling = next(m.le for m in field.metadata if hasattr(m, "le"))
+ assert ceiling == MAX_VIDEO_NUM_FRAMES
+
+
+def test_wan_lattice_is_step_4_not_step_8():
+ """Per-family, not one hardcoded rule: 85 is valid on Wan's 4k+1 and invalid on LTX-2's 8k+1."""
+ wan = detect_video_family("Wan-AI/Wan2.2-T2V-A14B-Diffusers")
+ validate_video_request_shape(wan, num_frames = 85)
+ with pytest.raises(ValueError):
+ validate_video_request_shape(LTX2, num_frames = 85)
+
+
+def test_omitted_fields_are_always_valid():
+ """None means "use the family default", which is valid by construction."""
+ validate_video_request_shape(LTX2)
+ validate_video_request_shape(LTX2, num_frames = None)
+
+
+def test_a_half_specified_size_resolves_against_the_default_preset():
+ """generate() fills a missing side from presets[0], so the check must judge the
+ same pair it will actually denoise."""
+ # 768 alone resolves to 768x512, the default preset.
+ validate_video_request_shape(LTX2, width = 768)
+ validate_video_request_shape(LTX2, height = 512)
+ # 1216 alone resolves to 1216x512, which is NOT a preset (1216 only pairs with 704).
+ with pytest.raises(ValueError) as excinfo:
+ validate_video_request_shape(LTX2, width = 1216)
+ assert "1216x512" in str(excinfo.value)
+
+
+def test_presets_spelled_as_lists_still_match():
+ """The status payload hands presets out as lists; a round-trip back in must not
+ silently stop matching and start 422-ing every supported size."""
+ fam = replace(LTX2, resolution_presets = tuple([w, h] for w, h in LTX2.resolution_presets))
+ for width, height in LTX2.resolution_presets:
+ validate_video_request_shape(fam, width = width, height = height)
+
+
+def test_a_family_with_no_presets_is_left_to_the_snap():
+ """Backwards compatibility for an unusual/custom family: nothing to enforce
+ against, so the old silent snap stays in charge rather than a blanket 422."""
+ fam = replace(LTX2, resolution_presets = ())
+ validate_video_request_shape(fam, width = 256, height = 256)
+ # The frame lattice is intrinsic to the VAE, so it is still enforced.
+ with pytest.raises(ValueError):
+ validate_video_request_shape(fam, num_frames = 100)
+
+
+def test_snapping_helpers_are_untouched():
+ """The validator is additive: internal callers still get the flooring snap."""
+ assert snap_video_size(LTX2, 250, 250) == (224, 224)
+ assert snap_num_frames(LTX2, 100) == 97
+ assert format_video_resolution_presets(LTX2) == "768x512, 1216x704, 704x1216, 512x768"
+
+
+# ── the route ─────────────────────────────────────────────────────────────────
+
+
+class _ShapeFakeBackend(video_module.VideoBackend):
+ """Real load state + real begin_generate/job machinery over a stub generate().
+
+ ``_state`` is a genuine ``_VideoLoadState`` so ``loaded_family()`` is exercised
+ against the object the loader really commits, and generate() mirrors the real
+ one's shape resolution (snap + family defaults) so a test can see whether a
+ request was snapped or rejected.
+ """
+
+ def load_as(self, fam) -> None:
+ self._state = video_module._VideoLoadState(
+ pipe = object(),
+ family = fam,
+ repo_id = f"unsloth/{fam.name}",
+ base_repo = fam.base_repo,
+ device = "cpu",
+ dtype = "bfloat16",
+ kind = "pipeline",
+ )
+
+ def generate(
+ self,
+ *,
+ prompt,
+ seed = None,
+ cancel_event = None,
+ **kwargs,
+ ):
+ state = self._state
+ if state is None:
+ raise RuntimeError(VIDEO_NOT_LOADED_MSG)
+ fam = state.family
+ default = fam.resolution_presets[0] if fam.resolution_presets else (768, 512)
+ width, height = snap_video_size(
+ fam, kwargs.get("width") or default[0], kwargs.get("height") or default[1]
+ )
+ frames = snap_num_frames(fam, kwargs.get("num_frames") or fam.default_num_frames)
+ fps = int(kwargs.get("fps") or fam.default_fps)
+ return {
+ "mp4_bytes": b"MP4-FAKE-BYTES",
+ "seed": 4242 if seed is None else seed,
+ "repo_id": state.repo_id,
+ "width": width,
+ "height": height,
+ "num_frames": frames,
+ "fps": fps,
+ "duration_s": frames / fps,
+ "has_audio": fam.has_audio,
+ "steps": int(kwargs.get("steps") or fam.default_steps),
+ "guidance": fam.default_guidance,
+ }
+
+
+def backend(monkeypatch):
+ fake = _ShapeFakeBackend()
+ monkeypatch.setattr(video_module, "get_video_backend", lambda: fake)
+ return fake
+
+
+def client(backend, monkeypatch, tmp_path):
+ # A real tmp gallery so the completed path runs the actual persist code.
+ monkeypatch.setattr(gallery_module, "gallery_dir", lambda: tmp_path)
+ app = FastAPI()
+ app.include_router(video_router, prefix = "/api/inference")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app)
+
+
+def _payload(**overrides) -> dict:
+ return {"prompt": "a cat", **overrides}
+
+
+def _wait_terminal(client, timeout = 5.0) -> dict:
+ """Generation is asynchronous (the POST only starts the job), so the outcome is
+ only observable by polling generate-progress."""
+ deadline = time.monotonic() + timeout
+ progress: dict = {}
+ while time.monotonic() < deadline:
+ progress = client.get("/api/inference/video/generate-progress").json()
+ if progress.get("phase") in ("completed", "failed"):
+ return progress
+ time.sleep(0.01)
+ raise AssertionError(f"generation never reached a terminal state: {progress}")
+
+
+def test_generate_rejects_256x256_with_422_naming_the_presets(client, backend):
+ """The QA report end to end: the request is in range and parses, but the loaded
+ model cannot render it, so it is refused instead of silently denoised."""
+ backend.load_as(LTX2)
+ resp = client.post("/api/inference/video/generate", json = _payload(width = 256, height = 256))
+ assert resp.status_code == 422, resp.text
+ detail = resp.json()["detail"]
+ assert "256x256" in detail
+ assert "768x512" in detail and "1216x704" in detail
+ # Rejected AT THE BOUNDARY: no job was started, so the backend is still idle.
+ progress = client.get("/api/inference/video/generate-progress").json()
+ assert progress["active"] is False and progress.get("phase") is None
+
+
[email protected]("fam", _FAMILIES, ids = lambda f: f.name)
+def test_generate_accepts_every_declared_preset_of_the_loaded_family(client, backend, fam):
+ """Every size the interface can offer for this family round-trips to a saved clip."""
+ backend.load_as(fam)
+ for width, height in fam.resolution_presets:
+ resp = client.post(
+ "/api/inference/video/generate",
+ json = _payload(width = width, height = height, num_frames = fam.default_num_frames),
+ )
+ assert resp.status_code == 200, (fam.name, width, height, resp.text)
+ record = _wait_terminal(client)["video"]
+ assert (record["width"], record["height"]) == (width, height)
+
+
+def test_generate_rejects_an_off_lattice_frame_count_with_422(client, backend):
+ backend.load_as(LTX2)
+ resp = client.post("/api/inference/video/generate", json = _payload(num_frames = 100))
+ assert resp.status_code == 422, resp.text
+ detail = resp.json()["detail"]
+ assert "97" in detail and "105" in detail
+
+
+def test_generate_with_nothing_loaded_still_reports_not_loaded_not_a_shape_error(client):
+ """The gate must not preempt the 409: with no model there is no family whose
+ rules could be applied, so the request falls through exactly as before."""
+ resp = client.post("/api/inference/video/generate", json = _payload(width = 256, height = 256))
+ assert resp.status_code == 409
+ assert resp.json()["detail"] == VIDEO_NOT_LOADED_MSG
+
+
+def test_generate_for_a_family_without_presets_still_snaps(client, backend):
+ """Backwards compatibility: an odd size against a family that declares no presets
+ is accepted and floored to the family multiple, the pre-change behaviour."""
+ backend.load_as(replace(LTX2, resolution_presets = ()))
+ resp = client.post("/api/inference/video/generate", json = _payload(width = 250, height = 250))
+ assert resp.status_code == 200, resp.text
+ record = _wait_terminal(client)["video"]
+ # 250 floored to LTX-2's /32 multiple, as snap_video_size has always done.
+ assert (record["width"], record["height"]) == (224, 224)
+
+
+def test_a_family_without_presets_still_enforces_its_frame_lattice(client, backend):
+ """The preset escape hatch covers the SIZE only. frame_step is declared whether or
+ not a family lists presets, so an off-lattice count is still a 422 here -- pinned at
+ the route because the size and frame branches take different paths through the gate."""
+ backend.load_as(replace(LTX2, resolution_presets = ()))
+ resp = client.post("/api/inference/video/generate", json = _payload(num_frames = 100))
+ assert resp.status_code == 422, resp.text
+ assert "97" in resp.json()["detail"] and "105" in resp.json()["detail"]
+ # And an on-lattice count against the same preset-less family still runs.
+ assert (
+ client.post("/api/inference/video/generate", json = _payload(num_frames = 97)).status_code
+ == 200
+ )
+
+
+def test_generate_omitting_the_shape_uses_the_family_defaults(client, backend):
+ """The common API call sends no size at all; it must not be caught by the gate."""
+ backend.load_as(LTX2)
+ resp = client.post("/api/inference/video/generate", json = _payload())
+ assert resp.status_code == 200, resp.text
+ record = _wait_terminal(client)["video"]
+ assert (record["width"], record["height"]) == LTX2.resolution_presets[0]
+ assert record["num_frames"] == LTX2.default_num_frames
+
+
+def test_the_coarse_pydantic_bounds_still_reject_out_of_range_sizes(client, backend):
+ """The outer guard is unchanged: family-agnostic nonsense is still a 422 from the
+ request model, before any family is consulted."""
+ backend.load_as(LTX2)
+ for body in (_payload(width = 16), _payload(height = 4096), _payload(num_frames = 0)):
+ assert client.post("/api/inference/video/generate", json = body).status_code == 422
+
+
+# ── the check has to be atomic with the state it judges ───────────────────────
+
+
+def test_the_shape_is_judged_under_the_lock_that_reserves_the_state(backend, monkeypatch):
+ """A load commits its new ``_state`` under the same lock ``begin_generate`` takes. Reading
+ the family separately, before that lock, leaves a window where a size is accepted for the
+ family being replaced and then denoised by the new one -- or a size the new family supports
+ is rejected. Proven directly: while the validator runs, the lock is unavailable to anyone
+ else, so no load can be committing.
+ """
+ backend.load_as(LTX2)
+ held: list[bool] = []
+ real = video_families_module.validate_video_request_shape
+
+ def _spy(*args, **kwargs):
+ # Another thread, because a Lock says nothing about which thread owns it and this call
+ # runs on the one that took it.
+ probe: list[bool] = []
+ watcher = threading.Thread(target = lambda: probe.append(backend._lock.acquire(False)))
+ watcher.start()
+ watcher.join(5)
+ if probe and probe[0]:
+ backend._lock.release()
+ held.append(not (probe and probe[0]))
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(video_module, "validate_video_request_shape", _spy)
+ backend.begin_generate(prompt = "a cat", width = 768, height = 512)
+
+ assert held == [True], "the shape was judged outside the lock that owns the state"
+
+
+def test_a_family_swap_cannot_slip_between_the_check_and_the_job(backend):
+ """The consequence, end to end rather than by construction. 704x1216 is a real LTX-2 preset
+ and is not one of Wan's, so whichever family is resident when the lock is taken decides the
+ outcome -- and the job that runs afterwards is the one that was judged."""
+ backend.load_as(LTX2)
+ backend.begin_generate(prompt = "a cat", width = 704, height = 1216) # accepted for LTX-2
+ backend.cancel_generate()
+ # The worker clears the slot asynchronously and this test is about the check, not the job.
+ backend._generate_job_active = False
+
+ backend.load_as(WAN_TI2V_5B)
+ with pytest.raises(ValueError):
+ backend.begin_generate(prompt = "a cat", width = 704, height = 1216)
+ assert not backend._generate_job_active, "a refused shape must not reserve the job slot"
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index b015441aff4..0eba907b8be 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -112,7 +112,9 @@ export interface VideoLoadRequest {
export interface VideoGenerateRequest {
prompt: string;
negative_prompt?: string;
- // Width/height/num_frames/fps default per loaded family (the backend snaps them to its lattice), so they are optional.
+ // Width/height/num_frames/fps default per loaded family, so they are optional. When sent they must match that family's
+ // rules -- width/height one of status.defaults.resolution_presets, num_frames on the k*frame_step+1 lattice -- or the
+ // backend answers 422 with the supported shapes (the same rules the video page's selects are built from).
width?: number;
height?: number;
num_frames?: number;