Repository navigation
fix(images): refuse stale-model parameters in /v1/images/generations - #9451
danielhanchen merged 7 commits into
Conversation
The route picked per-model steps/guidance and the edit-only verdict from a status() read taken before generation. A model replacement can commit between that read and generate() acquiring its lock — the replacement's teardown fence is already down for most of its construction, so the in-lock refusal did not cover the window — and the request then ran on the NEW model with the OLD model's parameters, with eligibility decided against the old model too (unslothai#9448). generate() gains expected_repo_id: once it holds the generation lock, a mismatch against the loaded repo raises a typed DiffusionModelReplacedError instead of denoising with stale parameters. The route pins each attempt's status read via that argument and, when a replacement slipped in, re-decides from fresh state once (re-evaluating the edit-only gate and per-model defaults); a second displacement maps to a 503 telling the client to retry.
|
Confirmed the window in studio/backend/routes/inference.py where the status() read steers steps and guidance for a model that was replaced before generate() took its lock, so pinning it is the right direction. The rewritten error paths now call openai_error_body(..., status_code = 400) but that helper takes status =, so the edit-only and activation-shortfall refusals will raise instead of returning their 400; could you revert those two call sites and keep the diff to the expected_repo_id pin? |
Three call sites passed status_code = to openai_error_body, which takes status =, so the edit-only refusal, the activation shortfall 400 and this PR's own second displacement 503 all raised TypeError inside the route and came back as a sanitized 500. The edit-only gate had no test, which is how it went unnoticed. The route also passed expected_repo_id to whatever get_active_diffusion_engine() returned, but only DiffusionBackend accepted it. On a CPU or Apple host the active engine is SdCppDiffusionBackend, whose generate() is keyword-only with a fixed signature, so every /v1/images/generations call there became a 500. Give the native engine the same parameter and the same in-lock refusal instead of special-casing the route: the window is identical, its generate() binds state under the same two locks. DiffusionModelReplacedError moves to diffusion_families, next to the other runtime-to-route contract values, so the native engine can raise it without importing the torch backend. It is re-exported from diffusion, so both import paths keep working. Tests: the reported interleaving end to end (a load parked inside the construction of the new model, fence down, a generate blocked on the lock), the native engine's refusal, the edit-only 400, the displacement retry re-deriving the new model's steps and guidance, the bounded second displacement, and a backend reporting no repo_id.
|
Pushed 24a6c0a to your branch. The diagnosis is right and the 1.
|
| Suite | 489fab4 | c71d66e | 24a6c0a |
|---|---|---|---|
test_openai_images_generations_route.py |
49 passed | 11 failed, 38 passed | 56 passed |
test_diffusion_backend.py |
321 passed | 322 passed | 323 passed |
test_sd_cpp_backend.py |
105 passed | 105 passed | 106 passed |
Full studio/backend/tests on 24a6c0a matches the merge base exactly (same 180 pre-existing failures from optional deps missing locally, mcp / pymupdf / sqlite_vec).
I also ran the reported race live against the real DiffusionBackend. Without the pin it reproduces:
generate RETURNED, ran on NEW model
it used the caller's steps/guidance: 9 / 0.0
and with it:
generate RAISED DiffusionModelReplacedError: The image model was replaced while this
request waited (expected '.../old', loaded '.../new'); retry with fresh parameters.
Then a matrix over [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, Intel, CPU only, Apple GPU] x [native available or not] x [forced native or not], driving the real select_diffusion_engine and checking the route's call binds against the selected engine's actual generate signature, plus 20 route scenarios on each engine's shape. On c71d66e that reports 30 failures, all of them the native-engine and envelope paths above. On 24a6c0a it is clean. Same matrix in an isolated Python 3.11 venv with no torch and no diffusers installed: also clean, so light CPU installs are fine.
Concurrency stress on the real backend, 6 workers against 2 replacers: 13,926 pinned generations ran, 1,473 correctly refused, zero ran on a model other than their snapshot, no deadlock.
Backwards compatibility: expected_repo_id defaults to None on both engines and the guard is skipped when it is absent, so every existing caller is unchanged. Studio's own /api/inference/images/generate does not pass it and takes steps and guidance from the request body, so the Images page behaves exactly as before. No frontend files are touched. DiffusionModelReplacedError subclasses RuntimeError, so existing except RuntimeError handlers still catch it.
Resolves two conflicts against main's generation-slot rework: - diffusion.generate: main replaced the inline teardown fence and the _active_generate_cancel registration with _generation_slot(cancel), so the expected_repo_id guard now sits after main's in-lock cancel check and the registration line is gone. The window unslothai#9448 describes is unchanged by that rework: the slot admits on a zero fence, and a replacement that has already committed leaves the fence at zero, so a generation that snapshotted status() earlier still reaches the new model. Re-ran the live reproduction on the merged tree to confirm it still reproduces without the pin and is refused with it. - test_openai_images_generations_route: both sides appended, so main's api_monitor tests and the replacement tests are both kept, and the diffusion_families import merges the two names.
Opening comment-reduction pass: shorter wording, no lost intent. Comments and docstrings only, AST verified.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d935f663d8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if workflows and "txt2img" not in workflows: | ||
| raise HTTPException( |
There was a problem hiding this comment.
Validate edit-only status after pinning the snapshot
If status() observes an edit-only model and a concurrent load commits a text-to-image replacement immediately afterward, this branch returns 400 without ever calling the pinned generate() method, so the replacement cannot raise DiffusionModelReplacedError and trigger the fresh-state retry. This leaves the workflow half of the stale-snapshot race unfixed in the edit-only-to-text-to-image direction; eligibility should be validated against a load incarnation that is still current, or the backend should expose a pinned eligibility check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining this one. The window here is not the window #9448 is about.
The original bug is wide because generate() blocks on the generation lock for the entire construction of the replacement, so the gap between the status() read and the decision is seconds to minutes. On the edit-only path there is no blocking call at all: status() returns, then two dict lookups, then the raise. _generate_openai_images is async and there is no await between them, so the event loop cannot even yield; only a load committing on another thread inside that handful of bytecodes would do it.
The direction that matters is already covered, and 837d106 widens it. If status() says txt2img and a replacement makes the model edit-only, generate() is called and now refuses on the family change, since family is part of the pin. What is left is the inverse: refusing when we should have proceeded, in a microsecond window. The remedies you list both cost real behaviour, a lock acquisition on a refusal path that a long denoise would then block for minutes, or moving the eligibility check behind generate() so a routine edit-only 400 waits on the lock instead of answering immediately.
Happy to revisit if there is a path where that read and the raise are separated by something that blocks.
/images/load takes base_repo and family_override independently of model_path, so the same local checkpoint reloads as a materially different model while repo_id stays put. The OpenAI images route derives steps and guidance from base_repo whenever repo_id names no known model, and its edit-only verdict from the family, so a repo_id-only pin let exactly the replacement this branch exists to catch through. Reproduced against the real backend before changing anything: load a local checkpoint with base FLUX.1-dev, snapshot it, replace it with the same path under FLUX.1-schnell, and the generation ran the schnell pipeline at dev's 28 steps and 3.5 guidance. generate() now takes a LoadIdentity (repo_id, base_repo, family) built by load_identity() from the same status() read the parameters came from, and both engines compare all three. A distinct type rather than a tuple, so a caller who pins a bare repo id compares unequal and is refused instead of matching some other shape by accident. Two loads agreeing on all three derive identical parameters, which is exactly when accepting one for the other is correct. Tests: the same path reloaded under a different base is refused end to end, and the pin is asserted to cover every field the request is derived from.
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Final comment-reduction pass. Comments and docstrings only, AST verified. Also corrects one that went stale with the fix: an engine reporting no repo_id still pins its base and family, it does not pin nothing.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
What
DiffusionBackend.generategainsexpected_repo_id: once it holds_generate_lock, a mismatch against the actually-loadedstate.repo_idraises a new typedDiffusionModelReplacedErrorinstead of denoising.POST /v1/images/generationspins each attempt'sstatus()read via that argument, and on a displacement re-decides from fresh state once (re-evaluating the edit-only gate anddefault_generation_params), mapping a second displacement to a 503 with a retry hint.Why
#9448 — the route derived per-model steps/guidance and the edit-only refusal from a
status()read taken before generation. As the reporter detailed,begin_loaddrops its teardown fence right after_unload_lockedand then holds_generate_lockalone for the whole construction of the new model, so for the large majority of a replacement the in-lock teardown refusal does not apply: a generate arriving in that window blocks on the lock and then runs on the new model with the old model's steps/guidance, with eligibility decided against the old model too.Pinning the read to the generation closes the window at the only point both agree — after the lock is held — and the bounded retry makes the common displacement transparent to OpenAI-compatible clients rather than turning it into an error.
Testing
test_generate_refuses_when_the_model_was_replaced_since_the_snapshotintest_diffusion_backend.py, using the suite's established fake-pipeline harness: load a model,generate(expected_repo_id="other/model")raises the typed error carryingexpected/actual; a matching snapshot generates normally; omitting the argument keeps the historical behaviour for existing callers. This suite needs torch, which my local environment cannot import (known DLL breakage), so it runs in CI — the test mirrors the neighboringtest_load_generate_unload_ggufharness line-for-line. Verified the pre-change module lacks the exception entirely (the test cannot pass against it).python -m pytest studio/backend/tests/test_mmproj_hf_cache_root.py5/5 (non-torch sanity that the package still imports cleanly); both edited modulesast.parseclean.Fixes #9448