Skip to content

fix(images): refuse stale-model parameters in /v1/images/generations - #9451

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
yzxcj797:fix/images-replaced-model-params-9448
Aug 23, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
yzxcj797:fix/images-replaced-model-params-9448

Conversation

@yzxcj797

Copy link
Copy Markdown
Contributor

Summary

What

  • DiffusionBackend.generate gains expected_repo_id: once it holds _generate_lock, a mismatch against the actually-loaded state.repo_id raises a new typed DiffusionModelReplacedError instead of denoising.
  • POST /v1/images/generations pins each attempt's status() read via that argument, and on a displacement re-decides from fresh state once (re-evaluating the edit-only gate and default_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_load drops its teardown fence right after _unload_locked and then holds _generate_lock alone 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

  • New test_generate_refuses_when_the_model_was_replaced_since_the_snapshot in test_diffusion_backend.py, using the suite's established fake-pipeline harness: load a model, generate(expected_repo_id="other/model") raises the typed error carrying expected/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 neighboring test_load_generate_unload_gguf harness 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.py 5/5 (non-torch sanity that the package still imports cleanly); both edited modules ast.parse clean.

Fixes #9448

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.
@danielhanchen

Copy link
Copy Markdown
Member

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.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 24a6c0a to your branch. The diagnosis is right and the diffusion.py half was already correct, but the route half needed two fixes before this could go in, plus test coverage for the paths that let them through.

1. openai_error_body(..., status_code = ...)

The helper is openai_error_body(message, *, status = 400, err_type = None, code = None, param = None) in studio/backend/utils/api_errors.py. There is no status_code parameter, so all three rewritten call sites raised TypeError instead of building their body:

  • the edit-only refusal, which is outside the try, so it surfaced as an unhandled 500
  • the ImageActivationShortfallError 400
  • this PR's own second-displacement 503

I reverted those three to status =.

2. expected_repo_id reached an engine that does not take it

The route calls get_active_diffusion_engine(), which returns SdCppDiffusionBackend on a CPU or Apple host. Its generate is keyword-only with a fixed signature and no expected_repo_id, so the new argument raised TypeError, got caught by the route's except Exception, and every /v1/images/generations call on those hosts became 500 Image generation failed.

That is also why 11 tests in test_openai_images_generations_route.py failed: the suite's _FakeBackend.generate has the same fixed signature the native engine does.

openai_images.generate_failed: _FakeBackend.generate() got an unexpected keyword argument 'expected_repo_id'

Rather than special-case the route, I gave the native engine the same parameter and the same in-lock refusal. The window is identical there: generate binds state = self._state under _generate_lock + _lock, exactly like the diffusers path, so a replacement can displace it the same way.

DiffusionModelReplacedError moved to diffusion_families.py, next to DIFFUSION_NOT_LOADED_MSG and DIFFUSION_CANCELLED_MSG (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.py, so from core.inference.diffusion import DiffusionModelReplacedError still works.

Tests added

  • test_generate_refuses_a_replacement_that_committed_while_it_waited: your reported interleaving end to end, not just the guard in isolation. A load is parked inside the construction of the new model, _teardown_waiters == 0 is asserted so the window is genuinely open, a generate blocks on _generate_lock, the load is released, and the generate must be refused rather than denoise on the replacement.
  • test_generate_refuses_a_snapshot_naming_another_model in test_sd_cpp_backend.py, for the native engine.
  • Route tests for the edit-only 400 (which had no coverage at all), the displacement retry re-deriving the new model's steps and guidance, the bounded second displacement, a replacement into an edit-only model, and a backend whose status() carries no repo_id.

Verification

Merge base 489fab4 vs your c71d66e vs 24a6c0a:

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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 23, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +26791 to 26792
if workflows and "txt2img" not in workflows:
raise HTTPException(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 837d1061b5

ℹ️ 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".

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 23, 2026
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 1629ee939a

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@danielhanchen
danielhanchen merged commit da060f0 into unslothai:main Aug 23, 2026
42 of 43 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Images: /v1/images/generations can run a replacement model with the previous model's steps and guidance

2 participants