Skip to content

Studio: queue media generation behind model teardown - #8866

Merged
wasimysaid merged 20 commits into
unslothai:mainfrom
divagr18:fix-studio-generation-teardown-race
Aug 21, 2026
Merged

wasimysaid merged 20 commits into
unslothai:mainfrom
divagr18:fix-studio-generation-teardown-race

Conversation

@divagr18

Copy link
Copy Markdown
Contributor

Summary

Fixes #8309.

Studio image and video generation could race with a model replacement or unload. Because Python lock acquisition is not FIFO, a newly queued generation could acquire the generation lock after teardown had been reserved but before teardown completed.

This caused generation requests to incorrectly report that they were cancelled or, for video replacements, observe the temporary unloaded state while the replacement model was still being constructed.

Changes

  • Add condition-based generation admission to the image and video backends.
  • Queue generation while teardown reservations are active.
  • Keep standard video replacement reservations active until the replacement commits or fails.
  • Wake queued generations only after every teardown reservation has drained.
  • Preserve existing explicit user-cancellation behavior.
  • Report the truthful model-not-loaded error after unload or failed replacement.
  • Add invariant checks for teardown reservation underflow.

Regression coverage

Added deterministic threaded tests covering:

  • Generation waiting behind multiple teardown reservations.
  • Successful generation against a replacement model.
  • Generation after unload reporting model-not-loaded.
  • Teardown failures draining their reservations.
  • Video background generation reaching a completed terminal state after replacement.
  • Explicit cancellation behavior remaining unchanged.

Validation

  • 226 runnable video backend tests passed.
  • 29 focused teardown and cancellation tests passed.
  • Ruff checks passed.
  • Python compilation checks passed.
  • git diff --check passed.

@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: c90dcd4cca

ℹ️ 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 thread studio/backend/core/inference/video.py Outdated
if self._state is None and self._teardown_waiters == 0:
raise RuntimeError(VIDEO_NOT_LOADED_MSG)
state = self._state
if state is not None:

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 Preserve request validation while a replacement is loading

When a standard replacement has torn down the old pipeline but not committed the new one, _state is None while _teardown_waiters is nonzero, so this conditional skips _resolve_keyframes, _resolve_references, and _resolve_flow_shifts. Consequently malformed image data, unsupported references, or invalid flow shifts receive a successful /video/generate response instead of the route's synchronous 400/422; the daemon worker only reports a failed job later through polling. Queuing behind replacement should not bypass the input-validation contract.

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.

studio/backend/core/inference/video.py is no longer part of this PR. 832fdfe scoped it down to the diffusion admission fix, so there is no code here for the _resolve_keyframes / _resolve_references / _resolve_flow_shifts skip to apply to. Not judged on the merits; it belongs on the video backend change when that lands as its own PR.

@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: c0a1a3cc6d

ℹ️ 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 thread studio/backend/core/inference/video.py Outdated
Comment on lines 4848 to 4849
if self._state is None and self._teardown_waiters == 0:
raise RuntimeError(VIDEO_NOT_LOADED_MSG)

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 Require an active replacement before accepting an unloaded job

When an unload supersedes a standard replacement after that replacement has torn down the old state, _loading is cleared but the stale load can retain a teardown reservation until its lengthy construction reaches the next token check. During that interval _state is None and _teardown_waiters is nonzero, so /video/generate is accepted with no incoming model, waits behind the stale worker, and eventually fails through polling with VIDEO_NOT_LOADED_MSG instead of returning the synchronous 409. Treat the waiter as a queueable replacement only when _loading still describes an active load.

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.

Also on video.py, which 832fdfe removed from this PR. The _loading check belongs on the video backend change when it lands separately.

Comment thread studio/backend/core/inference/video.py Outdated
Comment on lines +5111 to +5115
if _defer_shape_validation or (
_validated_state is not None and state is not _validated_state
):
validate_video_request_shape(
fam, width = width, height = height, num_frames = num_frames

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 Revalidate all conditioning after the admitted model changes

If begin_generate() validates against the currently loaded family and a replacement reserves teardown before the worker acquires the generation slot, the job now intentionally survives and runs on the replacement. The new _validated_state mismatch branch is fresh evidence that this ordering is handled, but it repeats only shape validation; keyframes, references, and flow shifts are first checked against the old family and are checked against the replacement only later inside the daemon worker. Inputs unsupported by the replacement therefore receive a successful generate response and fail asynchronously rather than preserving the route's synchronous 400/422 contract, so the full conditioning validation must be repeated when the state identity changes.

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.

Also on video.py, which is no longer in this PR after 832fdfe. Conditioning revalidation on a state-identity change is for the video backend PR.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits the fence in studio/backend/core/inference/diffusion.py where a generate arriving during a load-over-resident is refused with a cancellation message that is not true, and queueing it behind the teardown is the right direction. Could you split the video.py reservation decorator and the generate_progress reporting change out so the diffusion admission fix can be reviewed on its own?

@divagr18

Copy link
Copy Markdown
Contributor Author

Split out the video changes and progress reporting so this is just the diffusion race fix now. A generate that arrives during teardown waits instead of incorrectly coming back as cancelled.

@oobabooga

Copy link
Copy Markdown
Member

Pushed e4b3d3e to this branch rather than sending it back for another round. Revert it if you would rather do it differently.

Two things in the admission path. A generation that yielded the slot to a teardown parked on a threading.Condition whose lock is _lock, and begin_load holds _lock for the whole model construction, so Condition.wait() could not return and Stop could not land until the load finished. test_cancel_wakes_generation_waiting_for_replacement misses this because there the generation never wins _generate_lock and stays in the responsive spin. _teardown_drained is now a level-triggered Event, so a parked request waits without any lock.

Second, _generation_slot registered every request in _queued_generate_cancels on entry, so Stop for the denoising request also failed an unrelated request that was only serialized behind it on _generate_lock, with the same cancel sentinel this PR is removing. Registration is now scoped to requests waiting while nothing is denoising, which is the case where the wait really is a model transition.

Both have regression tests that fail on 832fdfe. test_diffusion_backend.py and test_diffusion_routes.py pass (420), as do the engine router, OpenAI image route, sd.cpp backend, batched, LoRA and gallery suites (273).

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@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: 0af55e6698

ℹ️ 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 +5381 to 5383
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._state

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 Recompute defaults after the replacement is admitted

When /v1/images/generations reads the old model status at routes/inference.py:24106-24125 and a replacement reserves teardown before this request acquires the slot, the new context waits and then binds state to the replacement at line 5383, but it retains the workflow decision and steps/guidance derived from the old model. For example, replacing Z-Image Turbo with Lumina can run the latter with 9 steps and guidance 0 instead of 50/4, while edit-only/text-to-image transitions can incorrectly return 400 or 500. Revalidate the workflow and recompute model defaults against the state actually admitted for generation.

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.

The mechanism is real, but it is not this PR's, so I am not fixing it here.

begin_load drops its teardown reservation immediately after _unload_locked, so on main _teardown_waiters is already 0 for the whole model construction. A generate arriving in that window does not hit the refusal; it blocks on _generate_lock and then binds state to whatever committed. I ran a probe against the merge-base diffusion.py (8059be6): load old_dir, block a replacement to new_dir inside _FakeTransformer.from_single_file with the fence already at 0, issue a generate, release the load. The result comes back with repo_id == new_dir on unmodified main. So a request already binds to a model the route did not validate against, and the stale default_generation_params at routes/inference.py:24123 already applies. This PR only makes the short fence window behave like the long construction window that behaved that way already.

Fixing it means resolving the per-model defaults and the edit-only refusal from the state actually admitted rather than from a status() read taken before the call, which is a contract change to generate() and to both image routes. That is the scope that was deliberately split out of this PR at 832fdfe. It deserves its own issue against the route, not a widening of this one.

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.

Filed as #9448, with the merge-base reproduction.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: b44b95f143

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

@oobabooga

Copy link
Copy Markdown
Member

@codex review

@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: 1af93d7044

ℹ️ 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 +5909 to +5913
cancels = set(self._queued_generate_cancels)
if not cancels:
return False
cancel.set()
for cancel in cancels:
cancel.set()

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 Preserve serialized requests during slot handoff

When one generation finishes and another request is waiting on _generate_lock, there is a handoff window after _generation_owns_slot becomes false but before the waiter registers itself as active. A concurrent cancel_generate() enters this branch, treats the waiter as if it were queued behind a model transition, and sets its event, so the unrelated request fails with DIFFUSION_CANCELLED_MSG even though no teardown exists. Distinguish transition-blocked waiters from ordinary serialized requests before cancelling this set.

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.

Rejecting this one, and the reason is partly your own earlier round.

The window is real but it is the handoff itself. The exiting generation clears _generation_owns_slot and releases _generate_lock inside one _generation_cancel_lock section, so the gap is only the time the waiter needs to return from its pending acquire, take _lock and take the cancellation lock: microseconds, and no user-visible state exists in it. Reaching it needs two concurrent image requests from different callers plus a Stop landing inside that gap on the exact interleaving where one has just finished.

More to the point, in that state nothing is denoising, no teardown is reserved and the slot is free, which is indistinguishable from "one request is pending and the user pressed Stop". Any rule that spares the waiter there also stops answering Stop for a lone pending request, which is the #8309 behaviour this PR exists to provide.

The remedy you suggest, distinguishing transition-blocked waiters from ordinary serialized ones, is the per-waiter classification 3825407302 asked me to remove two rounds ago, for the reason that a waiter asleep in its timed acquisition cannot reclassify itself. Rebuilding it needs Lock.locked(), which is racy by definition, plus a mirror of the reservation count under the cancellation lock, and the reserved-but-not-yet-acquired sliver would still be open. That trades one microsecond window for another and puts back the state the last simplification removed.

Worth noting that this same logic, byte for byte, was approved as b44b95f143 one round earlier: 1af93d7 changes only comments (AST-gated, code unchanged).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fixed in b142b6d: model transitions now publish slot ownership separately, so Stop only cancels queued requests while a teardown is reserved or a transition actually owns the slot. Added a deterministic release-to-admission handoff regression; 323 diffusion backend tests and 101 diffusion route tests pass.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 1af93d7044

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

@wasimysaid

Copy link
Copy Markdown
Collaborator

Confirmed the slot-handoff race in #8866 (comment) on 1af93d704402a777565dfc7975efe748e4c623f3 with a deterministic threaded reproducer. During the release-to-admission handoff, cancel_generate() can see no active owner while an ordinary serialized waiter is still published, return true, and cancel that unrelated request even though no model teardown is active.

I’m preparing the minimal fix and regression coverage now, then I’ll rerun the diffusion suite and follow up with the pushed commit.

@wasimysaid

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: bf92e0e9a9

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

@wasimysaid

Copy link
Copy Markdown
Collaborator

Follow-up: the slot-handoff fix is now on bf92e0e9a952933a56c3804a7bc319b42a363e26, and Codex reviewed that exact head with no major issues.

Fresh-main validation on wasimysaid#163 completed with 27 successful checks and 2 expected skips. This includes the full CPU repo suite, Linux/macOS/Windows startup, lint, API/auth, UI/browser, Core dependency matrices, Windows/macOS GGUF inference, and the 21-minute macOS Studio/API/update/inference job. The only non-success was the recurring Python 3.13 backend job timeout: it reached 95%, then was cancelled at the workflow's 45-minute limit without a test failure. The changed diffusion backend suite passes locally on Python 3.13 (323 passed), including the deterministic handoff regression.

@wasimysaid
wasimysaid merged commit 1bb5088 into unslothai:main Aug 21, 2026
1 check 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: first Generate after a model swap fails with 409 "Diffusion generation was cancelled."

4 participants