Repository navigation
Studio: let image generation be stopped - #8219
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 631ad3e393
ℹ️ 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".
| const handleCancelGenerate = useCallback(async () => { | ||
| cancelRequested.current = true; | ||
| try { | ||
| await cancelDiffusionGeneration(); |
There was a problem hiding this comment.
Handle Stop before the backend registers generation
If the user presses Stop immediately after the button appears, the generate fetch may have started but not yet registered _active_generate_cancel; the cancel endpoint then returns {cancelled: false}, which is ignored here. The latch cannot stop this first request because the loop already passed its pre-request check, so the full generation continues despite Stop. Preserve a cancellation request across this startup race, for example by associating it with the generate request or retrying until that request registers or settles.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The window is real in the code but not reachable in a session, and every remedy for it is a worse bug.
Timing: handleGenerate sets busy to generating and issues the POST in the same tick, so the Stop button is painted no earlier than the next frame, while the backend registers _active_generate_cancel at the very top of generate() (diffusion.py, immediately inside _generate_lock under _lock, before any prompt encoding or setup) and the route does nothing but asyncio.to_thread(backend.generate, ...) first. So the gap is one localhost round trip plus a thread handoff, and it has closed before the button a user must see and react to is even on screen. The reverse case, a Stop pressed while another client holds _generate_lock, needs a second concurrent generator and is out of scope here.
The remedies are the problem. A sticky cancel that the next generate() consumes turns a Stop the backend correctly answered false into a cancellation of a later, unrelated generation, which is a call dropped rather than one preserved. A retry-until-registered loop has the same hazard with a timer attached: on a count > 1 run it would land on run i+1, which the latch already stopped by other means. Neither trade is worth closing a gap narrower than a frame.
What is already covered: cancelRequested latches before the POST, so every remaining run of a count > 1 request stops regardless of what the cancel endpoint answered, and the catch around cancelDiffusionGeneration documents exactly the never-landed case. I did take the other item on this PR, the post-denoise recheck, which is the same class of disagreement but genuinely reachable.
|
Browser evidence, since a route returning 200 is not proof the sampler stopped. One headless Chromium session against a live Studio built from this branch,
The gallery was empty before and is still empty, so no cancelled run persisted anything. Run-loop latch, Create with Runs = 3: the button renders as The "no toast" result is a verified negative rather than an absent check. A control run clicked Generate on Inpaint with no mask painted, and the same toast scanner immediately reported Two honest deviations. The Steps slider is capped at 50 in the UI, so the ceiling proved against is 50, not the backend's 100; stopping at step 10 of 50 is still unambiguously mid-sampler. And Z-Image-Turbo denoises fast enough on this card that each run had to be lengthened (larger batch, larger sources) to leave a usable window to click in. The API-level pass in the description used 100 steps and stopped at steps 3 to 5. Reference and Edit are not covered because this model does not advertise them; they share the same handler and the same button. |
The cancel event stayed registered through the compile-cache save, and generate_progress still read active, so the page still offered Stop. A Stop pressed there was answered cancelled = true and then contradicted: generate() returned the images and the route persisted them. A static compile writes a fresh artifact per shape, so that save is not instant. Recheck the event once more before returning, so the two answers agree and a cancelled run leaves no gallery entry.
…executor The recheck still left the event registered across the generation-count update and the two adapter helpers that build the result, so Stop could answer true for a run that then returned its images. Check and deregister under _lock, the same lock cancel_generate takes, so the two cannot interleave. The cancel route also shared the default executor with /images/generate, which occupies a worker for the whole run while it blocks on the serial generate lock, so concurrent generations could leave a Stop queued until the run it was meant to stop had finished. It gets its own small pool, like the status probes above it; not the event loop, since cancelling a native sd.cpp run kills a process tree.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d37d558ca1
ℹ️ 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".
| cancelled = await asyncio.get_running_loop().run_in_executor( | ||
| _CANCEL_EXECUTOR, get_active_diffusion_engine().cancel_generate | ||
| ) |
There was a problem hiding this comment.
Bind cancellation to the requesting generation
With concurrent generation callers, this always cancels the backend's single currently active event rather than the generation owned by the caller. If request A is running while request B is queued on _generate_lock, pressing Stop in B cancels A; B's already-issued request then acquires the lock and continues generating. Pass a generation/request identifier through the generate and cancel endpoints so a queued caller cannot terminate another client's run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. It needs two concurrent generation clients, which is outside what this control is for, and the remedy would change a contract that predates this PR.
/images/generate/cancel is documented as stopping THE in-flight generation, mirroring /video/generate/cancel, and it reaches the same _active_generate_cancel that unload() and a superseding load already set. That is a global control by design, and binding it to a request id would have to change the generate endpoint, the video endpoint that mirrors it, and the unload path, so the three keep agreeing.
In the scenario as described, B is queued and owns no generation yet, so there is nothing of B's to cancel; Stop stopping the run that is actually running is the documented answer, not a misdirected one. B's own later runs are already stopped by the page's latch, which does not depend on the endpoint at all.
Studio drives one generation at a time from the page, so reaching this needs a second tab or an API client generating concurrently, and that same shape is what I declined earlier in this round for the startup race. I would rather leave a global Stop that is honest about being global than add an id handshake across four endpoints for it.
I did take the two concrete items from this round: the native backend's non-atomic deregistration, and the cancel route sharing the generation executor.
…a real error The native backend had the same gap the diffusers one just closed: its final cancel check sat outside the lock that clears the event, so a Stop landing between the two was answered true for a run that then returned its images. /images/generate/cancel resolves through the engine router, so both engines owe the same answer; same locked check-and-deregister there now. On the page, a cancel POST that never landed was treated as handled. The latch suppresses every later error for the run, not just the cancellation sentinel, so an OOM raised after a Stop that the server never heard vanished. Track whether the cancel landed: report the failure when it did not, and let the run report its own error.
|
@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: 40ccb0c73f
ℹ️ 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".
| } catch { | ||
| // The request never landed, so the denoise in flight keeps running. The latch still stops | ||
| // the remaining runs, but the click cannot be treated as handled: say so, and stop it | ||
| // explaining away an error the run raises later. | ||
| cancelFailed.current = true; |
There was a problem hiding this comment.
Treat a lost cancel response as an ambiguous outcome
When the cancel POST reaches the backend and sets the event but its response is dropped by the proxy or connection, this catch incorrectly concludes that the server never received it, sets cancelFailed, and reports that generation is still running. If the original generate request then returns its expected 409, shouldReportGenerateError also exposes the cancellation sentinel as an error because cancelFailed disabled suppression. Fresh evidence versus the earlier cancel-failure comment is that this revision now explicitly equates every fetch rejection with non-delivery, even though the generate API already recognizes that responses can be lost after work reaches the server.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The consequence you name does not happen, so leaving this as is.
shouldReportGenerateError is not gated on stopRequested alone; it falls through to a message test:
if (input.stopRequested) return false;
return !input.message.toLowerCase().includes("cancelled");
So with cancelFailed set and stopRequested therefore passed as false, a 409 carrying DIFFUSION_CANCELLED_MSG ("Diffusion generation was cancelled.") still returns false and is still suppressed. That holds for the native engine too: sd_cpp_backend maps SdCppCancelled to the same sentinel string, so both engines unwind with a message the test catches. The stopRequested branch is the belt to that pair of braces, for a run that unwinds some other way, which is exactly the case where we genuinely do not know whether the stop landed and would rather show the error than swallow it.
What is left is the toast wording overstating non-delivery on a lost response, which is cosmetic and not worth churning the file for. The unambiguous half of that scenario is the retry it enables, and I took that one: cancelDiffusionGeneration now passes retryNetworkErrors: false in 58c8c46.
authFetch retries network errors by default, but this endpoint always targets whichever generation is active now, so a retry firing up to 1.5s after a lost response can land on a run the user started in the meantime and stop that one instead. Cancellation is not retryable the way the idempotent GETs are. The status refresh also only ran on the successful path. When a native cancel is not reflected within its grace window, sd_cpp_server stops the server outright and the backend reloads on the next generate, so a stopped run left the page showing a model that was gone until the next Generate failed with no model loaded. Refresh on every exit instead.
… and post one Stop at a time
A fulfilled cancel was treated as an acknowledged one, so a {cancelled: false}
answered while the route was still persisting still silenced the run. If that
persistence then failed the user got neither an image nor an error. Track the
cancelled field instead: only a confirmed stop explains a later error away.
Each extra Stop click also posted again, and a late duplicate can arrive after
the stopped run settled and target whichever generation is running by then. One
request on the wire at a time; the click still latches, as before.
|
Before/after from two isolated Studio installs, merge base Mid-run, the composer action: After clicking Stop, once Before, the button is a disabled spinner for the whole run and there is no way to end it: still One measurement worth recording, because it surprised me and it shapes what a reviewer should expect. Cancellation latency depends on batch size:
The cancel lands at a step boundary, and a batched step is slow, so at batch 4 the button sits on Stop for around twenty seconds before settling. That is not a bug in the cancel, but it is long enough that a user may well press it twice and think nothing happened. Worth considering an immediate "Stopping..." state on the button. |
A cancel POST outstanding when the run settles (a 401 refresh-and-replay is the slow case) left the guard set, so the next run's own Stop was dropped before it was ever sent. Reset it at the start of each run, beside the other two per-run refs.
The clear ran unconditionally in the finally, so a slow cancel from an earlier run released the guard a later run had set, and a duplicate click could get through behind it. The guard now holds the run token that owns the request, and each cancel clears it only while it still owns it.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd12e7f14f
ℹ️ 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".
| // Per-run, like the two above. A cancel POST still outstanding from the PREVIOUS run (a 401 | ||
| // refresh-and-replay is the slow case) would otherwise leave the guard set and swallow this | ||
| // run's own Stop entirely. | ||
| cancelInFlight.current = null; |
There was a problem hiding this comment.
Keep a pending Stop tied to the previous run
When a Stop request is still awaiting authentication refresh or its response, clearing this guard allows the UI to finish the old generation and start another while the old cancel POST remains live. authFetch retries a 401 after refreshing the session, so that delayed POST can then reach /images/generate/cancel after the new generation becomes active and cancel it instead. This is a single-session scenario, unlike the previously rejected concurrent-client finding; keep Generate unavailable until the pending cancel settles, abort the old request, or bind cancellation to its run.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Taking this one, though not by either of the two remedies I have already declined.
You are right that the 401 refresh-and-replay is a single-session path: the guard I added is correctly scoped now, so no Stop is swallowed, but a request waiting on that refresh genuinely outlives its own run, and the replay targets whatever is active when it lands.
The fix is to make the request abortable rather than to hold Generate hostage or to bind a run id through the protocol. cancelDiffusionGeneration takes an AbortSignal, handleCancelGenerate owns a controller, and the next run aborts any pending cancel as it starts. So a Stop cannot outlive the generation that raised it: if it has not reached the server by the time the next run begins, it never will, and its replay is dropped client-side before it is sent. An abort is silent, since it belongs to a run that is already over.
That closes the last mechanism in this family. The network retry went in 58c8c46, the duplicate clicks in 6b437fb, the guard scoping in fd12e7f and 944e3f9, and with the refresh-and-replay dropped there is nothing left that can put a stale cancel on the wire from this page. I still would not add a request id to the endpoint: that was only ever needed for genuinely concurrent clients, and it would have to change the video endpoint and the unload path to keep the three agreeing.
Frontend suite 1428 passed, typecheck clean, and the backend suite matches origin/main line for line.
| if (isMounted.current) void refreshStatus(); | ||
| setBusy(null); |
There was a problem hiding this comment.
Await native status refresh before enabling Generate
When a resident sd.cpp job does not acknowledge cancellation within its grace period, SdCppServer.img_gen stops the entire server, and the subsequent status call clears the backend's loaded state. This refresh is launched without awaiting it, however, and setBusy(null) immediately re-enables Generate while the page still holds status.loaded === true; a user who starts another generation in that window gets a 409 because the backend no longer has a model. Await the cheap refresh before clearing busy on this exit path, or otherwise keep Generate disabled until the refreshed status is applied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and fixed in 944e3f9. The refresh I added was fired with void, so setBusy(null) ran first and Generate came back while the page still held the pre-cancel status. On the native path where the grace window expires, sd_cpp_server has already stopped the server by then, so that click 409s against a backend with nothing loaded.
It is awaited before setBusy(null) now. It is a local status GET, so the extra wait is not perceptible, and it only applies on the exit path where the button is being re-enabled anyway.
…nerate returns A cancel POST waiting on a 401 refresh-and-replay outlives the run that sent it, and the replay would then target whatever is generating by the time it lands. The request is abortable now, and the next run aborts any pending one as it starts, so nothing on the wire can outlive its own generation. An abort is silent: it belongs to a run that is already over. The status refresh was also fired without awaiting, so Generate came back before the refreshed status applied. On the native path where the cancel grace window expires, sd-server is stopped outright, and clicking Generate in that window 409s against a backend with nothing loaded. Await it first.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |


Fixes #8187.
Video generation can be stopped; image generation could not. Once a run started the only way out was shutting Studio down, which on a bad memory plan means sitting through a generation that is actively swapping the machine.
What was actually missing
The reporter's map said the image path has no backend cancellation and that "nothing reaches the sampling loop". That part is not right, and it makes the fix much smaller than the issue implies.
DiffusionBackend.generate()already creates a per-generationthreading.Event, registers it as_active_generate_cancelunder_lock, checks it in thecallback_on_step_endclosure (setting diffusers'_interrupt), and re-checks it after each chunk so a partial batch is discarded rather than persisted. The nativeSdCppDiffusionBackendhas the same plumbing, and its runner kills the sd-cli process tree on the event. The route even maps the cancelled sentinel to a 409 already.The only things missing were the ways to set that event from outside: nothing but
unload()and a superseding load could reach it, there was no route, and there was no control. So this adds those three, and nothing in the sampler changes.Changes
DiffusionBackend.cancel_generate()andSdCppDiffusionBackend.cancel_generate(), both mirroringVideoBackend.cancel_generate(): set the registered event under_lock, return False when nothing is running.POST /api/inference/images/generate/cancel, resolved through the engine router so it stops a diffusers denoise and a native sd.cpp run alike. Namedimages/...to match every other route on this page rather than thediffusion/...the issue guessed at.countbackend calls, but the backend cancel only reaches the denoise running right now, so without the latch pressing Stop on run 1 of 4 would immediately start run 2. The latch also suppresses the cancelled sentinel's toast, since the user asked for it._is_inference_pathalready excluded*/cancelby construction (it matches onendswith), so the cancel request is not tracked as an inference request and cannot pin the model it just stopped. That is now asserted rather than assumed.Every surface, not just Create
All seven workflows (Create, Transform, Inpaint, Extend, Upscale, plus Reference and Edit) funnel through the one
generate()and the one floating action button, so one control covers all of them. Verified per surface rather than argued:Driven against a live Studio with
unsloth/Z-Image-Turbo-GGUFQ4_K_S on CUDA, 100 steps at 1024x1024, pressing Stop once the sampler was past step 3:{"cancelled": true}{"cancelled": true}{"cancelled": true}{"cancelled": true}{"cancelled": true}The step column is the point: the sampler stopped, it did not finish. A 200 from the route would not have shown that.
What a cancelled run leaves behind
Settled rather than assumed:
images.extend(out), so nothing reaches the persist step.generate()'s outerfinallyon every exit, so the page does not stay stuck at "generating"._interrupt, sopipe()returns normally and the pipeline runs its ownmaybe_free_model_hooks(). This is the better of the two paths: video has no cooperative interrupt on its non-callback families, so it unwinds by exception and has to callmaybe_free_model_hooks()by hand or leave onloaded modules on the GPU. Worth saying out loud since the issue asked us to mirror video and not copy a flaw silently.Tests
cancel_generateacross every workflow, with a stepping fake pipeline that honours_interrupt, asserting the run stopped short of its step count, raised the sentinel, produced no images and cleared progress.Ten mutations, all killed: cancel_generate not setting the event; cancel_generate always reporting idle; the
_interruptset removed from the step callback; the post-chunk cancel check removed; the native cancel not setting its event; the cancel path counted as an inference request; the route's auth dependency dropped; the run loop ignoring the latch; the latch no longer suppressing the toast; and every failure suppressed. Suite green after restoring.Backend suite line sets are identical to the merge-base baseline (86 pre-existing FAILED/ERROR lines either side, 12 more tests passing).
hub/tests304 passed. Frontend typecheck clean, no new lint.