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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: queue media generation behind model teardown (#8866)
Divyansh Agrawal1bb508845212
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 54bb69aa2a4..db98ff9e794 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -18,6 +18,7 @@ bar. GPU-handoff policy lives in the arbiter the routes call, not here.from __future__ import annotations+from contextlib import contextmanagerimport functoolsimport inspectimport json@@ -1142,12 +1143,22 @@ class DiffusionBackend:self._load_token = 0# Set by unload() to abort an in-flight download. Replaced, never cleared, so a cancelled worker stays cancelled.self._cancel_event = threading.Event()+ # Keep Stop responsive while a replacement holds _lock.+ self._generation_cancel_lock = threading.Lock()# Cancel Event of the in-flight generation; per-generation so a cancel can't be lost or leak.self._active_generate_cancel: Optional[threading.Event] = None- # Unloads / superseding loads waiting on _generate_lock to free this pipeline. A generation queued behind the active- # one holds no cancel event yet, so without this fence it could win the lock after an eject and denoise anyway. A- # count, not a flag, so concurrent teardowns each own their own release.+ # Queued requests; cancel_generate() decides which Stop may signal.+ self._queued_generate_cancels: set[threading.Event] = set()+ # True while a generation owns the slot, including its epilogue.+ self._generation_owns_slot = False++ # True while a load or unload owns the generation slot.+ self._transition_owns_slot = False+ # Teardowns waiting to free this pipeline; a count supports concurrent reservations.self._teardown_waiters = 0+ # Set when no teardown is reserved; an Event keeps waiting independent of _lock.+ self._teardown_drained = threading.Event()+ self._teardown_drained.set()# Written by the callback, read lock-free by generate_progress().self._gen: Optional[_GenState] = None# img2img/inpaint pipes built via from_pipe (shared modules, no extra VRAM); cleared on unload.@@ -1170,6 +1181,106 @@ class DiffusionBackend:# The INDEXED string, so _resolve_device_target can rebuild a selection an override would erase.return target.torch_device, target.dtype+ def _reserve_teardown_locked(self) -> None:+ """Fence queued generations off the pipeline this teardown is about to free.++ Call only while holding ``_lock``, so the count and the gate move together.+ """+ self._teardown_waiters += 1+ self._teardown_drained.clear()++ def _release_teardown_locked(self) -> None:+ """Release one teardown reservation and wake generations when the last one leaves.++ Call only while holding ``_lock``. A count is necessary because an unload and a+ superseding load can both be queued behind the active generation.+ """+ assert self._teardown_waiters > 0, "teardown reservation released without an owner"+ self._teardown_waiters -= 1+ if self._teardown_waiters == 0:+ self._teardown_drained.set()++ @contextmanager+ def _model_transition_slot(self):+ """Hold the generation lock and publish that a model transition owns it.++ The teardown fence remains raised until after this context is entered, so queued+ cancellation always observes either that reservation or this owner flag. Releasing+ the flag and lock under the cancellation lock makes the handoff equally atomic.+ """+ self._generate_lock.acquire()+ with self._generation_cancel_lock:+ assert not self._transition_owns_slot, "two model transitions own one slot"+ self._transition_owns_slot = True+ try:+ yield+ finally:+ with self._generation_cancel_lock:+ self._transition_owns_slot = False+ self._generate_lock.release()++ @contextmanager+ def _generation_slot(self, cancel: threading.Event):+ """Hold the generation lock, yielding to teardown and remaining cancellable.++ Lock acquisition is not FIFO. If a generation wins the lock after a load or unload+ has raised its fence, it must let that teardown run before reading ``_state``. Once+ the final fence drops, the teardown still owns ``_generate_lock`` until its model+ transition has settled, so the retried acquisition observes the new truthful state.++ The zero-fence check and active-cancel registration share one ``_lock`` section. A+ teardown starting after that check therefore either sees this event and cancels it,+ or reserved before the check and makes this request yield.+ """+ admitted = False+ # Publish before the first acquisition so Stop can reach this request.+ with self._generation_cancel_lock:+ self._queued_generate_cancels.add(cancel)+ try:+ while True:+ # Timed acquisition keeps queued requests responsive during replacement.+ while True:+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ if self._generate_lock.acquire(timeout = 0.1):+ break+ with self._lock:+ if not self._teardown_waiters:+ # Register atomically with the zero-fence check.+ with self._generation_cancel_lock:+ cancelled = cancel.is_set()+ if not cancelled:+ self._queued_generate_cancels.discard(cancel)+ self._active_generate_cancel = cancel+ self._generation_owns_slot = True+ admitted = True+ else:+ cancelled = cancel.is_set()+ if admitted:+ break+ self._generate_lock.release()+ if cancelled:+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ # The gate wait leaves _lock free for the transition.+ while True:+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ if self._teardown_drained.wait(timeout = 0.1):+ break+ try:+ yield+ finally:+ # Release the slot and lock atomically for cancellation.+ with self._generation_cancel_lock:+ if self._active_generate_cancel is cancel:+ self._active_generate_cancel = None+ self._generation_owns_slot = False+ self._generate_lock.release()+ finally:+ if not admitted:+ with self._generation_cancel_lock:+ self._queued_generate_cancels.discard(cancel)+# Memory requests whose offload policy is decided by the REQUEST rather than by the measured# footprint. `fast` and `auto` are measurements and so cannot be judged network-free.def assert_precision_available(@@ -3217,11 +3328,12 @@ class DiffusionBackend:# Bail before signalling if this load was superseded, else a stale worker aborts a live one.if _load_token is not None and _load_token != self._load_token:raise RuntimeError("Diffusion load was cancelled.")- if self._active_generate_cancel is not None:- self._active_generate_cancel.set()+ with self._generation_cancel_lock:+ if self._active_generate_cancel is not None:+ self._active_generate_cancel.set()# Same fence unload() takes: a queued generation must not run on the pipeline this load is about to free.- self._teardown_waiters += 1- with self._generate_lock:+ self._reserve_teardown_locked()+ with self._model_transition_slot():with self._lock:try:# Re-check: a newer load/unload may have superseded this one while we waited.@@ -3232,7 +3344,7 @@ class DiffusionBackend:self._unload_locked()finally:# Released here, not at the end of the load: the old pipe is gone and the rest of the load holds _generate_lock.- self._teardown_waiters -= 1+ self._release_teardown_locked()# Single-file kinds resolve a checkpoint path; the pipeline kind has none.single_file_path = (@@ -5458,16 +5570,13 @@ class DiffusionBackend:# Per-generation cancel Event that unload()/a superseding load set (under _lock) to abort just this denoise.cancel = threading.Event()- with self._generate_lock:+ with self._generation_slot(cancel):with self._lock:- # A teardown is waiting for this lock and Python locks are not FIFO, so refuse rather than start a denoise on a pipeline that is already being torn down.- if self._teardown_waiters:- raise RuntimeError(DIFFUSION_CANCELLED_MSG)state = self._stateif state is None:raise RuntimeError(DIFFUSION_NOT_LOADED_MSG)- # Register under _lock so unload()/a load can signal THIS generation.- self._active_generate_cancel = cancel+ if cancel.is_set():+ raise RuntimeError(DIFFUSION_CANCELLED_MSG)# Publish an active (step 0) state before the slow pre-denoise setup so a reload mount probe does not read idle.self._gen = _GenState(total_steps = steps)try:@@ -5892,11 +6001,11 @@ class DiffusionBackend:# artifact per shape, so that save is not instant) and the page still shows Stop# for as long as progress reads active, so a Stop landing there was answered# cancelled = true and then contradicted by the image the route persisted.- # Check and deregister under _lock, which is the lock cancel_generate takes, so the+ # Check and deregister under the cancellation lock, which cancel_generate takes, so the# two cannot interleave: a cancel that saw this event registered ran strictly# before the check, and one that arrives after finds nothing to set and answers# false. The finally below repeats the clear for every other exit.- with self._lock:+ with self._generation_cancel_lock:if cancel.is_set():raise RuntimeError(DIFFUSION_CANCELLED_MSG)if self._active_generate_cancel is cancel:@@ -5927,9 +6036,10 @@ class DiffusionBackend:}finally:# Deregister so a later unload/load can't poke a finished generation (if still ours).- with self._lock:+ with self._generation_cancel_lock:if self._active_generate_cancel is cancel:self._active_generate_cancel = None+ with self._lock:# Sole clear of the published progress state, on every exit, so a crashed generation never leaves the UI stuck.self._gen = None@@ -5963,11 +6073,24 @@ class DiffusionBackend:Best effort by construction: the sampler stops at the NEXT step callback, so a cancelduring the VAE decode or the encode that precedes step 0 lands when that finishes.Same contract as the video backend."""- with self._lock:- cancel = self._active_generate_cancel- if cancel is None:+ with self._generation_cancel_lock:+ # Stop targets the denoising generation, not a serialized waiter.+ active = self._active_generate_cancel+ if active is not None:+ active.set()+ return True+ if self._generation_owns_slot:+ # Images are committed; do not report a cancellation after the last-word check.+ return False+ # Only teardown or transition ownership makes queued waiters cancellable.+ if not self._teardown_waiters and not self._transition_owns_slot:+ return False+ # Recheck live state so timed waiters observe a replacement handoff.+ cancels = set(self._queued_generate_cancels)+ if not cancels:return False- cancel.set()+ for cancel in cancels:+ cancel.set()return Truedef unload(self) -> dict[str, Any]:@@ -5976,23 +6099,25 @@ class DiffusionBackend:# rebinds this attribute, so an unlocked read could set an event the current load no longer watches.self._cancel_event.set()# Abort an in-flight denoise via ITS cancel event.- if self._active_generate_cancel is not None:- self._active_generate_cancel.set()- # Fence queued generations too: they hold no cancel event yet, so the signal above cannot reach them.- self._teardown_waiters += 1+ with self._generation_cancel_lock:+ if self._active_generate_cancel is not None:+ self._active_generate_cancel.set()+ # Fence queued generations too: they are intentionally not cancelled by model+ # lifecycle changes, so they must wait and observe the post-teardown state.+ self._reserve_teardown_locked()# Cancel any in-flight load (its worker checks this token) and drop the marker.self._load_token += 1self._loading = None# Wait for the signalled denoise to exit BEFORE tearing down: _unload_locked uninstalls process-wide state# (attention patches, GGUF compile hooks, backend flags, compile cache) the denoise still depends on.- with self._generate_lock:+ with self._model_transition_slot():with self._lock:try:self._unload_locked()finally:# Released in a finally, exactly like begin_load: _unload_locked ends in clear_gpu_cache(), which raises on a# sticky CUDA fault, and an un-drained fence would refuse every later generation for the life of the process.- self._teardown_waiters -= 1+ self._release_teardown_locked()return self.status()def _unload_locked(self) -> None:diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex cb38cd18f9e..37b4232881c 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -14,6 +14,7 @@ import contextlibimport reimport sysimport threading+import timeimport typesfrom pathlib import Path@@ -32,6 +33,7 @@ from core.inference.diffusion import (import core.inference.diffusion_eager_patches # noqa: E402,F401import core.inference.diffusion_arch_patches # noqa: E402,F401from core.inference.diffusion_families import (+ DIFFUSION_CANCELLED_MSG,_GATED_MIRROR_PAIRS,_MIRROR_PAIRS,_UNGATED_MIRROR_PAIRS,@@ -7378,7 +7380,7 @@ def test_download_plan_still_plans_an_unrecognised_gguf_given_an_explicit_base(mdef test_unload_fences_queued_generations_while_it_waits(fake_runtime, tmp_path):- # A queued generation holds no cancel event, so unload's signal cannot reach it, and Python locks are not FIFO, so it could get in ahead and denoise after the eject.+ # A queued generation must not bypass the teardown fence.(tmp_path / "model.gguf").write_bytes(b"weights")backend = DiffusionBackend()backend.load_pipeline(@@ -7437,8 +7439,50 @@ def test_a_raising_unload_still_drains_the_teardown_fence(fake_runtime, tmp_pathassert backend.generate(prompt = "after", steps = 2)["images"]-def test_generation_refuses_while_a_teardown_is_waiting(fake_runtime, tmp_path):- # The fence's effect: with a teardown waiting on _generate_lock, a generation that wins the lock refuses instead of denoising on a pipeline being freed.+class _RecordingGate(threading.Event):+ """Teardown gate that reports every time a generation parks on it."""++ def __init__(self, parked: threading.Event):+ super().__init__()+ self._parked = parked++ def wait(self, timeout = None):+ self._parked.set()+ return super().wait(timeout)+++class _AdmissionHookLock:+ """Lock wrapper that pauses generation after atomic admission releases state."""++ def __init__(self, backend, on_admitted):+ self._lock = threading.Lock()+ self._backend = backend+ self._on_admitted = on_admitted+ self._fired = False++ def acquire(self, *args, **kwargs):+ return self._lock.acquire(*args, **kwargs)++ def release(self):+ self._lock.release()+ if (+ not self._fired+ and threading.current_thread().name == "generation-under-test"+ and self._backend._active_generate_cancel is not None+ ):+ self._fired = True+ self._on_admitted()++ def __enter__(self):+ self.acquire()+ return self++ def __exit__(self, *_args):+ self.release()+++def test_generation_waits_for_all_pending_teardowns(fake_runtime, tmp_path, monkeypatch):+ # A lock winner must yield to every pending teardown.(tmp_path / "model.gguf").write_bytes(b"weights")backend = DiffusionBackend()backend.load_pipeline(@@ -7449,14 +7493,738 @@ def test_generation_refuses_while_a_teardown_is_waiting(fake_runtime, tmp_path):)assert backend.generate(prompt = "before", steps = 2)["images"]- backend._teardown_waiters = 1- with pytest.raises(RuntimeError, match = "cancelled"):- backend.generate(prompt = "during", steps = 2)- # Still loaded: the refusal is about the pending teardown, not a missing model.- assert backend._state is not None+ parked = threading.Event()+ denoise_entered = threading.Event()+ pipe_type = type(backend._state.pipe)+ real_call = pipe_type.__call__- backend._teardown_waiters = 0- assert backend.generate(prompt = "after", steps = 2)["images"]+ def record_denoise(self, *args, **kwargs):+ denoise_entered.set()+ return real_call(self, *args, **kwargs)++ monkeypatch.setattr(pipe_type, "__call__", record_denoise)+ backend._teardown_drained = _RecordingGate(parked)+ with backend._lock:+ backend._reserve_teardown_locked()+ backend._reserve_teardown_locked()++ outcome: dict = {}+ worker = threading.Thread(+ target = lambda: outcome.setdefault("result", backend.generate(prompt = "during", steps = 2)),+ daemon = True,+ )+ worker.start()+ assert parked.wait(5), "generation did not yield to the pending teardown"++ parked.clear()+ with backend._lock:+ backend._release_teardown_locked()+ assert parked.wait(5), "generation did not re-park behind the final teardown"+ assert not backend._teardown_drained.is_set(), "the gate opened with a reservation live"+ assert not denoise_entered.is_set(), "generation denoised before every teardown drained"++ with backend._lock:+ backend._release_teardown_locked()+ worker.join(5)+ assert not worker.is_alive(), "generation did not resume after the teardown drained"+ assert denoise_entered.is_set()+ assert outcome["result"]["images"]+++def test_cancel_wakes_generation_waiting_for_replacement(fake_runtime, tmp_path, monkeypatch):+ (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",+ )++ replacement_build_started = threading.Event()+ allow_replacement_commit = threading.Event()+ real_from_single_file = _FakeTransformer.from_single_file++ def blocking_from_single_file(cls, path, **kwargs):+ replacement_build_started.set()+ assert allow_replacement_commit.wait(5), "replacement load was not released"+ return real_from_single_file(path, **kwargs)++ monkeypatch.setattr(+ _FakeTransformer, "from_single_file", classmethod(blocking_from_single_file)+ )++ load_outcome: dict = {}++ def replace_model():+ try:+ load_outcome["result"] = backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "base/repo",+ family_override = "z-image",+ )+ except BaseException as exc: # noqa: BLE001 - surface worker failures in the test thread+ load_outcome["error"] = exc++ loader = threading.Thread(target = replace_model, daemon = True)+ loader.start()+ assert replacement_build_started.wait(5), load_outcome++ outcome: dict = {}++ def generate():+ try:+ backend.generate(prompt = "cancel while queued", steps = 2)+ except RuntimeError as exc:+ outcome["error"] = str(exc)++ worker = threading.Thread(target = generate, daemon = True)+ worker.start()+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._queued_generate_cancels:+ break+ time.sleep(0.01)+ else:+ allow_replacement_commit.set()+ pytest.fail("generation was not published while waiting for replacement")+ assert backend.cancel_generate() is True+ worker.join(5)+ assert not worker.is_alive(), "cancelled generation waited for replacement to finish"+ assert outcome["error"] == DIFFUSION_CANCELLED_MSG+ assert not backend._queued_generate_cancels+ assert backend.generate_progress()["active"] is False+ assert loader.is_alive(), "replacement unexpectedly finished before the queued cancel"++ allow_replacement_commit.set()+ loader.join(5)+ assert not loader.is_alive(), "replacement load did not finish"+ assert "error" not in load_outcome, load_outcome+++def test_cancel_stops_every_generation_queued_behind_teardown(fake_runtime, tmp_path):+ (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",+ )+ with backend._lock:+ backend._reserve_teardown_locked()++ errors: list[str] = []++ def generate(prompt):+ try:+ backend.generate(prompt = prompt, steps = 2)+ except RuntimeError as exc:+ errors.append(str(exc))++ workers = [+ threading.Thread(target = generate, args = (f"queued-{index}",), daemon = True)+ for index in range(2)+ ]+ for worker in workers:+ worker.start()++ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if len(backend._queued_generate_cancels) == 2:+ break+ time.sleep(0.01)+ else:+ pytest.fail("both generations did not register for queued cancellation")++ try:+ assert backend.cancel_generate() is True+ for worker in workers:+ worker.join(5)+ assert not worker.is_alive()+ assert errors == [DIFFUSION_CANCELLED_MSG, DIFFUSION_CANCELLED_MSG]+ assert not backend._queued_generate_cancels+ finally:+ with backend._lock:+ if backend._teardown_waiters:+ backend._release_teardown_locked()+++class _SlotYieldLock:+ """Generation-lock wrapper that reports the release yielding the slot to a teardown."""++ def __init__(self, lock, yielded):+ self._lock = lock+ self._yielded = yielded++ def acquire(self, *args, **kwargs):+ return self._lock.acquire(*args, **kwargs)++ def release(self):+ self._lock.release()+ self._yielded.set()++ def __enter__(self):+ self.acquire()+ return self++ def __exit__(self, *_args):+ self.release()+++def test_cancel_reaches_a_queued_generation_while_a_load_holds_the_state_lock(+ fake_runtime, tmp_path+):+ # A replacement holds _lock for the whole of its model construction, so a generation+ # parked behind the teardown must not need that lock to notice Stop. Waiting on a+ # Condition over _lock does need it -- Condition.wait() reacquires the lock before it+ # returns, timeout included -- which left the request blocked for the length of the load.+ (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",+ )+ with backend._lock:+ backend._reserve_teardown_locked()++ yielded = threading.Event()+ backend._generate_lock = _SlotYieldLock(backend._generate_lock, yielded)++ outcome: dict = {}++ def generate():+ try:+ backend.generate(prompt = "queued", steps = 2)+ except RuntimeError as exc:+ outcome["error"] = str(exc)++ worker = threading.Thread(target = generate, daemon = True)+ worker.start()+ assert yielded.wait(5), "generation did not yield the slot to the teardown"+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._queued_generate_cancels:+ break+ time.sleep(0.01)+ else:+ pytest.fail("the queued generation never published a cancel event")++ # Simulate construction while _lock is held.+ with backend._lock:+ assert backend.cancel_generate() is True+ worker.join(5)+ assert not worker.is_alive(), "Stop could not reach the queued generation"+ assert outcome["error"] == DIFFUSION_CANCELLED_MSG+ assert not backend._queued_generate_cancels++ with backend._lock:+ backend._release_teardown_locked()+++def test_cancel_reaches_a_waiter_once_the_generation_it_queued_behind_exits(+ fake_runtime, tmp_path, monkeypatch+):+ # Stop eligibility is decided from live state after the handoff.+ (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",+ )++ denoising = threading.Event()+ release_active = threading.Event()+ calls: list[int] = []+ real_call = _FakePipe.__call__++ def _call(self, **kwargs):+ first = not calls+ calls.append(1)+ if first:+ denoising.set()+ assert release_active.wait(5), "the active generation was never released"+ return real_call(self, **kwargs)++ monkeypatch.setattr(_FakePipe, "__call__", _call)++ outcomes: dict = {}++ def generate(key, prompt):+ try:+ outcomes[key] = backend.generate(prompt = prompt, steps = 2)+ except RuntimeError as exc:+ outcomes[key] = exc++ active = threading.Thread(target = generate, args = ("active", "active"), daemon = True)+ active.start()+ assert denoising.wait(5), "the first generation never started denoising"+ waiter = threading.Thread(target = generate, args = ("waiter", "waiter"), daemon = True)+ waiter.start()++ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._queued_generate_cancels:+ break+ time.sleep(0.01)+ else:+ release_active.set()+ pytest.fail("the waiting request was never published")++ # Reserve teardown before releasing the active generation.+ with backend._lock:+ backend._reserve_teardown_locked()+ release_active.set()+ active.join(5)+ assert not active.is_alive()++ try:+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._active_generate_cancel is None:+ break+ time.sleep(0.01)+ else:+ pytest.fail("the active generation never deregistered")++ assert backend.cancel_generate() is True, "Stop did not reach the waiting request"+ waiter.join(5)+ assert not waiter.is_alive(), "the waiting request stayed queued through the teardown"+ assert isinstance(outcomes["waiter"], RuntimeError)+ assert str(outcomes["waiter"]) == DIFFUSION_CANCELLED_MSG+ assert not backend._queued_generate_cancels+ finally:+ with backend._lock:+ if backend._teardown_waiters:+ backend._release_teardown_locked()+ waiter.join(5)+++def test_cancel_spares_a_serialized_request_through_the_active_epilogue(+ fake_runtime, tmp_path, monkeypatch+):+ # The active generation drops its cancel event at the last-word check, while it still owns+ # the slot for the epilogue that builds the result. Reading "no cancel event" as "nothing+ # owns the slot" there failed a request that was only serialised behind it.+ (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",+ )++ from core.inference import diffusion as diffusion_module++ queued = threading.Event()+ stop_answered: list[bool] = []+ fired: list[int] = []+ real_baked = diffusion_module._baked_lora_names++ def _baked(pipe):+ # Runs in the epilogue, after the last-word check cleared _active_generate_cancel and+ # before _generation_slot releases the lock. Only the first generation's epilogue has a+ # request queued behind it.+ if not fired:+ fired.append(1)+ if queued.wait(5):+ stop_answered.append(backend.cancel_generate())+ return real_baked(pipe)++ monkeypatch.setattr(diffusion_module, "_baked_lora_names", _baked)++ outcomes: dict = {}++ def generate(key, prompt):+ try:+ outcomes[key] = backend.generate(prompt = prompt, steps = 2)+ except RuntimeError as exc:+ outcomes[key] = exc++ active = threading.Thread(target = generate, args = ("active", "active"), daemon = True)+ active.start()+ serialized = threading.Thread(target = generate, args = ("serialized", "serialized"), daemon = True)+ serialized.start()+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._queued_generate_cancels:+ break+ time.sleep(0.01)+ queued.set()++ active.join(5)+ serialized.join(5)+ assert not active.is_alive() and not serialized.is_alive()+ assert stop_answered == [False], "Stop claimed a generation that had already committed"+ assert isinstance(outcomes["active"], dict), outcomes["active"]+ assert isinstance(outcomes["serialized"], dict), outcomes["serialized"]+ assert outcomes["serialized"]["images"]+++class _FirstAcquireHookLock:+ """Generation-lock wrapper that runs a hook before the first acquisition attempt."""++ def __init__(self, lock, on_first_acquire):+ self._lock = lock+ self._on_first_acquire = on_first_acquire+ self._fired = False++ def acquire(self, *args, **kwargs):+ if not self._fired:+ self._fired = True+ self._on_first_acquire()+ return self._lock.acquire(*args, **kwargs)++ def release(self):+ self._lock.release()++ def __enter__(self):+ self.acquire()+ return self++ def __exit__(self, *_args):+ self.release()+++def test_stop_reaches_a_queued_generation_before_its_first_lock_attempt(fake_runtime, tmp_path):+ # A replacement can already own the slot when the request arrives, so publishing the cancel+ # event only after the first timed acquisition failed left a 100 ms hole: Stop answered+ # false, the page settled its button back to Generate, and the generation still ran once the+ # load finished.+ (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",+ )+ with backend._lock:+ backend._reserve_teardown_locked()++ stop_answered: list[bool] = []+ backend._generate_lock = _FirstAcquireHookLock(+ backend._generate_lock, lambda: stop_answered.append(backend.cancel_generate())+ )++ outcome: dict = {}++ def generate():+ try:+ backend.generate(prompt = "queued", steps = 2)+ except RuntimeError as exc:+ outcome["error"] = str(exc)++ worker = threading.Thread(target = generate, daemon = True)+ worker.start()+ try:+ worker.join(5)+ assert not worker.is_alive(), "the queued generation did not unwind"+ assert stop_answered == [True], "Stop did not see the request before it queued"+ assert outcome["error"] == DIFFUSION_CANCELLED_MSG+ assert not backend._queued_generate_cancels+ finally:+ with backend._lock:+ if backend._teardown_waiters:+ backend._release_teardown_locked()+ worker.join(5)+++class _SlotHandoffLock:+ """Generation-lock wrapper that pauses a waiter after it receives the slot."""++ def __init__(self, lock, handed_off, admit_waiter):+ self._lock = lock+ self._handed_off = handed_off+ self._admit_waiter = admit_waiter++ def acquire(self, *args, **kwargs):+ acquired = self._lock.acquire(*args, **kwargs)+ if acquired and threading.current_thread().name == "serialized-waiter":+ self._handed_off.set()+ assert self._admit_waiter.wait(5), "the waiter was not allowed to register"+ return acquired++ def release(self):+ self._lock.release()++ def __enter__(self):+ self.acquire()+ return self++ def __exit__(self, *_args):+ self.release()+++def test_cancel_spares_a_serialized_request_during_slot_handoff(+ fake_runtime, tmp_path, monkeypatch+):+ # Once the active request releases _generate_lock, a waiter can own it before moving its+ # cancel event from the queued set to the active slot. Stop in that handoff must not mistake+ # the ordinary serialized waiter for a request blocked by model replacement.+ (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",+ )++ denoising = threading.Event()+ release_active = threading.Event()+ handed_off = threading.Event()+ admit_waiter = threading.Event()+ calls: list[int] = []+ real_call = _FakePipe.__call__++ def _call(self, **kwargs):+ first = not calls+ calls.append(1)+ if first:+ denoising.set()+ assert release_active.wait(5), "the active generation was never released"+ return real_call(self, **kwargs)++ monkeypatch.setattr(_FakePipe, "__call__", _call)+ backend._generate_lock = _SlotHandoffLock(backend._generate_lock, handed_off, admit_waiter)++ outcomes: dict = {}++ def generate(key, prompt):+ try:+ outcomes[key] = backend.generate(prompt = prompt, steps = 2)+ except RuntimeError as exc:+ outcomes[key] = exc++ active = threading.Thread(+ target = generate,+ args = ("active", "active"),+ name = "active-generation",+ daemon = True,+ )+ active.start()+ assert denoising.wait(5), "the first generation never started denoising"+ serialized = threading.Thread(+ target = generate,+ args = ("serialized", "serialized"),+ name = "serialized-waiter",+ daemon = True,+ )+ serialized.start()+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ with backend._generation_cancel_lock:+ if backend._queued_generate_cancels:+ break+ time.sleep(0.01)+ else:+ pytest.fail("the serialized request was never published")++ release_active.set()+ assert handed_off.wait(5), "the serialized waiter never received the slot"+ assert backend.cancel_generate() is False+ admit_waiter.set()++ active.join(5)+ serialized.join(5)+ assert not active.is_alive() and not serialized.is_alive()+ assert isinstance(outcomes["active"], dict), outcomes["active"]+ assert isinstance(outcomes["serialized"], dict), outcomes["serialized"]+ assert outcomes["serialized"]["images"]+++class _SlotContentionLock:+ """Generation-lock wrapper that reports a failed (contended) acquisition."""++ def __init__(self, lock, contended):+ self._lock = lock+ self._contended = contended++ def acquire(self, *args, **kwargs):+ acquired = self._lock.acquire(*args, **kwargs)+ if not acquired:+ self._contended.set()+ return acquired++ def release(self):+ self._lock.release()++ def __enter__(self):+ self.acquire()+ return self++ def __exit__(self, *_args):+ self.release()+++def test_cancel_spares_a_request_only_serialized_behind_the_active_one(+ fake_runtime, tmp_path, monkeypatch+):+ # Two image requests can be in flight at once: POST /images/generate and the+ # OpenAI-compatible POST /v1/images/generations both call generate() and neither has a+ # busy guard, so the second simply waits on _generate_lock. Stop is about the generation+ # the page is showing, so it must not fail that second request with the cancel sentinel+ # -- the same untrue "cancelled" this PR exists to remove.+ (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",+ )++ denoising = threading.Event()+ release_active = threading.Event()+ contended = threading.Event()+ calls: list[int] = []+ real_call = _FakePipe.__call__++ def _call(self, **kwargs):+ first = not calls+ calls.append(1)+ if first:+ denoising.set()+ assert release_active.wait(5), "the active generation was never released"+ return real_call(self, **kwargs)++ monkeypatch.setattr(_FakePipe, "__call__", _call)+ backend._generate_lock = _SlotContentionLock(backend._generate_lock, contended)++ outcomes: dict = {}++ def generate(key, prompt):+ try:+ outcomes[key] = backend.generate(prompt = prompt, steps = 2)+ except RuntimeError as exc:+ outcomes[key] = exc++ active = threading.Thread(target = generate, args = ("active", "active"), daemon = True)+ active.start()+ assert denoising.wait(5), "the first generation never started denoising"+ serialized = threading.Thread(target = generate, args = ("serialized", "serialized"), daemon = True)+ serialized.start()+ assert contended.wait(5), "the second request never queued on the generation lock"++ assert backend.cancel_generate() is True+ release_active.set()+ active.join(5)+ serialized.join(5)+ assert not active.is_alive() and not serialized.is_alive()++ assert isinstance(outcomes["active"], RuntimeError)+ assert str(outcomes["active"]) == DIFFUSION_CANCELLED_MSG+ assert isinstance(outcomes["serialized"], dict), outcomes["serialized"]+ assert outcomes["serialized"]["images"]+++def test_admission_registers_cancel_before_teardown_can_reserve(fake_runtime, tmp_path):+ (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",+ )++ start_teardown = threading.Event()+ teardown_reserved = threading.Event()+ saw_active_cancel: list[bool] = []++ def after_admission():+ start_teardown.set()+ assert teardown_reserved.wait(5), "teardown did not reserve after admission"++ backend._lock = _AdmissionHookLock(backend, after_admission)++ def teardown():+ assert start_teardown.wait(5), "generation never reached admission"+ with backend._lock:+ with backend._generation_cancel_lock:+ cancel = backend._active_generate_cancel+ saw_active_cancel.append(cancel is not None)+ if cancel is not None:+ cancel.set()+ backend._reserve_teardown_locked()+ teardown_reserved.set()+ with backend._generate_lock:+ with backend._lock:+ try:+ backend._unload_locked()+ finally:+ backend._release_teardown_locked()++ teardown_worker = threading.Thread(target = teardown, daemon = True)+ teardown_worker.start()++ outcome: dict = {}++ def generate():+ try:+ backend.generate(prompt = "atomic admission", steps = 2)+ except RuntimeError as exc:+ outcome["error"] = str(exc)++ generation_worker = threading.Thread(target = generate, name = "generation-under-test", daemon = True)+ generation_worker.start()+ generation_worker.join(5)+ teardown_worker.join(5)++ assert not generation_worker.is_alive(), "generation ignored teardown cancellation"+ assert not teardown_worker.is_alive(), "teardown remained blocked behind generation"+ assert saw_active_cancel == [True]+ assert outcome["error"] == DIFFUSION_CANCELLED_MSG+ assert backend._state is None+ assert backend._teardown_waiters == 0+++def test_generation_reports_not_loaded_after_waiting_for_unload(fake_runtime, tmp_path):+ (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",+ )++ parked = threading.Event()+ backend._teardown_drained = _RecordingGate(parked)+ with backend._lock:+ backend._reserve_teardown_locked()++ outcome: dict = {}++ def generate():+ try:+ backend.generate(prompt = "during", steps = 2)+ except RuntimeError as exc:+ outcome["error"] = str(exc)++ worker = threading.Thread(target = generate, daemon = True)+ worker.start()+ assert parked.wait(5), "generation did not wait for unload"++ with backend._lock:+ backend._unload_locked()+ backend._release_teardown_locked()+ worker.join(5)+ assert not worker.is_alive(), "generation remained blocked after unload"+ assert outcome["error"] == "No diffusion model is loaded."def test_a_superseding_load_fences_queued_generations_too(fake_runtime, tmp_path):