Repository navigation
Replace an in-flight chat model load with the latest pick - #11697
Merged
wasimysaid merged 23 commits intoSep 24, 2026
Merged
Conversation
…jecting it Picking a different model while one is still loading used to be refused with "Another model is already loading", leaving the user to wait or cancel by hand. A pick now supersedes the load in flight. Each attempt claims the single shared load slot with a run token, so a superseded run stops touching shared loading state once a newer selection owns it: terminal cleanup goes through an ownership-checked helper rather than releasing the replacement's refs and lifecycle lease. The replacement cancels the pending load and inherits that run's rollback checkpoint and config, so a failed switch restores the model that was actually working instead of the transient state the cancelled load had applied. Cancellation is scoped to the exact attempt: the run mints one opaque requestId, sends it as load_request_id on its own /load, and cancels with a single /unload carrying the matching cancel_load_request_id. The path is recorded at the load boundary, so a cancel fires only for a load that reached the backend, and an unregistered load is replayed from the backend's cancel tombstone. This replaces the previous unscoped double-unload, which could run both unloads before the old /load registered and let that load start anyway. Clean replacement for unslothai#7109, narrowed to the model-load switching fix only; the unrelated hf-auth, security and transformers-upgrade consent refactors are left out. Regression coverage in studio/frontend/tests/chat-model-load-replacement.test.ts fails on the pinned baseline and passes here.
…ntents after preflight Codex review round 2 on this head found that a replacement could still race the run it superseded, because cancellation released the slot while the old coroutine was parked in an unabortable preflight await, and because a newer pick that could not claim the lifecycle lease left no picker entry behind for the epoch re-check. - ActiveModelLoadRun now carries settledPromise/markSettled; the run's outer finally resolves it as its last act, and cancelLoadRun awaits it before releasing the slot. - Abort checks after the staged-metadata read and after validateModel, so a cancelled coroutine cannot apply its config over the replacement's. - The post-confirmation re-check now also rejects on modelSelectionIntentEpoch, and the adoption path yields to a newer intent. - A superseded run no longer restores its config over the replacement's. - Four new source-level regressions; all four fail on ae03a7f and pass here.
…moved resident model Codex review round 3 found two more preflight-window races on this head. - The replacement loop broke as soon as the picker was empty. Cancellation clears the picker before its /unload settles while the run keeps the slot and the lifecycle lease, so a second pick arriving mid-cancel fell through, failed to acquire the lease, and was silently dropped. The loop now breaks only when neither a picker entry nor an owning run is left, and re-narrows the run before cancelling it. - A replacement cancelling a run that is awaiting its preliminary unloadModel(currentCheckpoint) left the backend with nothing while the store still advertised that checkpoint, and cancelLoadRun reported success. The run now records that its preliminary unload removed the resident model (only the real /unload, not the forced path that leaves it to /load), and cancellation reconciles the checkpoint against the backend before handing the slot over. Two new source-level regressions plus the updated loop assertion; all three fail on dd9e612 and pass here.
Codex review on ccfd293 found four residual state-machine issues in the cancellation/replacement path; all four are fixed here. - P1: a failed scoped /unload reconciled status before the cancelled run had settled. loadModel cannot be aborted, so the still-running /load could make this run's own target resident after that refresh; the aborted coroutine then discards the response and the cancellation finally releases the lease without reading status again, leaving the store naming the old checkpoint while the newly loaded model serves prompts. The failure path now awaits run.settledPromise before refresh(). - P2: the cancellation reconciliation cleared the checkpoint without restoring run.rollbackConfig first. After the preliminary unload, params.checkpoint still named the former resident while the store already held the cancelled target's settings, so clearCheckpoint() persisted that transient state under the former model's durable ID. A new restoreRollbackConfigForClear() puts the rollback snapshot back before the clear. - P2: the replacement inherited only the rollback checkpoint, while the reconciliation had just cleared the store checkpoint. performLoad therefore saw an empty currentCheckpoint, never set previousWasUnloaded, and skipped its compensating reload, leaving no resident model. PendingReplacementRollback now carries residentUnloaded (only when the run really unloaded the former resident and never POSTed its own /load), and both the run's flag and performLoad's rollback gate read it. - P2: the !stopped path returned without clearing pendingReplacementRollback, so the next selection unconditionally inherited a stale checkpoint/config from a failed run whose backend state is explicitly uncertain. The marker is now cleared on the way out. Five new source-level regressions (four for the findings, one updating the run registration assertion). The four finding tests fail on the rebased ccfd293 source and on the pinned upstream-main baseline 541dd1a, and pass on this head.
Round 5 on the previous head raised two P1 and three P2 findings; all five are addressed here. - Retry the latest pick after releasing the preflight lease (P1). A pick arriving while a PREFLIGHT holder owns the lease read null from the gate and returned, and the holder then yielded as stale, so neither selection loaded. The claim is now a bounded wait loop over the store, re-checking this pick's own intent epoch on each wakeup before taking the lease itself. - Wire external picks into replacement cancellation (P1). The hosted/external branch updated the checkpoint and returned without touching the local run, so modelLoading stayed true and the local run's completion overwrote the external capability fields. It now invalidates the local intent first (so a run parked in its preflight yields instead of adopting its status), cancels the in-flight load, re-asserts the external checkpoint the cancelled run's reconciliation may have cleared, and guards every write with the intent check. - Use the inherited config in every rollback path (P2). The decline path and the in-performLoad rollback snapshots still read selection.previousConfig, which names the superseded target, so declining or failing restored the resident model wearing that target's settings. They now read the inherited config. - Preserve the rollback GGUF variant across cancellation (P2). clearCheckpoint() drops activeGgufVariant, so a compensating reload sent gguf_variant: null and restored the wrong artifact. The variant is captured on the run and carried through the inherited rollback record. - Retain the unloaded marker after the load POSTs (P2). The inherited record required loadAttemptPath === null, so a replacement cancelled before its own preliminary unload skipped the compensating reload even though the POST did not put the removed resident back. Each finding has a source-level regression test; all five fail on the previous head and on the pinned upstream baseline, and pass here.
The replacement series derives the rollback target from the cancelled run's inherited loaded state instead of the live store, so the replayed rollback block now reads rollbackState rather than stateBeforeUnload. Those expectations, plus the resident adoption guard lookup that now has earlier residency checks in front of it, predate the change and were asserting a stale identifier and scope. Assertions are unchanged in substance: the same rollback fields are still required to replay the loaded baseline, and the guard is still required to open the block the adoption identity check sits in.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Sep 24, 2026
…spelling (unslothai#11817) unslothai#11697 pinned the rollback branch as the literal 'if (previousWasUnloaded && previousCheckpoint) {'. unslothai#11729, merged first, had already added a third condition (roll back only an answered failure), and the formatter wraps the three-part guard, so on main the pin no longer matches and chat-model-load-replacement.test.ts fails. The merged code keeps both intents. The contract now asks for the guard to open on previousWasUnloaded and previousCheckpoint, allowing further conditions and wrapping. It still fails if the inherited unloaded state leaves the guard, if && becomes ||, or if a different checkpoint is checked.
shaojun
pushed a commit
to shaojun/unsloth
that referenced
this pull request
Sep 29, 2026
…11697) * Fix chat model load switching: replace the pending load instead of rejecting it Picking a different model while one is still loading used to be refused with "Another model is already loading", leaving the user to wait or cancel by hand. A pick now supersedes the load in flight. Each attempt claims the single shared load slot with a run token, so a superseded run stops touching shared loading state once a newer selection owns it: terminal cleanup goes through an ownership-checked helper rather than releasing the replacement's refs and lifecycle lease. The replacement cancels the pending load and inherits that run's rollback checkpoint and config, so a failed switch restores the model that was actually working instead of the transient state the cancelled load had applied. Cancellation is scoped to the exact attempt: the run mints one opaque requestId, sends it as load_request_id on its own /load, and cancels with a single /unload carrying the matching cancel_load_request_id. The path is recorded at the load boundary, so a cancel fires only for a load that reached the backend, and an unregistered load is replayed from the backend's cancel tombstone. This replaces the previous unscoped double-unload, which could run both unloads before the old /load registered and let that load start anyway. Clean replacement for unslothai#7109, narrowed to the model-load switching fix only; the unrelated hf-auth, security and transformers-upgrade consent refactors are left out. Regression coverage in studio/frontend/tests/chat-model-load-replacement.test.ts fails on the pinned baseline and passes here. * Hold the load slot until a cancelled run unwinds; reject superseded intents after preflight Codex review round 2 on this head found that a replacement could still race the run it superseded, because cancellation released the slot while the old coroutine was parked in an unabortable preflight await, and because a newer pick that could not claim the lifecycle lease left no picker entry behind for the epoch re-check. - ActiveModelLoadRun now carries settledPromise/markSettled; the run's outer finally resolves it as its last act, and cancelLoadRun awaits it before releasing the slot. - Abort checks after the staged-metadata read and after validateModel, so a cancelled coroutine cannot apply its config over the replacement's. - The post-confirmation re-check now also rejects on modelSelectionIntentEpoch, and the adoption path yields to a newer intent. - A superseded run no longer restores its config over the replacement's. - Four new source-level regressions; all four fail on ae03a7f and pass here. * Wait for a cancelling run after its picker is cleared; reconcile a removed resident model Codex review round 3 found two more preflight-window races on this head. - The replacement loop broke as soon as the picker was empty. Cancellation clears the picker before its /unload settles while the run keeps the slot and the lifecycle lease, so a second pick arriving mid-cancel fell through, failed to acquire the lease, and was silently dropped. The loop now breaks only when neither a picker entry nor an owning run is left, and re-narrows the run before cancelling it. - A replacement cancelling a run that is awaiting its preliminary unloadModel(currentCheckpoint) left the backend with nothing while the store still advertised that checkpoint, and cancelLoadRun reported success. The run now records that its preliminary unload removed the resident model (only the real /unload, not the forced path that leaves it to /load), and cancellation reconciles the checkpoint against the backend before handing the slot over. Two new source-level regressions plus the updated loop assertion; all three fail on dd9e612 and pass here. * Fix the four rollback/cancellation findings from Codex review round 4 Codex review on ccfd293 found four residual state-machine issues in the cancellation/replacement path; all four are fixed here. - P1: a failed scoped /unload reconciled status before the cancelled run had settled. loadModel cannot be aborted, so the still-running /load could make this run's own target resident after that refresh; the aborted coroutine then discards the response and the cancellation finally releases the lease without reading status again, leaving the store naming the old checkpoint while the newly loaded model serves prompts. The failure path now awaits run.settledPromise before refresh(). - P2: the cancellation reconciliation cleared the checkpoint without restoring run.rollbackConfig first. After the preliminary unload, params.checkpoint still named the former resident while the store already held the cancelled target's settings, so clearCheckpoint() persisted that transient state under the former model's durable ID. A new restoreRollbackConfigForClear() puts the rollback snapshot back before the clear. - P2: the replacement inherited only the rollback checkpoint, while the reconciliation had just cleared the store checkpoint. performLoad therefore saw an empty currentCheckpoint, never set previousWasUnloaded, and skipped its compensating reload, leaving no resident model. PendingReplacementRollback now carries residentUnloaded (only when the run really unloaded the former resident and never POSTed its own /load), and both the run's flag and performLoad's rollback gate read it. - P2: the !stopped path returned without clearing pendingReplacementRollback, so the next selection unconditionally inherited a stale checkpoint/config from a failed run whose backend state is explicitly uncertain. The marker is now cleared on the way out. Five new source-level regressions (four for the findings, one updating the run registration assertion). The four finding tests fail on the rebased ccfd293 source and on the pinned upstream-main baseline 541dd1a, and pass on this head. * Fix the five rollback/preflight findings from Codex review round 5 Round 5 on the previous head raised two P1 and three P2 findings; all five are addressed here. - Retry the latest pick after releasing the preflight lease (P1). A pick arriving while a PREFLIGHT holder owns the lease read null from the gate and returned, and the holder then yielded as stale, so neither selection loaded. The claim is now a bounded wait loop over the store, re-checking this pick's own intent epoch on each wakeup before taking the lease itself. - Wire external picks into replacement cancellation (P1). The hosted/external branch updated the checkpoint and returned without touching the local run, so modelLoading stayed true and the local run's completion overwrote the external capability fields. It now invalidates the local intent first (so a run parked in its preflight yields instead of adopting its status), cancels the in-flight load, re-asserts the external checkpoint the cancelled run's reconciliation may have cleared, and guards every write with the intent check. - Use the inherited config in every rollback path (P2). The decline path and the in-performLoad rollback snapshots still read selection.previousConfig, which names the superseded target, so declining or failing restored the resident model wearing that target's settings. They now read the inherited config. - Preserve the rollback GGUF variant across cancellation (P2). clearCheckpoint() drops activeGgufVariant, so a compensating reload sent gguf_variant: null and restored the wrong artifact. The variant is captured on the run and carried through the inherited rollback record. - Retain the unloaded marker after the load POSTs (P2). The inherited record required loadAttemptPath === null, so a replacement cancelled before its own preliminary unload skipped the compensating reload even though the POST did not put the removed resident back. Each finding has a source-level regression test; all five fail on the previous head and on the pinned upstream baseline, and pass here. * fix(studio): preserve rollback access during model replacement * fix(studio): preserve queued picks and rollback launch state * fix(studio): track upgrade-triggered model unloads * fix(studio): restore resident config after Hub auth decline * fix(studio): invalidate pending loads on repeated external picks * fix(studio): clear rollback after resident status adoption * fix(studio): settle rollback after replacement cancellation * fix(studio): reconcile model replacement rollback * fix(studio): restore cancelled run reconciliation * fix(studio): reconcile unloaded rollback on credential decline * fix(studio): restore cancelled load config on external swap * fix(studio): resnapshot config after compensation reload * test(studio): align rollback assertions with inherited rollback state The replacement series derives the rollback target from the cancelled run's inherited loaded state instead of the live store, so the replayed rollback block now reads rollbackState rather than stateBeforeUnload. Those expectations, plus the resident adoption guard lookup that now has earlier residency checks in front of it, predate the change and were asserting a stale identifier and scope. Assertions are unchanged in substance: the same rollback fields are still required to replay the loaded baseline, and the guard is still required to open the block the adoption identity check sits in. * Update chat contract harness for replacement lifecycle * Discard declined replacement rollback for resident model * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim duplicate model-switch contract test * Condense model-switch regression contracts --------- Co-authored-by: imagineer99 <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun
pushed a commit
to shaojun/unsloth
that referenced
this pull request
Sep 29, 2026
…spelling (unslothai#11817) unslothai#11697 pinned the rollback branch as the literal 'if (previousWasUnloaded && previousCheckpoint) {'. unslothai#11729, merged first, had already added a third condition (roll back only an answered failure), and the formatter wraps the three-part guard, so on main the pin no longer matches and chat-model-load-replacement.test.ts fails. The merged code keeps both intents. The contract now asks for the guard to open on previousWasUnloaded and previousCheckpoint, allowing further conditions and wrapping. It still fails if the inherited unloaded state leaves the guard, if && becomes ||, or if a different checkpoint is checked.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replacement for #7405, narrowed per its review; supersedes the earlier #7109.
While model A is still loading, picking model B was refused with "Another model is
already loading" — the user had to wait for A or cancel it by hand before B could be
selected. A pick now supersedes the load in flight.
What changed
slot with a run token. Async callbacks from a superseded run prove they still own the
slot before touching shared loading state, so a cancelled load cannot clobber the run
that replaced it.
stop a load that is already POSTing, so the replacement awaits the backend's answer
before claiming the slot, and preserves the working checkpoint as its rollback target.
requestId,sends it as
load_request_idon its own/load, and cancels with a single/unloadcarrying the matching
cancel_load_request_id. The target path is recorded at the loadboundary, so a cancel fires only for a load that actually reached the backend, and a
load whose registration has not landed yet is replayed from the backend's cancel
tombstone.
That last point replaces the previous unscoped double-unload. Both of those unloads could
run before the old
/loadregistered its target, letting the superseded load start anyway— the exact race the cancellation was meant to close.
final head, a load cancelled by declining the Hub-credential prompt discards its own
inherited rollback state instead of leaving a marker that a later replacement could
adopt, so the resident model keeps its settings.
Scope
Frontend only. The unrelated hf-auth, security and transformers-upgrade consent-dialog
refactors from the earlier attempt are deliberately left out, per review.
Verification
Live end-to-end Studio check at the final head, real GGUF files, CPU-only, with the exact
upstream
maintip as the paired control. Same scene, same clicks, one scene revision onboth sides:
f5109b58(before)e034d578(after)loading=["model-a"]loading=["model-a"]falsetrue"Another model is already loading"/"Wait for it to finish or cancel it first."model-amodel-b[][]Before — the pick is refused; the trigger still reads

model-a GGUF · Q6_K:After — the same pick replaces the load and settles on B:

Each image is a 3024x1056 side-by-side, left =
main, right = head. Full evidence,reproduction steps and hash manifest:
acceptance/203-e034d578.Source-level checks re-run at
e034d578:studio/frontend/tests/chat-model-load-replacement.test.ts— 42/42 pass on this head;the same file against the pinned
mainsource gives 1 pass / 41 fail (the one pass isa harness-only snapshot case), so the new coverage is genuinely red on
main.tests/studio/test_new_chat_context_recount.py,test_model_picker_contracts.py,test_multi_chat_prompt_queue_contract.py— 266 passed, 1 skipped.npm run typecheck— clean (exit 0).The fork's older frontend CI startup budget is red (5,606.9 KiB raw versus its 5,595.7 KiB cap). On the paired upstream-main build the same metric is 5,601.4 KiB, a 5.5 KiB head increase; upstream
mainhas since raised its cap to 5,810.5 KiB. Other fork CI failures remain under triage; these focused checks and live results are not a claim that all CI is green.Credit: @Imagineer99 for the original implementation and investigation.