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.

Studio: stop the desktop watchdog killing a backend that is rendering a clip (#9627)

oobaboogaeba38dc59dc6
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index ccf2201e40b..e537c508cda 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -6829,3 +6829,9 @@ def get_diffusion_backend() -> DiffusionBackend:
if _diffusion_backend is None:
_diffusion_backend = DiffusionBackend()
return _diffusion_backend
+
+
+def generation_in_flight() -> bool:
+ """Read the active-generation marker without constructing or locking the backend."""
+ backend = _diffusion_backend
+ return backend is not None and backend._gen is not None
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 15e92453d0b..f4efd9ba423 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -2791,3 +2791,9 @@ def get_sd_cpp_backend() -> SdCppDiffusionBackend:
if _sd_cpp_backend is None:
_sd_cpp_backend = SdCppDiffusionBackend()
return _sd_cpp_backend
+
+
+def generation_in_flight() -> bool:
+ """Read the active-generation marker without constructing or locking the backend."""
+ backend = _sd_cpp_backend
+ return backend is not None and backend._gen is not None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index ad46d3f860a..b40563e6c91 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -31,6 +31,7 @@ family's official base repos, or a local path the user explicitly picked.
from __future__ import annotations
import contextlib
+import functools
import inspect
import os
import tempfile
@@ -1053,6 +1054,9 @@ class VideoBackend:
self._gen: dict[str, Any] = {"active": False}
# True from begin_generate() until its worker records a terminal state, so a second call is refused while it runs.
self._generate_job_active = False
+ # Which job the flag belongs to. The flag alone cannot tell "my job" from "the job that
+ # replaced mine", so finalising is keyed on this. Compared by identity.
+ self._generate_job_token: Optional[object] = None
def _device_target(self, ordinal: Optional[int] = None) -> DiffusionDeviceTarget:
"""The device target for ``ordinal``, pinned onto the calling thread.
@@ -4986,6 +4990,7 @@ class VideoBackend:
sentinels the route maps to 409.
"""
cancel = threading.Event()
+ job_token = object() # this reservation's identity; only its own worker may finalise it
while True:
# Resolve outside the lock, then retry if the resident state changed.
with self._lock:
@@ -5033,6 +5038,7 @@ class VideoBackend:
state.family, width = width, height = height, num_frames = num_frames
)
self._generate_job_active = True
+ self._generate_job_token = job_token
# Register before the worker starts so cancellation covers the spawn window.
self._active_generate_cancel = cancel
self._gen = {
@@ -5043,8 +5049,10 @@ class VideoBackend:
"eta_seconds": None,
}
break
- threading.Thread(
- target = self._run_generate,
+ worker = threading.Thread(
+ # The token rides on the target rather than in kwargs: those kwargs are also a
+ # valid generate() call, and callers replay them as one.
+ target = functools.partial(self._run_generate, job_token = job_token),
kwargs = dict(
prompt = prompt,
negative_prompt = negative_prompt,
@@ -5060,9 +5068,59 @@ class VideoBackend:
cancel_event = cancel,
),
daemon = True,
- ).start()
+ )
+ try:
+ worker.start()
+ except RuntimeError:
+ # No thread, so nothing would ever release the slot reserved above: generate stays
+ # refused for the session, and liveness reports a rendering backend to a watchdog
+ # that answers busy by waiting longer rather than restarting.
+ # RuntimeError, not BaseException: start() raises it only before the thread exists,
+ # but it then waits on the child, and a signal in that wait unwinds with the worker
+ # live. Rolling back there would retire a running render's token and drop its cancel
+ # handle. A worker that exists finalises its own reservation.
+ self._finish_generate_job(
+ job_token = job_token,
+ cancel_event = cancel,
+ error = "Video generation could not start.",
+ )
+ raise
+
+ def _run_generate(
+ self,
+ *,
+ cancel_event: threading.Event,
+ job_token: Optional[object] = None,
+ **gen_kwargs: Any,
+ ) -> None:
+ """Backstop around the worker body, so a reservation cannot outlive its thread.
+
+ The body names every ordinary outcome and finalises it; keyed on job_token, this
+ finally is then a no-op. It is for what the body cannot name: an exit through
+ BaseException, or a failure before its first try. A leaked marker tells the watchdog a
+ wedged backend is still rendering, the inverse of the bug the marker fixes.
+
+ Still the thread target: begin_generate resolves it by name and doubles subclass it."""
+ try:
+ self._run_generate_body(cancel_event = cancel_event, job_token = job_token, **gen_kwargs)
+ finally:
+ if job_token is not None:
+ # Only begin_generate makes a reservation, so only it can leave one dangling.
+ # Firing for a direct call would match the same unreserved token the body just
+ # finalised with, replacing its outcome with the generic failure below.
+ self._finish_generate_job(
+ job_token = job_token,
+ cancel_event = cancel_event,
+ error = "Video generation failed.",
+ )
- def _run_generate(self, *, cancel_event: threading.Event, **gen_kwargs: Any) -> None:
+ def _run_generate_body(
+ self,
+ *,
+ cancel_event: threading.Event,
+ job_token: Optional[object] = None,
+ **gen_kwargs: Any,
+ ) -> None:
"""begin_generate's worker: generate, persist to the gallery, record the
terminal state where generate_progress() reports it. The error mapping is
the exact one the route applied when the call was synchronous: ValueError
@@ -5074,18 +5132,24 @@ class VideoBackend:
try:
result = self.generate(cancel_event = cancel_event, **gen_kwargs)
except ValueError as exc:
- self._finish_generate_job(cancel_event = cancel_event, error = str(exc))
+ self._finish_generate_job(
+ job_token = job_token, cancel_event = cancel_event, error = str(exc)
+ )
return
except RuntimeError as exc:
msg = str(exc)
if msg not in (VIDEO_NOT_LOADED_MSG, VIDEO_CANCELLED_MSG):
logger.error("video.generate_failed: %s", exc, exc_info = True)
msg = "Video generation failed."
- self._finish_generate_job(cancel_event = cancel_event, error = msg)
+ self._finish_generate_job(job_token = job_token, cancel_event = cancel_event, error = msg)
return
except Exception as exc: # noqa: BLE001 -- worker thread: never propagate
logger.error("video.generate_failed: %s", exc, exc_info = True)
- self._finish_generate_job(cancel_event = cancel_event, error = "Video generation failed.")
+ self._finish_generate_job(
+ job_token = job_token,
+ cancel_event = cancel_event,
+ error = "Video generation failed.",
+ )
return
# Persist the clip with its full recipe as the JSON sidecar the gallery reads back.
@@ -5129,14 +5193,22 @@ class VideoBackend:
except Exception as exc: # noqa: BLE001 -- disk failure must reach the poller
logger.error("video.persist_failed: %s", exc)
self._finish_generate_job(
- cancel_event = cancel_event, error = "Failed to save the generated video."
+ job_token = job_token,
+ cancel_event = cancel_event,
+ error = "Failed to save the generated video.",
)
return
- self._finish_generate_job(cancel_event = cancel_event, video = record, total = result["steps"])
+ self._finish_generate_job(
+ job_token = job_token,
+ cancel_event = cancel_event,
+ video = record,
+ total = result["steps"],
+ )
def _finish_generate_job(
self,
*,
+ job_token: Optional[object] = None,
cancel_event: Optional[threading.Event] = None,
video: Optional[dict] = None,
error: Optional[str] = None,
@@ -5145,8 +5217,18 @@ class VideoBackend:
"""Record a job's terminal state as one atomic swap. The terminal dict
replaces the live-progress one so a poll can never mix fields from both,
and the busy flag drops in the same critical section so the earliest
- moment a new begin_generate() can start is after the outcome is visible."""
+ moment a new begin_generate() can start is after the outcome is visible.
+
+ At most once per reservation and only by that reservation: the first call carrying the
+ live token publishes and retires it, later ones return. Keyed on the token, not on
+ _generate_job_active, because the flag goes true again the moment the next job reserves
+ and the backstop runs after the body published - on the flag a finished job would
+ finalise its successor. None means a caller that never reserved, e.g. direct
+ _run_generate()."""
with self._lock:
+ if self._generate_job_token is not job_token:
+ return
+ self._generate_job_token = None
self._generate_job_active = False
if cancel_event is not None and self._active_generate_cancel is cancel_event:
# Covers a worker that failed before reaching generate()'s finally; identity-guarded so a direct generate() keeps its handle.
@@ -6183,3 +6265,9 @@ def get_video_backend() -> VideoBackend:
if _backend is None:
_backend = VideoBackend()
return _backend
+
+
+def generation_in_flight() -> bool:
+ """Read the background-job marker without constructing or locking the backend."""
+ backend = _backend
+ return backend is not None and bool(backend._generate_job_active)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 84fa25166a7..c21165cefe5 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1589,6 +1589,30 @@ def _torch_warm_in_progress() -> bool:
return bool(status["started"] and not status["finished"] and status["alive"])
+# Modules that expose generation_in_flight(). The three engines answer for the render itself;
+# routes.inference answers for the image-persist tail, which outlives the engine's own marker.
+_MEDIA_BACKEND_MODULES = (
+ "core.inference.video",
+ "core.inference.diffusion",
+ "core.inference.sd_cpp_backend",
+ "routes.inference",
+)
+
+
+def _media_generation_active() -> bool:
+ """Check imported media backends without importing, constructing, or locking them."""
+ for module_name in _MEDIA_BACKEND_MODULES:
+ module = sys.modules.get(module_name)
+ if module is None:
+ continue
+ try:
+ if module.generation_in_flight():
+ return True
+ except Exception:
+ continue
+ return False
+
+
def _inference_active() -> bool:
"""True while at least one generation is in flight.
@@ -1596,14 +1620,17 @@ def _inference_active() -> bool:
one that has died: a saturated host can stall the event loop past a probe budget, and
killing there ends a response the user is still waiting on.
- A len() under a threading.Lock held only for that read, so the route stays cheap.
- Failures report "not busy", the same answer as before this field existed.
+ A len() under a threading.Lock held only for that read, plus a bool off each resident
+ media backend, so the route stays cheap. Failures report "not busy", the same answer as
+ before this field existed.
"""
try:
from state import active_generations
- return active_generations.count() > 0
+ if active_generations.count() > 0:
+ return True
except Exception:
- return False
+ pass
+ return _media_generation_active()
@app.get("/api/liveness")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index cf89d2c57ac..375b8190822 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -26644,6 +26644,17 @@ async def load_diffusion_model_gated(
_diffusion_persist_active = 0
+def generation_in_flight() -> bool:
+ """Read the image-persist marker without importing or locking anything.
+
+ An image job is not done when the engine's own marker clears: the route is still writing
+ the gallery records the response is built from. generate-progress already treats that
+ window as active; liveness has to agree, or the watchdog sees an idle backend and spends
+ its short budget on a request that is still running.
+ """
+ return _diffusion_persist_active > 0
+
+
_GENERATE_FAILURE_FALLBACK = "Image generation failed."
# Failure classes worth naming in the UI, as FIXED text: the engine's own message can embed local paths and argv, so only the class is reported.
_GENERATE_FAILURE_CLASSES: tuple[tuple[tuple[str, ...], str], ...] = (
@@ -27419,10 +27430,16 @@ async def _generate_openai_images(
items.append(ImageGenerationData(url = _absolute_image_url(request, record["id"])))
return items
+ # Same counter as /images/generate: the request is still in flight until these records
+ # exist, and liveness reads the counter to say so.
+ global _diffusion_persist_active
+ _diffusion_persist_active += 1
try:
data = await asyncio.to_thread(_persist)
except Exception as exc: # noqa: BLE001
logger.error("openai_images.persist_failed: %s", exc)
raise HTTPException(status_code = 500, detail = "Failed to save the generated image.")
+ finally:
+ _diffusion_persist_active -= 1
return ImageGenerationResponse(created = created, data = data)
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index a234f67fc87..3f3916a8793 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -10431,3 +10431,44 @@ def test_an_unsupported_host_is_not_told_its_shards_are_unstaged(
)
reason3 = ((status3.get("resolved") or {}).get("transformer_quant") or {}).get("reason") or ""
assert "shards are not staged" in reason3, reason3
+
+
+def test_generation_in_flight_tracks_a_generation(fake_runtime, tmp_path, monkeypatch):
+ import core.inference.diffusion as diffusion_mod
+
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend = DiffusionBackend()
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "base/repo",
+ family_override = "z-image",
+ )
+ monkeypatch.setattr(diffusion_mod, "_diffusion_backend", backend)
+
+ seen = {}
+
+ def fake_apply(self, state, loras, cancel):
+ # Check the marker during pre-denoise setup.
+ seen["in_flight"] = diffusion_mod.generation_in_flight()
+
+ monkeypatch.setattr(DiffusionBackend, "_apply_loras", fake_apply)
+
+ assert diffusion_mod.generation_in_flight() is False
+ backend.generate(prompt = "a sloth", steps = 4)
+ assert (
+ seen["in_flight"] is True
+ ), "liveness cannot tell this backend from a dead one while it renders an image"
+ assert diffusion_mod.generation_in_flight() is False
+
+
+def test_generation_in_flight_never_builds_a_backend(fake_runtime, monkeypatch):
+ import core.inference.diffusion as diffusion_mod
+
+ monkeypatch.setattr(diffusion_mod, "_diffusion_backend", None)
+ monkeypatch.setattr(
+ diffusion_mod,
+ "DiffusionBackend",
+ lambda *a, **k: pytest.fail("liveness constructed a diffusion backend"),
+ )
+ assert diffusion_mod.generation_in_flight() is False
diff --git a/studio/backend/tests/test_liveness_reports_inference_active.py b/studio/backend/tests/test_liveness_reports_inference_active.py
index 4fc71fb0dca..0088ff05448 100644
--- a/studio/backend/tests/test_liveness_reports_inference_active.py
+++ b/studio/backend/tests/test_liveness_reports_inference_active.py
@@ -14,8 +14,12 @@ So liveness carries an `inference_active` marker and the watchdog widens its fai
while the last answered probe was generating. Only for probes that time out: a refused
connection means the port is gone, and that is still reported at three strikes.
+Media jobs do not enter `active_generations`, so the marker also checks video and both
+image engines.
+
The marker must not cost what health costs: it is a len() under a lock already held for
-microseconds, never a wait on the generations themselves.
+microseconds plus a bool off each resident media backend, never a wait on the work itself
+and never an import of the ML stack.
CPU-only, no network, no GPU, no weights.
"""
@@ -32,7 +36,11 @@ _COMMANDS_RS = _BACKEND_DIR.parent / "src-tauri" / "src" / "commands.rs"
_SNIPPET = r"""
-import json, os, threading, time
+import json, os, sys, threading, time, types
+
+
+def _raise():
+ raise RuntimeError("backend module is mid-teardown")
# Keep the real warm out of the way: it would import the ML stack, and this file is about
# the busy marker, not the warm one.
@@ -77,10 +85,41 @@ with active_generations.ActiveGeneration(threading.Event(), thread_id = "t1", ki
busy = probe()
idle_after = probe()
+# Keep this independent of main._MEDIA_BACKEND_MODULES so omissions are detected.
+media_modules = (
+ "core.inference.video",
+ "core.inference.diffusion",
+ "core.inference.sd_cpp_backend",
+ "routes.inference",
+)
+# routes.inference is imported at startup regardless, so the ML-stack question is only
+# about the three engines.
+media_import_free = [
+ name for name in media_modules if name.startswith("core.") and name in sys.modules
+]
+scanned = list(getattr(main, "_MEDIA_BACKEND_MODULES", ()) or ())
+
+probes = {"idle_before": idle_before, "busy": busy, "idle_after": idle_after}
+for name in media_modules:
+ short = name.rsplit(".", 1)[-1]
+ module = types.ModuleType(name)
+ module.generation_in_flight = lambda: False
+ sys.modules[name] = module
+ probes[short + "_idle"] = probe()
+ module.generation_in_flight = lambda: True
+ probes[short + "_rendering"] = probe()
+ module.generation_in_flight = lambda: False
+ probes[short + "_done"] = probe()
+
+# Backend probe failures must not fail liveness.
+sys.modules["core.inference.video"].generation_in_flight = _raise
+probes["broken"] = probe()
+
print("RESULT" + json.dumps({
- "idle_before": idle_before,
- "busy": busy,
- "idle_after": idle_after,
+ "probes": probes,
+ "media_import_free": media_import_free,
+ "media_modules": list(media_modules),
+ "scanned": scanned,
}))
"""
@@ -103,7 +142,7 @@ def _probe() -> dict:
def test_liveness_reports_a_generation_in_flight():
"""The regression: nothing in the reply distinguished a backend stalled under four
concurrent generations from one that had exited, so the watchdog killed both."""
- result = _probe()
+ result = _probe()["probes"]
assert result["busy"]["status_code"] == 200
assert result["busy"]["status"] == "alive"
@@ -118,7 +157,7 @@ def test_the_marker_disappears_once_nothing_is_generating():
"""The wide budget is for a backend that is producing tokens. Leaving the marker lit
after the last stream ends would arm it for the rest of the session, and a genuinely
hung backend would sit unreported."""
- result = _probe()
+ result = _probe()["probes"]
assert not result["idle_before"][
"has_busy_key"
@@ -132,7 +171,7 @@ def test_the_marker_disappears_once_nothing_is_generating():
def test_the_marker_costs_nothing_to_read():
"""A probe every 15s cannot pay for anything that waits, which is why the route reads
a registry len() rather than asking the backend what it is doing."""
- result = _probe()
+ result = _probe()["probes"]
for state, sample in result.items():
assert sample["elapsed"] < 0.5, (
@@ -163,3 +202,81 @@ def test_the_desktop_watchdog_still_reads_the_marker():
"the budget is no longer chosen in one place; the busy case and the dead-port "
"case have to stay distinguishable"
)
+
+
+def test_liveness_reports_a_media_job_in_flight():
+ """Media jobs publish the same busy marker as chat generation."""
+ result = _probe()["probes"]
+
+ for backend in ("video", "diffusion", "sd_cpp_backend"):
+ assert result[f"{backend}_rendering"]["inference_active"] is True, (
+ f"liveness does not say the backend is busy while {backend} renders; the "
+ f"watchdog kills the job at three missed probes and reports the app as crashed"
+ )
+ assert not result[f"{backend}_idle"]["has_busy_key"], f"{backend} reported busy while idle"
+ assert not result[f"{backend}_done"]["has_busy_key"], (
+ f"{backend} still reports busy after the job ended; the widened budget would "
+ f"stay armed for the rest of the session"
+ )
+
+
+def test_the_probe_does_not_import_the_media_backends():
+ """The liveness check must not import media backends."""
+ result = _probe()
+
+ assert result["media_import_free"] == [], (
+ f"/api/liveness imported {result['media_import_free']} to answer; the marker must "
+ f"read backends that already exist and say 'not busy' for the rest"
+ )
+
+
+def test_a_broken_media_backend_still_answers_the_probe():
+ """A backend probe failure must not fail liveness."""
+ result = _probe()["probes"]
+
+ assert result["broken"]["status_code"] == 200
+ assert result["broken"]["status"] == "alive"
+
+
+def test_every_media_backend_is_scanned():
+ """Every supported media backend must be scanned."""
+ result = _probe()
+
+ assert result["scanned"] == result["media_modules"], (
+ f"/api/liveness scans {result['scanned']}, this file exercises "
+ f"{result['media_modules']}; a media backend in neither list renders invisibly"
+ )
+
+
+def test_liveness_covers_the_image_persist_tail():
+ """An image job is not over when the engine's marker clears: the route is still writing
+ the gallery records the response is built from, and on a saturated host that write is
+ exactly when probes start missing. generate-progress already calls that window active
+ (routes/inference.py diffusion_generate_progress); liveness disagreeing with it is how a
+ request that is still running gets the idle three-strike budget."""
+ import importlib
+
+ routes_inference = importlib.import_module("routes.inference")
+ assert routes_inference.generation_in_flight() is False
+
+ routes_inference._diffusion_persist_active += 1
+ try:
+ assert routes_inference.generation_in_flight() is True
+ finally:
+ routes_inference._diffusion_persist_active -= 1
+ assert routes_inference.generation_in_flight() is False
+
+
+def test_both_image_routes_publish_the_persist_marker():
+ """The Studio route and the OpenAI-compatible one write the gallery on separate paths.
+ Only the first used to count, so an OpenAI client's persist was invisible to both
+ generate-progress and liveness."""
+ import inspect
+ import importlib
+
+ source = inspect.getsource(importlib.import_module("routes.inference"))
+ assert source.count("_diffusion_persist_active += 1") == 2, (
+ "an image route persists gallery records without publishing the marker, so liveness "
+ "reports idle while that request is still in flight"
+ )
+ assert source.count("_diffusion_persist_active -= 1") == 2
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 413e5d30bfd..49f799d693f 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -2432,3 +2432,44 @@ def test_an_unresolvable_device_pin_says_so_and_still_loads(tmp_path, capsys):
# No selection is not an unresolved one, so it says nothing.
assert bk.sd_cpp_device_name_for_ordinal(str(binary), None) is None
assert "device_pin_unresolved" not in capsys.readouterr().out
+
+
+def test_generation_in_flight_tracks_a_generation(monkeypatch):
+ from core.inference import diffusion_lora
+
+ eng = _FakeEngine()
+ b = _loaded_backend(engine = eng)
+ monkeypatch.setattr(bk, "_sd_cpp_backend", b)
+ monkeypatch.setattr(diffusion_lora, "supports_lora", lambda **_k: True)
+
+ seen: dict = {}
+
+ def _resolve(
+ active,
+ *,
+ family = None,
+ hf_token = None,
+ cancel_event = None,
+ ):
+ # Check the marker during pre-generate setup.
+ seen["in_flight"] = bk.generation_in_flight()
+ return []
+
+ monkeypatch.setattr(diffusion_lora, "resolve_specs", _resolve)
+
+ assert bk.generation_in_flight() is False
+ b.generate(prompt = "a fox", width = 64, height = 64, steps = 8, loras = [("some/lora", 1.0)])
+ assert (
+ seen["in_flight"] is True
+ ), "liveness cannot tell this backend from a dead one while the native engine renders"
+ assert bk.generation_in_flight() is False
+
+
+def test_generation_in_flight_never_builds_a_backend(monkeypatch):
+ monkeypatch.setattr(bk, "_sd_cpp_backend", None)
+ monkeypatch.setattr(
+ bk,
+ "SdCppDiffusionBackend",
+ lambda *a, **k: pytest.fail("liveness constructed a native diffusion backend"),
+ )
+ assert bk.generation_in_flight() is False
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 60aca94e31d..650f184fb84 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -8282,3 +8282,366 @@ def test_the_h3_modular_refusal_reruns_when_the_prequant_checkpoint_does_not_lan
assert sized == ["fp8", None]
# ... and nothing was built.
assert _FakeModularPipeline.instance.load_kwargs is None
+
+
+def test_generation_in_flight_tracks_a_background_job(fake_runtime, tmp_path, monkeypatch):
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ rendering = threading.Event()
+ release = threading.Event()
+ inside = {}
+
+ def _block(
+ self,
+ *,
+ cancel_event = None,
+ **gen_kwargs,
+ ):
+ # Hold the worker open while liveness is checked.
+ inside["in_flight"] = video_mod.generation_in_flight()
+ rendering.set()
+ release.wait(10)
+ raise ValueError("stopped after the probe")
+
+ monkeypatch.setattr(VideoBackend, "generate", _block)
+
+ assert video_mod.generation_in_flight() is False
+ backend.begin_generate(prompt = "a clip")
+ assert rendering.wait(10), "the generate worker never started"
+ assert (
+ video_mod.generation_in_flight() is True
+ ), "liveness cannot tell this backend from a dead one while it renders a clip"
+ assert inside["in_flight"] is True
+
+ release.set()
+ deadline = time.monotonic() + 10
+ while backend.generate_progress()["active"] and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert video_mod.generation_in_flight() is False, (
+ "the marker stayed lit after the job ended, so the watchdog would hold the widened "
+ "budget against a backend that really did hang"
+ )
+
+
+def test_generation_in_flight_never_builds_a_backend(fake_runtime, monkeypatch):
+ import core.inference.video as video_mod
+
+ monkeypatch.setattr(video_mod, "_backend", None)
+ monkeypatch.setattr(
+ video_mod,
+ "VideoBackend",
+ lambda *a, **k: pytest.fail("liveness constructed a video backend"),
+ )
+ assert video_mod.generation_in_flight() is False
+
+
+def _video_result(tag: str) -> dict:
+ """The result shape _run_generate_body persists; tag identifies which job produced it."""
+ return {
+ "mp4_bytes": tag.encode(),
+ "negative_prompt": None,
+ "width": 64,
+ "height": 64,
+ "num_frames": 9,
+ "fps": 8,
+ "duration_s": 1.0,
+ "steps": 2,
+ "guidance": 1.0,
+ "seed": 1,
+ "has_audio": False,
+ "conditioning": "t2v",
+ "flow_shift": None,
+ "audio_flow_shift": None,
+ "repo_id": "test/model",
+ }
+
+
+def _until(predicate, timeout = 10.0):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.005)
+ return False
+
+
+def test_a_worker_that_never_started_does_not_hold_the_job_open(
+ fake_runtime, tmp_path, monkeypatch
+):
+ """begin_generate reserves the slot before it spawns, so a spawn that raises leaves a
+ reservation no worker will ever release: generate stays refused for the rest of the
+ session, and liveness reports this backend as rendering to a watchdog that answers a
+ busy backend by waiting longer, not by restarting it."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ real_start = threading.Thread.start
+ monkeypatch.setattr(
+ threading.Thread,
+ "start",
+ lambda self: (_ for _ in ()).throw(RuntimeError("can't start new thread")),
+ )
+
+ with pytest.raises(RuntimeError, match = "can't start new thread"):
+ backend.begin_generate(prompt = "a clip")
+
+ assert video_mod.generation_in_flight() is False
+ assert backend._active_generate_cancel is None
+ progress = backend.generate_progress()
+ assert progress["active"] is False, "progress stayed queued for a job that never ran"
+
+ # ... and the rejected spawn did not poison the next request.
+ monkeypatch.setattr(threading.Thread, "start", real_start)
+ monkeypatch.setattr(backend, "generate", lambda **kw: _video_result("second"))
+ from core.inference import video_gallery
+
+ monkeypatch.setattr(video_gallery, "save", lambda data, meta: {"id": "second"})
+
+ backend.begin_generate(prompt = "second")
+ assert _until(lambda: not video_mod.generation_in_flight())
+ assert backend.generate_progress()["phase"] == "completed"
+
+
[email protected]("ignore::pytest.PytestUnhandledThreadExceptionWarning")
+def test_a_worker_killed_outright_does_not_hold_the_job_open(fake_runtime, tmp_path, monkeypatch):
+ """The worker names ValueError, RuntimeError and Exception. SystemExit and
+ KeyboardInterrupt are none of those, so before the finally they unwound past every
+ terminal path and left the marker lit for good; unload() does not clear it either."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ entered = threading.Event()
+
+ def _die(
+ self,
+ *,
+ cancel_event = None,
+ **gen_kwargs,
+ ):
+ entered.set()
+ raise SystemExit("worker killed")
+
+ monkeypatch.setattr(VideoBackend, "generate", _die)
+
+ backend.begin_generate(prompt = "a clip")
+ assert entered.wait(10), "the generate worker never started"
+
+ assert _until(lambda: not video_mod.generation_in_flight()), (
+ "the marker outlived the worker, so liveness reports this backend as rendering "
+ "for the rest of the process"
+ )
+ assert backend.generate_progress()["active"] is False
+
+
+def test_a_finished_job_cannot_finalise_the_one_that_replaced_it(
+ fake_runtime, tmp_path, monkeypatch
+):
+ """The backstop runs after the body has already published, and by then the next job may
+ own the slot. Keyed on the busy flag it would finalise that successor instead: clear a
+ marker that is still rendering, overwrite its progress with a generic failure, and let a
+ third job past the busy guard. Keyed on the job's own token it is a no-op."""
+ import core.inference.video as video_mod
+ from core.inference import video_gallery
+ from core.inference.video_families import VIDEO_GENERATION_BUSY_MSG
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+ monkeypatch.setattr(video_gallery, "save", lambda data, meta: {"id": data.decode()})
+
+ second_running = threading.Event()
+ release_second = threading.Event()
+ calls = []
+
+ def _generate(*, cancel_event, **gen_kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ return _video_result("one")
+ second_running.set()
+ assert release_second.wait(10)
+ return _video_result("two")
+
+ monkeypatch.setattr(backend, "generate", _generate)
+
+ first_published = threading.Event()
+ release_first = threading.Event()
+ backstop_ran = threading.Event()
+ real_finish = backend._finish_generate_job
+
+ def _gated_finish(**kwargs):
+ # Hold the first job between publishing its outcome and reaching its backstop,
+ # which is exactly the window the second job reserves in.
+ if (kwargs.get("video") or {}).get("id") == "one":
+ real_finish(**kwargs)
+ first_published.set()
+ assert release_first.wait(10)
+ return
+ real_finish(**kwargs)
+ if kwargs.get("error") == "Video generation failed." and first_published.is_set():
+ backstop_ran.set()
+
+ monkeypatch.setattr(backend, "_finish_generate_job", _gated_finish)
+
+ backend.begin_generate(prompt = "one")
+ assert first_published.wait(10)
+
+ backend.begin_generate(prompt = "two")
+ assert second_running.wait(10)
+ assert video_mod.generation_in_flight() is True
+
+ release_first.set()
+ assert backstop_ran.wait(10), "the first job's backstop never ran"
+
+ assert video_mod.generation_in_flight() is True, (
+ "the finished job cleared the running job's marker; liveness now calls a rendering "
+ "backend idle, which is the failure this marker exists to prevent"
+ )
+ assert backend.generate_progress()["active"] is True
+ with pytest.raises(RuntimeError, match = VIDEO_GENERATION_BUSY_MSG):
+ backend.begin_generate(prompt = "three")
+
+ release_second.set()
+ assert _until(lambda: not video_mod.generation_in_flight())
+ progress = backend.generate_progress()
+ assert progress["phase"] == "completed"
+ assert progress["video"]["id"] == "two", "the running job lost its own outcome"
+
+
+def test_the_backstop_leaves_a_cancelled_job_reported_as_cancelled(
+ fake_runtime, tmp_path, monkeypatch
+):
+ """Cancellation is a RuntimeError carrying a sentinel the route maps to its own status.
+ A backstop that overwrote it would turn every cancel into a generic failure."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ entered = threading.Event()
+
+ def _wait_for_cancel(*, cancel_event, **gen_kwargs):
+ entered.set()
+ assert cancel_event.wait(10)
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
+
+ monkeypatch.setattr(backend, "generate", _wait_for_cancel)
+
+ backend.begin_generate(prompt = "cancel me")
+ assert entered.wait(10)
+ backend.cancel_generate()
+
+ assert _until(lambda: not video_mod.generation_in_flight())
+ progress = backend.generate_progress()
+ assert progress["phase"] == "failed"
+ assert progress["error"] == VIDEO_CANCELLED_MSG
+
+ # The backstop runs after the body returns; give it room to prove it changed nothing.
+ time.sleep(0.1)
+ assert backend.generate_progress()["error"] == VIDEO_CANCELLED_MSG
+
+
+def test_an_interrupted_spawn_leaves_a_live_worker_its_reservation(
+ fake_runtime, tmp_path, monkeypatch
+):
+ """Thread.start() creates the OS thread and then waits on it, so a signal delivered in
+ that wait unwinds with the worker already running. Rolling the reservation back there
+ would retire a live render's token: liveness would call it idle, cancel and unload could
+ not reach it, and the next request could reserve the slot underneath it."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ rendering = threading.Event()
+ release = threading.Event()
+
+ def _hold(*, cancel_event = None, **gen_kwargs):
+ rendering.set()
+ assert release.wait(10)
+ return _video_result("held")
+
+ monkeypatch.setattr(backend, "generate", _hold)
+ from core.inference import video_gallery
+
+ monkeypatch.setattr(video_gallery, "save", lambda data, meta: {"id": "held"})
+
+ real_start = threading.Thread.start
+
+ def _start_then_interrupt(self):
+ real_start(self)
+ raise KeyboardInterrupt("signal delivered while waiting on the child")
+
+ monkeypatch.setattr(threading.Thread, "start", _start_then_interrupt)
+
+ with pytest.raises(KeyboardInterrupt):
+ backend.begin_generate(prompt = "a clip")
+ assert rendering.wait(10), "the worker never started"
+
+ assert video_mod.generation_in_flight() is True, (
+ "the interrupted spawn retired a running render's reservation, so liveness reports "
+ "this backend as idle while it renders"
+ )
+ assert backend._active_generate_cancel is not None, "the running job lost its cancel handle"
+ monkeypatch.setattr(threading.Thread, "start", real_start)
+ with pytest.raises(RuntimeError, match = "already in progress"):
+ backend.begin_generate(prompt = "second")
+
+ release.set()
+ assert _until(lambda: not video_mod.generation_in_flight())
+ assert backend.generate_progress()["phase"] == "completed"
+
+
+def test_a_direct_worker_call_keeps_the_outcome_it_recorded(fake_runtime, tmp_path, monkeypatch):
+ """_run_generate is callable without a reservation. Such a caller finalises with the same
+ "unreserved" token the backstop would carry, so a backstop that fired here would match a
+ second time and replace the recorded outcome with the generic failure."""
+ import core.inference.video as video_mod
+ from core.inference import video_gallery
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+ monkeypatch.setattr(video_gallery, "save", lambda data, meta: {"id": "direct"})
+ monkeypatch.setattr(backend, "generate", lambda **kw: _video_result("direct"))
+
+ backend._run_generate(cancel_event = threading.Event(), prompt = "a clip")
+
+ progress = backend.generate_progress()
+ assert (
+ progress["phase"] == "completed"
+ ), f"a direct call recorded {progress['phase']!r}; the backstop overwrote its result"
+ assert progress["video"]["id"] == "direct"
+
+
+def test_a_direct_worker_call_keeps_its_cancellation(fake_runtime, tmp_path, monkeypatch):
+ """Same path, the outcome that matters most: a cancellation carries a sentinel the route
+ maps to its own status, and turning it into a generic failure loses that."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(video_mod, "_backend", backend)
+
+ def _cancelled(**kwargs):
+ raise RuntimeError(VIDEO_CANCELLED_MSG)
+
+ monkeypatch.setattr(backend, "generate", _cancelled)
+ backend._run_generate(cancel_event = threading.Event(), prompt = "a clip")
+
+ progress = backend.generate_progress()
+ assert progress["phase"] == "failed"
+ assert (
+ progress["error"] == VIDEO_CANCELLED_MSG
+ ), f"a direct call reported {progress['error']!r} instead of the cancellation sentinel"