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
fix(images): refuse stale-model parameters in /v1/images/generations (#9451)
yzxcj797da060f0c682c
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex f1d98e71ad7..e28f31da30d 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -44,6 +44,9 @@ from .diffusion_families import (IDEOGRAM4_FAMILY_NAME,LUMINA2_FAMILY_NAME,DiffusionFamily,+ DiffusionModelReplacedError, # re-exported: callers import it from either module+ LoadIdentity,+ load_identity,assert_flux2_gguf_matches_base,assert_pipeline_class_available,_is_local_path,@@ -5586,6 +5589,8 @@ class DiffusionBackend:loras: Optional[list[tuple[str, float]]] = None,# ControlNet (id, control_image_b64, control_type, strength, guidance_start, guidance_end). None = off.controlnet: Optional[tuple[str, str, str, float, float, float]] = None,+ # load_identity() of the caller's status() read; refuse rather than run a different load (#9448).+ expected_load: Optional[LoadIdentity] = None,) -> dict[str, Any]:import torchfrom PIL import Image@@ -5599,6 +5604,10 @@ class DiffusionBackend:raise RuntimeError(DIFFUSION_NOT_LOADED_MSG)if cancel.is_set():raise RuntimeError(DIFFUSION_CANCELLED_MSG)+ # The slot admits on a zero fence, which a COMMITTED replacement also satisfies (#9448).+ loaded_id = load_identity(state.repo_id, state.base_repo, state.family.name)+ if expected_load is not None and expected_load != loaded_id:+ raise DiffusionModelReplacedError(expected_load, loaded_id)# 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:diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 8b329429f21..a0ff3188fa5 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -30,6 +30,48 @@ DIFFUSION_NOT_LOADED_MSG = "No diffusion model is loaded."DIFFUSION_CANCELLED_MSG = "Diffusion generation was cancelled."+@dataclass(frozen = True)+class LoadIdentity:+ """What a caller's derived request parameters depend on, as one comparable value.++ ``repo_id`` alone is not one: /images/load takes ``base_repo`` and ``family_override``+ independently of the path, so a local checkpoint reloads as a different model while the+ path stays put, and the images route derives steps/guidance from ``base_repo`` and its+ edit-only verdict from the family (#9448). Loads agreeing on all three derive identical+ parameters, which is exactly when accepting one for the other is correct.++ A type rather than a tuple, so pinning a bare repo id compares unequal and is refused+ instead of matching some other shape by accident.+ """++ repo_id: str+ base_repo: str+ family: str+++def load_identity(repo_id, base_repo, family) -> LoadIdentity:+ """``LoadIdentity`` for one load. None and "" describe the same absent field."""+ return LoadIdentity(str(repo_id or ""), str(base_repo or ""), str(family or ""))+++class DiffusionModelReplacedError(RuntimeError):+ """Both engines' ``generate`` refusing a ``LoadIdentity`` that is no longer loaded.++ Keeps a caller's per-model steps/guidance and workflow verdict, taken from an earlier+ ``status()`` read, off a model they never validated (#9448). Here rather than in+ ``diffusion`` so the native engine can raise it without importing the torch backend.+ """++ def __init__(self, expected: LoadIdentity, actual: LoadIdentity):+ super().__init__(+ f"The image model was replaced while this request waited "+ f"(expected {expected.repo_id!r}, loaded {actual.repo_id!r}); "+ "retry with fresh parameters."+ )+ self.expected = expected+ self.actual = actual++@dataclass(frozen = True)class DiffusionFamily:name: strdiff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 88383ed2b33..15e92453d0b 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -43,7 +43,10 @@ from core.inference.diffusion_families import (DIFFUSION_CANCELLED_MSG,DIFFUSION_NOT_LOADED_MSG,DiffusionFamily,+ DiffusionModelReplacedError,+ LoadIdentity,detect_family_for_pick,+ load_identity,family_sd_cpp_supported,mirror_repo,legacy_source_repo,@@ -2156,6 +2159,8 @@ class SdCppDiffusionBackend:loras: Optional[list[tuple[str, float]]] = None,# ControlNet is diffusers-only; rejected by the guard below (accepted for parity).controlnet: Optional[tuple[str, str, str, float, float, float]] = None,+ # load_identity() of the caller's status() read; refuse rather than run a different load (#9448).+ expected_load: Optional[LoadIdentity] = None,) -> dict[str, Any]:import tempfile@@ -2202,6 +2207,10 @@ class SdCppDiffusionBackend:):self._state = Noneraise RuntimeError(DIFFUSION_NOT_LOADED_MSG)+ # Same window as the diffusers engine: a replacement can commit while this waits (#9448).+ loaded_id = load_identity(state.repo_id, state.base_repo, state.family.name)+ if expected_load is not None and expected_load != loaded_id:+ raise DiffusionModelReplacedError(expected_load, loaded_id)self._active_generate_cancel = cancel# Publish an active (step 0) state before the slow pre-generate setup so a reload probe does not read idle while this holds _generate_lock.self._gen = _SdGen(total_steps = int(steps))diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex cdb83432fbe..fa72ff3b142 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -26773,53 +26773,74 @@ async def _generate_openai_images(# Use the active engine (diffusers OR native sd.cpp), the same accessor /images/generate uses.backend = get_active_diffusion_engine()- status = backend.status()- if not status.get("loaded"):- # Mirror /v1/completions and /v1/embeddings, which 503 when their backend is not loaded.- raise HTTPException(status_code = 503, detail = _NO_IMAGE_MODEL_MSG)-- # An edit-only model needs an input image this API cannot supply; refuse with a 400 rather than a backend 500.- workflows = status.get("workflows") or []- if workflows and "txt2img" not in workflows:- raise HTTPException(- status_code = 400,- detail = openai_error_body(- "The loaded image model is edit-only (it requires an input image); "- "load a text-to-image model to use this endpoint.",- status = 400,- param = "model",- ),- )-- # Fall back to the resolved base repo so a local-path load still gets the right per-model steps/guidance.- steps, guidance = default_generation_params(status.get("repo_id"), status.get("base_repo"))- try:- result = await asyncio.to_thread(- backend.generate,- prompt = body.prompt,- width = width,- height = height,- steps = steps,- guidance = guidance,- batch_size = body.n,- )- except Exception as exc: # noqa: BLE001 (single boundary, sanitized envelope)- # A RuntimeError with the model now unloaded means it was evicted mid-call (a race): 503. Every other failure is a real 500 whose raw message must not reach the client.- if isinstance(exc, RuntimeError) and not backend.is_loaded:+ from core.inference.diffusion_memory import ImageActivationShortfallError+ from core.inference.diffusion_families import DiffusionModelReplacedError, load_identity++ # A replacement can commit between this status() read and generate() taking its lock, running the+ # new model with the old one's steps/guidance and edit-only verdict (#9448). Pin the read to the+ # generation, then re-decide from fresh state once.+ result = None+ for attempt in range(2):+ status = backend.status()+ if not status.get("loaded"):+ # Mirror /v1/completions and /v1/embeddings, which 503 when their backend is not loaded.raise HTTPException(status_code = 503, detail = _NO_IMAGE_MODEL_MSG)- # The activation refusal is the one message here written FOR the caller: it names the- # resolution, the budget and the remedies. Sanitising it into "Image generation failed."- # left an OpenAI client with a 500 for a request only they can fix, while the Studio- # route showed the reason. Typed, so no other ValueError's raw text escapes.- from core.inference.diffusion_memory import ImageActivationShortfallError- if isinstance(exc, ImageActivationShortfallError):+ # An edit-only model needs an input image this API cannot supply; refuse with a 400 rather than a backend 500.+ workflows = status.get("workflows") or []+ if workflows and "txt2img" not in workflows:raise HTTPException(status_code = 400,- detail = openai_error_body(str(exc), status = 400, param = "size"),+ detail = openai_error_body(+ "The loaded image model is edit-only (it requires an input image); "+ "load a text-to-image model to use this endpoint.",+ status = 400,+ param = "model",+ ),)- logger.error("openai_images.generate_failed: %s", exc)- raise HTTPException(status_code = 500, detail = "Image generation failed.")++ # Fall back to the resolved base repo so a local-path load still gets the right per-model steps/guidance.+ steps, guidance = default_generation_params(status.get("repo_id"), status.get("base_repo"))+ try:+ result = await asyncio.to_thread(+ backend.generate,+ prompt = body.prompt,+ width = width,+ height = height,+ steps = steps,+ guidance = guidance,+ batch_size = body.n,+ expected_load = load_identity(+ status.get("repo_id"), status.get("base_repo"), status.get("family")+ ),+ )+ break+ except DiffusionModelReplacedError:+ if attempt > 0:+ raise HTTPException(+ status_code = 503,+ detail = openai_error_body(+ "The image model was replaced while this request waited; retry with fresh parameters.",+ status = 503,+ param = "model",+ ),+ )+ continue+ except Exception as exc: # noqa: BLE001 (single boundary, sanitized envelope)+ # A RuntimeError with the model now unloaded means it was evicted mid-call (a race): 503. Every other failure is a real 500 whose raw message must not reach the client.+ if isinstance(exc, RuntimeError) and not backend.is_loaded:+ raise HTTPException(status_code = 503, detail = _NO_IMAGE_MODEL_MSG)+ # The activation refusal is the one message here written FOR the caller: it names the+ # resolution, the budget and the remedies. Sanitising it into "Image generation failed."+ # left an OpenAI client with a 500 for a request only they can fix, while the Studio+ # route showed the reason. Typed, so no other ValueError's raw text escapes.+ if isinstance(exc, ImageActivationShortfallError):+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(str(exc), status = 400, param = "size"),+ )+ logger.error("openai_images.generate_failed: %s", exc)+ raise HTTPException(status_code = 500, detail = "Image generation failed.")# A local-directory load puts the host path in repo_id and the monitor row goes out over# the tunnel, so the label gets the same path-free treatment as active_model.diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 37b4232881c..7e97f675ca7 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -22,6 +22,7 @@ import pytestfrom core.inference.diffusion import (DiffusionBackend,+ DiffusionModelReplacedError,_LoadState,_base_file_downloaded,_clamp_max_side,@@ -41,6 +42,7 @@ from core.inference.diffusion_families import (canonical_base,detect_family,family_prequant_repo,+ load_identity,mirror_repo,prefer_ungated_mirror,resolve_base_repo,@@ -753,6 +755,128 @@ def fake_runtime(monkeypatch):yield+def test_generate_refuses_when_the_model_was_replaced_since_the_snapshot(fake_runtime, tmp_path):+ """The guard in isolation: a snapshot naming another model is refused, typed (#9448)."""+ (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",+ )+ st = backend.status()+ loaded = load_identity(st["repo_id"], st["base_repo"], st["family"])++ # Snapshot names a different model: typed refusal, no denoise started.+ stale = load_identity("other/model", st["base_repo"], st["family"])+ with pytest.raises(DiffusionModelReplacedError) as replaced:+ backend.generate(prompt = "stale request", expected_load = stale)+ assert replaced.value.expected == stale+ assert replaced.value.actual == loaded++ gen = backend.generate(prompt = "fresh request", expected_load = loaded, steps = 4)+ assert len(gen["images"]) == 1++ # And callers that pass no snapshot keep the historical behaviour.+ gen2 = backend.generate(prompt = "legacy caller", steps = 4)+ assert len(gen2["images"]) == 1+++def test_generate_refuses_a_replacement_that_committed_while_it_waited(fake_runtime, tmp_path):+ """The reported interleaving end to end (#9448).++ A load drops its teardown fence for the whole construction of the new model while still+ holding the generation lock, so a generate arriving there used to block, then denoise on+ the NEW model with the snapshot's steps/guidance.+ """+ old_dir, new_dir = tmp_path / "old", tmp_path / "new"+ for d in (old_dir, new_dir):+ d.mkdir()+ (d / "model.gguf").write_bytes(b"weights")+ load_kwargs = dict(gguf_filename = "model.gguf", base_repo = "base/repo", family_override = "z-image")++ backend = DiffusionBackend()+ backend.load_pipeline(str(old_dir), **load_kwargs)+ st = backend.status() # the route's pre-generation read+ snapshot = load_identity(st["repo_id"], st["base_repo"], st["family"])++ # Park a replacement inside the construction of the new model: the fence is down there.+ reached, release = threading.Event(), threading.Event()+ original = _FakeTransformer.from_single_file.__func__++ def _parked(cls, path, **kwargs):+ reached.set()+ assert release.wait(30)+ return original(cls, path, **kwargs)++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(_FakeTransformer, "from_single_file", classmethod(_parked))+ loader = threading.Thread(+ target = backend.load_pipeline, args = (str(new_dir),), kwargs = load_kwargs, daemon = True+ )+ loader.start()+ assert reached.wait(30)+ assert backend._teardown_waiters == 0 # the window under test is genuinely open++ outcome = {}++ def _generate():+ try:+ outcome["ok"] = backend.generate(+ prompt = "a sloth", steps = 9, guidance = 0.0, expected_load = snapshot+ )+ except BaseException as exc: # noqa: BLE001 (the exception IS the assertion)+ outcome["err"] = exc++ gen = threading.Thread(target = _generate, daemon = True)+ gen.start()+ gen.join(1.0)+ assert gen.is_alive() # blocked on _generate_lock, which the load holds++ release.set()+ loader.join(30)+ gen.join(30)++ assert not gen.is_alive()+ assert backend.status()["repo_id"] == str(new_dir) # the replacement did commit+ assert "ok" not in outcome, "denoised on the replacement with the snapshot's parameters"+ assert isinstance(outcome["err"], DiffusionModelReplacedError)+ assert (outcome["err"].expected.repo_id, outcome["err"].actual.repo_id) == (+ str(old_dir),+ str(new_dir),+ )+++def test_the_same_path_reloaded_under_a_different_base_is_a_replacement(fake_runtime, tmp_path):+ """repo_id is not a load identity (#9448).++ base_repo and family_override are settable per load, so one local checkpoint reloads as a+ different model. Pinning the path alone let a FLUX.1-dev request reach a schnell pipeline.+ """+ (tmp_path / "model.gguf").write_bytes(b"weights")+ backend = DiffusionBackend()+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "black-forest-labs/FLUX.1-dev",+ family_override = "z-image",+ )+ st = backend.status()+ snapshot = load_identity(st["repo_id"], st["base_repo"], st["family"])++ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "black-forest-labs/FLUX.1-schnell",+ family_override = "z-image",+ )+ assert backend.status()["repo_id"] == snapshot.repo_id # repo_id alone sees no change+ with pytest.raises(DiffusionModelReplacedError) as replaced:+ backend.generate(prompt = "p", steps = 28, guidance = 3.5, expected_load = snapshot)+ assert replaced.value.actual.base_repo == "black-forest-labs/FLUX.1-schnell"++def test_load_generate_unload_gguf(fake_runtime, tmp_path):(tmp_path / "model.gguf").write_bytes(b"weights")backend = DiffusionBackend()diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.pyindex cd99c9994db..af01b6c954b 100644--- a/studio/backend/tests/test_openai_images_generations_route.py+++ b/studio/backend/tests/test_openai_images_generations_route.py@@ -20,7 +20,11 @@ import core.inference.diffusion_engine_router as engine_routerimport core.inference.image_gallery as gallery_modulefrom auth.authentication import get_current_subjectfrom core.inference.api_monitor import api_monitor-from core.inference.diffusion_families import default_generation_params+from core.inference.diffusion_families import (+ DiffusionModelReplacedError,+ default_generation_params,+ load_identity,+)from routes.inference import router, _parse_openai_image_sizefrom utils.api_errors import install_api_error_handlers@@ -103,10 +107,17 @@ class _FakeBackend:generate_error = None,unload_on_generate = False,native_seeds = False,+ # Supported workflows: a list, or a repo_id -> list map so a replacement changes them.+ workflows = None,+ # (repo_id, base_repo) pairs generate() reports as loaded, one per call: models a+ # replacement landing between the route's status() read and its lock (#9448).+ replaced_by = None,) -> None:self._loaded = loadedself._repo_id = repo_idself._base_repo = base_repo+ self._workflows = workflows+ self._replaced_by = list(replaced_by or [])# Model the native sd.cpp engine, which returns a distinct seed per image.self._native_seeds = native_seeds# When set, generate() raises this; unload_on_generate flips is_loaded off first, to model the eviction race vs an in-pipeline OOM.@@ -119,7 +130,7 @@ class _FakeBackend:return self._loadeddef status(self):- return {+ out = {"loaded": self._loaded,"repo_id": self._repo_id if self._loaded else None,"family": "z-image" if self._loaded else None,@@ -128,6 +139,11 @@ class _FakeBackend:"dtype": "float32","cpu_offload": False,}+ if isinstance(self._workflows, dict):+ out["workflows"] = self._workflows.get(self._repo_id, [])+ elif self._workflows is not None:+ out["workflows"] = self._workflows+ return outdef generate(self,@@ -138,9 +154,16 @@ class _FakeBackend:steps,guidance,batch_size = 1,+ expected_load = None,):if not self._loaded:raise RuntimeError("No diffusion model is loaded.")+ # Both engines refuse in-lock when the caller's snapshot named a different model.+ if self._replaced_by:+ self._repo_id, self._base_repo = self._replaced_by.pop(0)+ loaded = load_identity(self._repo_id, self._base_repo, "z-image")+ if expected_load is not None and expected_load != loaded:+ raise DiffusionModelReplacedError(expected_load, loaded)if self._generate_error is not None:if self._unload_on_generate:self._loaded = False@@ -153,6 +176,7 @@ class _FakeBackend:steps = steps,guidance = guidance,batch_size = batch_size,+ expected_load = expected_load,))out = {@@ -209,7 +233,13 @@ def test_url_response_shape(client):assert "/images/gallery/img0/file-signed?token=" in item["url"]# Z-Image-Turbo defaults (9 steps, 0 guidance) flow into the backend call.assert client.backend.calls[0] == dict(- prompt = "a sloth", width = 256, height = 256, steps = 9, guidance = 0.0, batch_size = 1+ prompt = "a sloth",+ width = 256,+ height = 256,+ steps = 9,+ guidance = 0.0,+ batch_size = 1,+ expected_load = load_identity("unsloth/Z-Image-Turbo-GGUF", None, "z-image"),)@@ -540,3 +570,114 @@ def test_a_failed_generation_does_not_leak_a_local_path_label(monkeypatch):row = api_monitor.snapshot(include_details = False)[0]assert row["status"] == "error"assert row["model"] == expected+++# ── model replaced mid-request (#9448) ──────────────────────────────────+++def _replacement_client(monkeypatch, backend):+ monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)+ cli, store, _save = _make_client(backend)+ monkeypatch.setattr(gallery_module, "save", _save)+ return cli, store+++def test_generation_pins_the_status_read_it_derived_its_params_from(monkeypatch):+ # Without the pin the backend cannot tell a stale snapshot from a fresh one.+ backend = _FakeBackend()+ cli, _ = _replacement_client(monkeypatch, backend)+ assert cli.post("/v1/images/generations", json = {"prompt": "p"}).status_code == 200+ assert backend.calls[0]["expected_load"] == load_identity(+ "unsloth/Z-Image-Turbo-GGUF", None, "z-image"+ )+++def test_replacement_retries_once_with_the_new_models_params(monkeypatch):+ # Z-Image-Turbo (9 steps, guidance 0) is replaced by Z-Image (20 steps, guidance 4). The first+ # attempt is refused in-lock; the retry must re-derive from fresh state, not reuse the turbo's.+ backend = _FakeBackend(replaced_by = [("unsloth/Z-Image-GGUF", None)])+ cli, _ = _replacement_client(monkeypatch, backend)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 200+ assert len(backend.calls) == 1 # the refused attempt never generated+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (20, 4.0)+++def test_second_replacement_is_a_503_not_a_sanitized_500(monkeypatch):+ # Bounded at one retry, and the client is told to retry rather than handed a server error.+ backend = _FakeBackend(replaced_by = [("a/one", None), ("b/two", None)])+ cli, _ = _replacement_client(monkeypatch, backend)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 503+ assert backend.calls == []+ err = resp.json()["error"]+ assert err["type"] == "api_error" and err["param"] == "model"+ assert "replaced" in err["message"]+++def test_replacement_into_an_edit_only_model_is_a_400(monkeypatch):+ # The retry re-decides eligibility too, not just the parameters.+ edit_only = "unsloth/Qwen-Image-Edit-GGUF"+ backend = _FakeBackend(+ replaced_by = [(edit_only, None)],+ workflows = {"unsloth/Z-Image-Turbo-GGUF": ["txt2img"], edit_only: ["img2img"]},+ )+ cli, _ = _replacement_client(monkeypatch, backend)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 400+ assert "edit-only" in resp.json()["error"]["message"]+ assert backend.calls == []+++def test_edit_only_model_is_an_actionable_400(monkeypatch):+ # No test covered this gate, so a broken error-envelope call there turned it into a 500.+ backend = _FakeBackend(workflows = ["img2img", "inpaint"])+ cli, _ = _replacement_client(monkeypatch, backend)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 400+ err = resp.json()["error"]+ assert err["type"] == "invalid_request_error" and err["param"] == "model"+ assert "edit-only" in err["message"]+ assert backend.calls == []+++def test_txt2img_capable_model_passes_the_gate(monkeypatch):+ # A model advertising txt2img among its workflows must not be caught by the edit-only refusal.+ backend = _FakeBackend(workflows = ["txt2img", "img2img"])+ cli, _ = _replacement_client(monkeypatch, backend)+ assert cli.post("/v1/images/generations", json = {"prompt": "p"}).status_code == 200+++def test_backend_reporting_no_repo_id_still_generates(monkeypatch):+ # An engine reporting no repo_id still pins its base and family, and still generates.+ backend = _FakeBackend(repo_id = None)+ cli, _ = _replacement_client(monkeypatch, backend)+ assert cli.post("/v1/images/generations", json = {"prompt": "p"}).status_code == 200+ assert backend.calls[0]["expected_load"] == load_identity(None, None, "z-image")+++def test_same_repo_reloaded_under_a_different_base_is_a_replacement(monkeypatch):+ # base_repo is settable per load, and decides steps/guidance when repo_id names nothing+ # known. Pinning repo_id alone let FLUX.1-dev's 28 steps / 3.5 reach a schnell pipeline.+ local = "/models/my-ckpt"+ dev, schnell = "black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-schnell"+ assert default_generation_params(local, dev) != default_generation_params(local, schnell)+ backend = _FakeBackend(repo_id = local, base_repo = dev, replaced_by = [(local, schnell)])+ cli, _ = _replacement_client(monkeypatch, backend)+ resp = cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"})+ assert resp.status_code == 200+ assert len(backend.calls) == 1 # the refused attempt never generated+ assert (backend.calls[0]["steps"], backend.calls[0]["guidance"]) == (4, 0.0)+++def test_the_pin_covers_every_field_the_request_is_derived_from():+ # Whatever the route derives parameters or eligibility from has to be in the pin, or a+ # replacement that differs only there is accepted as the snapshot.+ turbo, base = "unsloth/Z-Image-Turbo-GGUF", "Tongyi-MAI/Z-Image"+ pin = load_identity(turbo, base, "z-image")+ assert pin != load_identity("unsloth/Z-Image-GGUF", base, "z-image") # steps/guidance+ assert pin != load_identity(turbo, "black-forest-labs/FLUX.1-dev", "z-image") # steps/guidance+ assert pin != load_identity(turbo, base, "qwen-image-edit") # edit-only verdict+ # None and "" describe the same absent field, so they must not read as a replacement.+ assert load_identity(turbo, None, "z-image") == load_identity(turbo, "", "z-image")diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex 7dade471217..413e5d30bfd 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -752,6 +752,23 @@ def test_generate_qwen_passes_sampling_args():assert "--flow-shift" in (kw.get("extra_args") or [])+def test_generate_refuses_a_snapshot_naming_another_model():+ # Parity with the diffusers engine (#9448): on a no-GPU host the OpenAI images route runs here.+ eng = _FakeEngine()+ b = _loaded_backend(engine = eng)+ st = b.status()+ loaded = bk.load_identity(st["repo_id"], st["base_repo"], st["family"])+ with pytest.raises(bk.DiffusionModelReplacedError) as replaced:+ stale = bk.load_identity("other/model", st["base_repo"], st["family"])+ b.generate(prompt = "stale", expected_load = stale)+ assert replaced.value.expected.repo_id == "other/model"+ assert replaced.value.actual == loaded+ assert eng.calls == [] # refused before any sd-cli run+ # A matching snapshot, and an absent one (the pre-#9448 caller), both still generate.+ assert b.generate(prompt = "x", steps = 4, expected_load = loaded)+ assert b.generate(prompt = "x", steps = 4)++def test_generate_raises_when_not_loaded():b = SdCppDiffusionBackend(engine = _FakeEngine())with pytest.raises(RuntimeError, match = "No diffusion model is loaded"):