Skip to content

Fix chat model load switching - #7109

Closed
Imagineer99 wants to merge 126 commits into
unslothai:mainfrom
Imagineer99:fix/chat-model-load-switching
Closed

Imagineer99 wants to merge 126 commits into
unslothai:mainfrom
Imagineer99:fix/chat-model-load-switching

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes chat model switching while a local/GGUF model load is already in flight.

The important behavior change is in the central selectModel path: when a different model or GGUF variant is selected during an in-flight load, the UI now aborts the pending frontend load, awaits the backend unload call, and then continues with the newly selected model. Duplicate clicks for the exact same pending model still no-op.

This also guards staged auto-load download callbacks so stale download events from a previously staged repo cannot auto-load or abandon the current staged model after the user switches picks.

Root cause

There were two related frontend/backend state issues:

  • Some model selection paths, especially downloaded GGUF variant selection, call selectModel directly. The earlier staged-selection handling was not enough because selectModel had its own in-flight guard that only showed "Another model is already loading" and returned.
  • useRepoDownload stores latest callback handlers in refs. After retargeting the hook to a different repo, an old subscription could call the newest handlers unless the subscription verified it still matched the current repo.

Together, those paths can make the UI look stuck on a prior load/download and reject a user switch even though the correct action is to stop the old load and proceed with the new selection.

Validation

  • Reproduced the failure in the real chat UI with Studio backend running and Playwright installed in an isolated /tmp package.
  • Before the central selectModel fix, the mocked downloaded-GGUF UI repro selected model A, switched to model B while A was loading, showed the "Another model is already loading" path, and never called unload/load for B.
  • After the fix, the same repro observed: load-start model-a, unload model-a, validate model-b, load-start model-b, with no "Another model is already loading" toast.
  • npm --prefix studio/frontend run typecheck
  • npm --prefix studio/frontend run build
  • git diff --check
  • Targeted eslint on changed hook/download files. Only existing warning remained in use-chat-model-runtime.ts for an unnecessary setParams dependency.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request improves model loading, cancellation, and download subscription handling in the chat interface. Key changes include refactoring cancelLoading to be asynchronous, automatically attempting to cancel in-flight loads upon new selections, cleaning up auto-load references, and preventing stale download listener callbacks. Feedback highlights a potential race condition in selectModel where a new load could be initiated while a previous model's unload is still in flight, suggesting a defensive check on store.modelLoading.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Imagineer99 and others added 27 commits July 13, 2026 19:20
…on Python 3.14+) (unslothai#7186)

* Studio: don't apply nest_asyncio on plain CLI starts (breaks asyncio on Python 3.14+)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip nest_asyncio on Python 3.14+ so notebook and embedded Studio starts also work

* Tighten the nest_asyncio gate comment

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
…rs_bias (unslothai#7189)

* Propagate fp8 block_size before the early return in get_lora_parameters_bias

get_lora_parameters_bias set the fp8 block_size on W/W_quant only after the
disable_adapters/merged early return, so on the merged or disabled path (merged
inference, DPO reference model) a block-fp8 weight lost its real block_size and
downstream fp8 kernels fell back to [128, 128]. The non-bias sibling
get_lora_parameters already sets block_size before its early return; move the
block so both behave the same.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Guard the fp8 block_size against a missing quant state

A decompressed compressed-tensors layer keeps quant_method == "fp8" while its
weight is back to bf16, so it has no quant state and get_lora_parameters_bias
must still return W_quant None for fast_linear_forward to fall back to a plain
matmul. Only attach block_size when a quant state was actually found.

* Guard the sibling get_lora_parameters fp8 block_size against a missing quant state

Mirror the get_lora_parameters_bias guard so a decompressed compressed-tensors
layer (quant_method fp8, bf16 weight, no quant state) does not raise
AttributeError on the fused-LoRA path. Add a CPU-only regression test.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* feat(studio): expose opt-in MCP control plane

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Harden Studio MCP tools: byte-safe auth, page clamping, forward export/checkpoint fields

Follow-up hardening on the opt-in MCP control plane. All changes are additive
and backwards compatible.

- BearerTokenMiddleware now compares the Authorization header on raw bytes.
  A non-ASCII bearer value previously reached str-based hmac.compare_digest,
  which raises TypeError and surfaced as a 500 instead of a clean 401. The
  constructor also rejects an empty or whitespace-only token so an empty token
  can never match an empty "Bearer " header.
- MCP tools call the route functions directly, which skips FastAPI Query
  validation. list_training_runs and get_recipe_job_dataset now clamp limit and
  offset to the same bounds the HTTP routes enforce (a negative SQLite LIMIT
  otherwise means "no limit").
- export_gguf forwards hf_token (the backend rejects a Hub upload without it),
  accepts a list of quantization methods, and exposes imatrix / imatrix_path so
  the IQ low-bit quants are reachable.
- load_checkpoint forwards hf_token and approved_remote_code_fingerprint so
  gated checkpoints and the remote-code approval retry work. Its docstring is
  corrected: the export backend coexists with training and inference rather than
  freeing GPU work.
- start_training passes via_api_key=False explicitly instead of relying on the
  unfilled Depends default.

Tests: add coverage for non-ASCII and empty-token auth, the correct-token pass
through, non-http scope pass through, pagination clamping, and the forwarded
export/checkpoint fields.

* Harden Studio MCP: cap /mcp request bodies, reject unusable tokens, fix docs

Follow-up hardening from a full review pass. All changes are additive and
backwards compatible.

- Add "/mcp" to _BODY_PROTECTED_PREFIXES so MaxBodyMiddleware enforces the same
  request-body cap it already applies to every other write endpoint (/api/train,
  /api/export, /api/data-recipe, ...). The MCP endpoint accepts authenticated
  POST tool-call bodies; without this an authenticated client could send an
  unbounded body. The middleware only buffers the request body (not the SSE
  response), so streaming is unaffected, and the 500MB default cap never affects
  a real JSON-RPC tool call (verified live).
- Reject a non-ASCII UNSLOTH_STUDIO_MCP_TOKEN at construction. HTTP header values
  are ASCII, so a non-ASCII token cannot be sent by a standard client and would
  silently lock out the endpoint; fail fast instead.
- MCP.md: document the canonical /mcp/ endpoint and note that /mcp redirects to
  it, so clients that do not follow redirected POSTs still connect.

Tests: add non-ASCII token rejection coverage.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten MCP server comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
…unslothai#7194)

* fix(tokenizer): check for tokenizer.model after saving it, not before

`fix_sentencepiece_tokenizer` creates its temporary directory, then returns
early unless that directory already contains a tokenizer.model:

    if not os.path.exists(temporary_location):
        os.makedirs(temporary_location)          # fresh, empty

    if not os.path.isfile(f"{temporary_location}/tokenizer.model"):
        return new_tokenizer                     # always true

    old_tokenizer.save_pretrained(temporary_location)   # writes that file

The file only appears on the line after the check, so the guard is always
true and the body never runs. Nothing else writes that path either --
`convert_to_fast_tokenizer` saves into a per-name subdirectory, not
`{temporary_location}/tokenizer.model`.

Both call sites are in `get_chat_template` and are commented "Must fix the
sentence piece tokenizer since there's no tokenizer.model file!" -- the
guard defeats the exact intent the caller states. The effect is silent: the
caller still gets a working `new_tokenizer`, but the sentencepiece piece
rename is skipped, so the mapped token (e.g. the eos token remapped to
`<|im_end|>`) is missing from tokenizer.model and GGUF/llama.cpp exports
carry the old piece.

`check_if_sentencepiece_model` in save.py does the same probe in the right
order -- makedirs, save_pretrained, then isfile. Match it.

Tests are added under tests/saving/ next to the existing sentencepiece
coverage, and to the two Bucket-A lists in consolidated-tests-ci.yml, since
Repo tests (CPU) --ignores tests/saving and these need protobuf.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Clear stale tokenizer.model before the sentencepiece guard

The guard now runs after old_tokenizer.save_pretrained, but the default
temporary_location is a fixed reusable directory. A fast-only tokenizer writes
no tokenizer.model, so a stale file from an earlier sentencepiece call could
pass the guard and patch the wrong model (e.g. mixing models in one process,
like a long-running server). Remove any existing tokenizer.model first, and add
a regression test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Empty the reusable sentencepiece scratch directory each call

The final AutoTokenizer.from_pretrained reloads the whole temporary_location, so
removing only a stale tokenizer.model still let other artifacts from a previous
tokenizer (added_tokens.json, chat template, etc.) leak into the reload when the
default reusable directory is used across models in one process. Recreate the
directory instead, and add a regression test for the leaked-artifact case.

* Clear only top-level scratch files, keep subdirectories

Recreating the whole reusable directory deleted the {name} subtree that
convert_to_fast_tokenizer stores a converted tokenizer's source vocab in, so
old_tokenizer.save_pretrained could not copy tokenizer.model and the guard
returned the tokenizer unpatched for those legacy converted tokenizers. Remove
only stale top-level files (all the final reload reads) and leave subdirectories
intact. Add a regression test for the converted-source subdirectory.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the current tokenizer's own source vocab when clearing

On a repeated get_chat_template(map_eos_token=True) call, the returned tokenizer's
vocab_file points back at the top-level tokenizer.model, and the cleanup deleted
that source before old_tokenizer.save_pretrained could re-emit it, so the guard
returned the tokenizer unpatched. Skip removing the old tokenizer's own source
vocab while still clearing stale files from a different tokenizer, and add a
regression test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Use a per-call temporary directory for the sentencepiece fix

The scratch directory defaulted to a single shared path, so concurrent or repeated
get_chat_template(map_eos_token=True) calls could delete or overwrite each other's
tokenizer.model between save and reload (tripping the piece assertion or reloading
the wrong model), and stale files from an earlier tokenizer could leak into the
reload. Work in a unique per-call subdirectory instead: this isolates every call
without deleting anything the caller owns, and replaces the earlier per-file cleanup.
Tests updated to read the patched model from the reloaded directory and to cover
isolation and source-vocab preservation.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pass only the applied token mappings into the sentencepiece fix

get_chat_template mirrors token remaps into tokenizer.model via
fix_sentencepiece_tokenizer, but two caller paths passed a mapping that did not
match what they wrote to the fast tokenizer JSON, so once the sentencepiece patch
runs the model and JSON disagree:
- the mapped-token path skipped entries whose target already existed but still
  passed the full mapping, renaming a piece the JSON never changed;
- the EOS-swap path swapped both tokens in the JSON but passed only one direction,
  leaving two stop_word pieces and no old EOS piece.
Pass the applied mapping (and both swap directions) instead. Add regression tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten sentencepiece guard comments

* Add SPDX license identifier to sentencepiece guard test

* Reclaim the per-call sentencepiece scratch directory

The per-call tempfile.mkdtemp fixed the shared-directory race but never cleaned
up, so a long-running process leaked one scratch dir per call. The dir cannot be
deleted eagerly for sentencepiece tokenizers because the returned tokenizer's
vocab_file points into it (a later save_pretrained copies the patched
tokenizer.model from there). Reclaim it correctly instead: remove the dir right
away on the fast-only path (the returned tokenizer never references it), and
attach a weakref.finalize so the sentencepiece dir is removed once its tokenizer
is garbage collected. Add regression tests for both.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the scratch-dir reclaim comment

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
* Stabilize Studio regression tests

Rebuild on current main. Restore the set-membership sidebar account-block matcher
(unslothai#6647, which fixed the same order-sensitive regex, was reverted on main, so the
guard is failing on main again) and keep the watchdog replacement-race fix, whose
blocked-watchdog stub now waits without a timeout so a superseded watchdog stays
alive until cleanup regardless of scheduler load.

* Tighten the blocked-watchdog stub comment

---------

Co-authored-by: Daniel Han <[email protected]>
…nslothai#7195)

* fix(dataprep): skip .jsonl lines that are valid JSON but not objects

`_read_file_by_format` json.loads each line and hands the result to
`_extract_text_from_json`, which assumes a dict:

    for field in self._TEXT_FIELDS:
        if field in data and isinstance(data[field], str):

A JSON line does not have to be an object -- `"context"`, `["text"]` and
`42` are all valid JSON. For those, `field in data` stops being a key
lookup and becomes a substring/membership test, so `data[field]` raises:

    "context"        -> "text" in "context" is True (substring!)
                     -> TypeError: string indices must be integers
    ["text", "foo"]  -> TypeError: list indices must be integers
    42               -> TypeError: argument of type 'int' is not iterable

The TypeError escapes past `except json.JSONDecodeError: continue`, so the
whole load dies on one odd line.

That except clause is also the tell: a *malformed* line is already skipped
gracefully. A *well-formed* line that happens not to be an object should be
too -- it carries no text either way. This makes the two agree.

Reachable from `unsloth-cli.py:253` (`--dataset foo.jsonl` auto-detect) and
`RawTextDataLoader` is exported from `unsloth/__init__.py`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Slim the non-object jsonl regression test and shorten the guard comment

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
…nslothai#7230)

* fix(studio): equal padding in dataset source segmented control

* fix(studio): scope dataset source pill layoutId per component instance
The Connections form hid the API key field for the Ollama preset, which
blocked Ollama cloud (it requires a key). Show the optional field for
Ollama; the backend already sends Authorization: Bearer when a key is
set and omits the header when empty, so local keyless servers are
unaffected.

Fixes unslothai#7163
…nslothai#7231)

With 5 or more pills active the composer collapses every pill to an
icon, which hid the Bypass permissions label behind a small glyph.
Exempt the permission pill via data-keep-label so it always shows its
label, with the collapsed icons lining up to its right. Since the pill
is never icon-only now, drop the compact-mode fallthrough in the glyph
off switch so it works while the other pills are collapsed.
* fix(studio): add MLX adapter state control

* fix(studio): honor MLX adapter comparison state

* fix(studio): keep enabled MLX adapters permissive

* Studio: preserve public error message on MLX compare-mode adapter failures

generate_with_adapter_control raised a plain RuntimeError, which the compare
route handled with the generic handler that drops the operational message.
Raise GenStreamErrorRaised(public=chunk.public) instead and catch it in the
streaming and non-streaming consumers, matching the safetensors tool loop, so
errors like 'model is being unloaded' surface their real message.

* Studio: re-emit VLM think prefill inside the adapter context

The compare-mode merge dropped _generate_vlm's upfront yield of the prefilled
<think> block. Restore it as the first snapshot inside the lock+adapter context
(matching _generate_text) so the UI renders the thinking block during prefill
and a cancel/error before the first token does not drop it. Adds a regression
test asserting the prefill is emitted first, after entering the adapter context.

---------

Co-authored-by: danielhanchen <[email protected]>
…release (unslothai#7223)

The pip scan-packages studio shard is red on main and on every open PR:
the baselined fastapi finding (the benign SSE keepalive `while True:`
loop in fastapi/routing.py, reviewed and suppressed long ago) records
its evidence at L586 with the span digest of the fastapi release current
at baseline time. The latest fastapi shifts that loop to L587 and its
span digest with it, so the evidence hash no longer matches and the
scanner reports the finding as new, failing the shard with one
unsuppressed CRITICAL.

Re-reviewed the flagged code in the current release before refreshing:
L587 is the same keepalive loop inside the streaming response machinery,
not a beacon. Only the one entry's evidence and evidence_hash change.

Verified with the scanner itself: `scan_packages.py fastapi
--no-baseline` reproduces the exact CI evidence string, and with the
updated baseline the same scan exits 0 with the finding suppressed as
1 CRITICAL baselined.
…slothai#7185)

* Studio: enforce 60s minimum on idle auto-unload TTL (0 stays off)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop decorative section separator from idle TTL floor tests

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
* Replace standalone Studio wording with Unsloth

Replace the single word Studio with Unsloth wherever it is used as
shorthand for Unsloth Studio in docs, CLI output, UI strings, i18n
locales, workflow display names, comments and docstrings.

Kept unchanged: the full name Unsloth Studio, third party product
names (LM Studio, Visual Studio, Mac Studio), feature names
(Recipe Studio, Fine-tuning Studio and its translations), and all
identifiers such as env vars, commands, paths and filenames.

* Address review feedback on the Studio wording rename

Use "an" before Unsloth where the rename left the article as "a".
Restore the split brand where Unsloth and Studio render as two halves
of the full product name: the onboarding sidebar subtitle and the
IPv6 localhost warning. Scope two messages to the full name Unsloth
Studio where plain Unsloth was misleading: the AMD README bullet and
the CLI studio setup error.
… inventory (unslothai#7018)

* Studio: hide infra models from the hub cached inventory

The hub inventory scans behind /api/hub/cached-gguf and /api/hub/cached-models
returned the llama.cpp install validation probe (ggml-org/models) and the RAG
embedder (unsloth/bge-small-en-v1.5[-GGUF]) as on-device models. Share the
hidden-model check from routes/models.py via utils/models/hidden_models.py and
apply it in both scans. A GGUF infra repo stays visible when the user
explicitly downloaded a variant through the Hub, since variant manifests only
exist for user-initiated downloads.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: make On Device trust the hub inventory, match repo ids exactly, lighten the hidden-model import

Follow-up on the hub cached-inventory hidden-model change, addressing the review.

On Device now trusts the Hub inventory API for cached rows. The backend already
hides the RAG embedder and the llama.cpp probe and re-includes a GGUF infra repo
once the user downloads a variant through the Hub, but the frontend was
re-hiding it by repo id, so the user-downloaded variant never appeared in the On
Device list or the count. isVisibleInventoryRow now short-circuits cached rows
(kind === "cache") to visible and keeps client-side needle hiding only for local
filesystem rows and Discover.

is_hidden_model matches Hub repo ids exactly (case-insensitive) against the probe
plus the effective embedder and its GGUF companion, instead of substring
matching the configured-embedder basename. A custom embedder with a generic
basename like org/model no longer hides unrelated cached repos such as
user/model-chat or org/model-instruct. The probe filename and local-path
embedders keep exact matching.

The helper moves to utils/hidden_models.py and is imported at module scope in the
hub cache scanner, so it no longer pulls in utils/models/__init__ (the eager
model-config/checkpoint stack) and a broken import fails at startup instead of
being swallowed per-repo and silently emptying the inventory. routes.models
keeps the _is_hidden_model and _safe_resolve aliases and drops the unused
_HF_REPO_ID_RE re-export that was failing source lint.

Tests: exact repo-id matching with a custom embedder, the cached-models scan
keeping an unrelated repo, and a clean-interpreter check that the helper imports
without the model-config stack.

* Studio: match the llama.cpp probe filename on both path separators

The hidden-model check compared the probe's on-disk filename with
Path(value).name, which on a POSIX interpreter does not split a Windows-style
path ("...\stories260K.gguf") and would let the probe through. Split on both
separators so the probe is matched regardless of which OS produced the path,
matching the tolerance of the previous substring check. Adds a Windows-path
assertion to the probe test.

* Studio: harden hidden infra model handling

* Fix hidden cache row confirmation

* Fix hidden local rows and confirmed hint merges

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Handle snapshot-configured hidden models

* Hide basename-only default embedders

* Fix dynamic embedder inventory filtering

* Studio: hide the configured RAG embedder from Discover and feed rows

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
…ai#7227)

* fix(registry): don't register deepseek models at import time

`_deepseek.py` called `register_deepseek_models(include_original_model=True)`
at module scope, so merely importing `unsloth.registry` registered models
(and reached the hub via `list_models`) as a side effect. None of the other
five families (`_gemma`/`_llama`/`_mistral`/`_phi`/`_qwen`) do this; they only
register when `register_models()` asks them to.

Two consequences:
- Importing the registry populated MODEL_REGISTRY on its own (32 entries,
  including 10 `deepseek-ai` original models that no other family leaks) and
  did network I/O at import time.
- Because the import-time call set the `_IS_DEEPSEEK_*_REGISTERED` guards with
  `include_original_model=True`, the later `register_models()` call (which uses
  the default `include_original_model=False`) early-returned, so the
  original-model set won permanently.

Remove the stray module-level call. The `if __name__ == "__main__"` block below
still registers with `include_original_model=True` for standalone use, so the
generator script is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* test(registry): make import-side-effect test pass on CPU-only runners

The new test spawned a fresh `python -c "import unsloth.registry"` that did
not inherit tests/conftest.py's GPU-free harness, so on no-accelerator CI
runners the child raised NotImplementedError from unsloth_zoo.device_type
before printing REGISTRY_SIZE. With check=True this surfaced only as an
opaque CalledProcessError, turning the "Repo tests (CPU)" job red even
though the registry fix is correct.

Import this directory's conftest inside the child first so it applies the
same device_type stubs and torch.cuda probe patches. Also use check=False
and include the child stdout/stderr in the assertion message so a future
import regression is legible instead of an opaque non-zero exit.

* test(registry): assert register_models() leaks no upstream originals

Adds a fresh-interpreter test that register_models() registers only
unsloth-org models (deepseek still present via the normal path) and never
leaks the upstream deepseek-ai originals that the import-time guard poisoning
used to leak (129 -> 139). Factors the conftest-harness subprocess runner
into a shared helper reused by both registry import tests.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
…opover (unslothai#7217)

* studio: show the active run's saved config in the Training Progress popover

The Training Config popover on the live Training Progress page read the
editable form store (useTrainingConfigStore), so it showed stale/static values
whenever the form changed after the run started; only the History view read the
run's saved config snapshot, which is why re-opening the same run from Recents
showed the correct values (unslothai#6853).

Wire the live view to the same authoritative source History already uses:

- Extract History's field mapping into sections/run-config-override.ts
  (mapRunConfigToOverride) so both views share one mapper over
  GET /api/train/runs/{id} config.
- LiveTrainingView fetches the run record as soon as the job id is known and
  passes the mapped override to ProgressSection; the fetched config is keyed
  by job id, and until it loads (or if the fetch fails) the form store remains
  the fallback. The run record is created at job start, so it is available
  while the run is live.
- ProgressSection prefers configOverride whenever one is present instead of
  only when isHistorical, so the live override takes effect.

Adds a source-level regression test pinning the wiring and the mapper's
backend config keys.

Fixes unslothai#6853

* studio: retry the run-config fetch after the first step, carry the saved method

Two review fixes on the live Training Config popover source:

1. The backend creates the run row only on the first progress event, so the
   fetch issued as soon as the job id appeared commonly 404'd during
   model/dataset preparation and never retried -- leaving the popover on the
   form store for the whole run. The effect is now also keyed on
   firstStepReceived (and skips once resolved for the job), so it re-fetches
   exactly when the row is guaranteed to exist.

2. The popover's method label and LoRA-row visibility came from
   viewData.trainingMethod, still read from the editable form store; changing
   the form (e.g. LoRA -> Full) after starting a run relabeled it and hid its
   saved LoRA rows. The run-config mapper now derives trainingMethod from the
   snapshot's training_type/load_in_4bit (via parseBackendTrainingMethod, now
   exported from the feature index) and the live view prefers it.

* studio: fetch the run config on a terminal phase too, not just the first step

The live config-popover fetch was keyed on firstStepReceived, which the runtime
store sets only when step > 0. A run that fails or completes during preparation
(before step 1) creates and finalizes its row from the terminal error/complete
event, but neither the job id nor firstStepReceived changed, so the fetch never
ran and the popover stayed on the editable form store -- showing the wrong
config/method if the form was edited afterward (Configure re-enables on failure).

Gate the fetch on a runRowReady signal = firstStepReceived OR a terminal phase
(completed/error/stopped), the states in which the backend guarantees the row
exists. This also stops the earlier fetch-then-404 churn during preparation and
lets the effect depend only on values it reads (no lint suppression needed).

* studio: retry the run-config lookup and accept a hydrated step as row-ready

Two ways the popover could stay stuck on the editable form store for a whole
run:

- The backend publishes the progress event that reveals the run before
  create_run commits, so the first lookup can lose that race and 404. The catch
  changed neither runRowReady nor fetchedRunConfig, leaving every effect
  dependency identical, so no further attempt was ever made for that job. The
  failure path now schedules an explicit retry, bounded and keyed by job id, so
  a genuinely absent row falls back to the form store instead of polling.

- A run recovered through status/metrics polling (SSE unavailable or blocked)
  has currentStep restored by applyStatus/applyMetrics but never
  firstStepReceived, and the phase stays training, so the row was treated as
  not ready even at step > 0. currentStep > 0 is now a readiness signal of its
  own.

* studio: fetch the saved run config as soon as the job id exists

start_training() inserts the run row before the pump can consume any event --
deliberately, so the run appears in history during model loading -- and /status
exposes the job id throughout the pre-step phases. Gating the lookup on a first
step or a terminal phase therefore held the popover on the editable form store
for the whole configuring/loading/downloading window, which on a long model or
dataset load is minutes, and indefinitely for a run adopted from another client.

The job id is now the entire readiness condition; the existing bounded retry
still covers the instant before the insert commits.

* Fix Training Config popover fallback for history runs without a saved config; tighten popover comments

---------

Co-authored-by: danielhanchen <[email protected]>
…hai#7247)

* test(version-compat): keep GRPO fake-run logits finite on CPU

The GRPO fake-run test samples completions from a tiny untrained model on
CPU. Such a model can emit non-finite logits, so torch.multinomial inside
generate() intermittently raises "probability tensor contains either inf,
nan or element < 0" -- a nondeterministic sampling failure, not a regression
(the Trainer already fixes the seed, but CPU reduction order is not
bit-reproducible). Add a forward hook that sanitizes the LM head logits to a
finite bounded range before sampling, so the fake run reliably exercises the
whole train loop; the test checks the loop runs, not the numerics.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* test(version-compat): drop redundant nan_to_num bounds (clamp handles them)

* test(version-compat): scope GRPO finite-logits guard to the GRPO test

Only test_grpo_trains_on_cpu autoregressively samples completions, so it is
the only canary that can hit the non-finite-logits torch.multinomial crash.
Move the _guard_finite_logits hook out of the shared _load_plain() and into
test_grpo_trains_on_cpu so the SFT and DPO canaries keep asserting against the
model's true, unclamped logits.

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Studio: GPU memory dropdown — llama.cpp --fit on and manual gpu-layers/cpu-moe

* Studio: simplify GPU memory changes (reuse ParamSlider, GPU_LAYERS_ALL, loadedGpuMemoryFields helper)

* Studio: GPU picker — choose which GPUs a GGUF model loads on (gpu_ids)

* Studio: simplify GPU picker (share /api/system fetch, validate gpu_ids)

* Studio: GPU picker review fixes (gate relative indices, no cross-model leak, validate, types)

* Studio: group GPU controls under a collapsible GPU section

* Studio: GPU feature review fixes (fix fit-ctx test, behavior-test the floor, comment accuracy)

* Studio: make GPU a top-level settings section (not nested under Model)

* Studio: flatten GPU controls into the Model section, group by GPU/context/generation

* Studio: move GPU Memory to the bottom of Model with its dependent controls beneath it

* Studio: move GPU Memory below Tensor Parallelism and GPUs below GPU Memory

* Studio: tighten GPU Memory and GPU Layers tooltip copy

* Studio: fix fit-mode context slider track-click, restore GPU Memory tooltip, shorten fit dropdown label

* Studio: GPU Memory tooltip one mode per line, briefer

* Studio: note HIP_VISIBLE_DEVICES (ROCm) in the GPUs picker tooltip

* Studio: narrow the GPU Memory dropdown to fit the shortened label

* Studio: use 'llama.cpp --fit' in the GPU Memory tooltip for consistency

* Studio: allow Tensor Parallelism in Manual GPU mode

* Studio: graduated MoE-on-CPU offload (--n-cpu-moe) replacing the all-or-nothing toggle

* Studio: size the MoE-offload slider for staged (deferred-load) models

* Studio: share one GGUF header walk for the context-length and MoE-count readers

* Studio: size the GPU Layers slider for staged models (one staged-header read)

* Studio: move Tensor Parallelism below the GPUs picker

* Studio: GPU split (--tensor-split) per-GPU model share in Manual mode

* Studio: tolerate whitespace in GPU split input, move it below GPU Layers

* Studio: rename the GPU split control to "Split ratio"

* Studio: Split ratio sends explicit even input; fix blank=free-VRAM (not even) copy

* Studio: tighten llama.cpp --fit VRAM margin with --fit-target 512

* Studio: GPU memory review fixes (rollback re-baseline, single-GPU TP gate, accurate copy)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: move Split ratio below MoE Layers on CPU

* Studio: address PR review (fix GPU-info hydration race, share fit context-length across load paths)

* Studio: address codex review (manual single-GPU TP guard, GPU-aware spec defaults in fit/manual, GGUF-only context/preference)

* Studio: address codex review round 2 (gpu_present seed, single-GPU tensor-split guard, staged manual-knob reset, strip inherited offload flags)

* Studio: address codex review round 3 (strip inherited --n-cpu-moe, CPU-fallback warning in Manual mode)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: address codex review round 4 (preserve pinned fit context across a later Apply)

* Studio: address codex review round 5 (honor GPU picker for diffusion GGUFs, clear fit pin on cross-model switch)

* Studio: preserve the pending GPU Memory mode when staging a model

* Studio: pin diffusion GPU device order and reset GPU-memory state for diffusion loads

* Studio: address codex review round 6 (fit-Auto rollback context, preserve manual non-tensor split modes, persist GPU mode on load not select)

* Studio: persist the applied GPU Memory mode, not the requested one (skip diffusion loads)

* Studio: replace Manual-mode split-ratio field with per-GPU layer sliders

* Studio: clarify per-GPU layer split hint for tensor-parallel mode

* Studio: address codex review round 7 (allow GGUF gpu_ids past the legacy guard, replay GPU-memory fields on respawn)

* Studio: address codex review round 8 (size the validate preflight like the load in fit mode, across both load paths)

* Studio: skip the training-OOM guard for llama.cpp --fit GGUF loads (they spill to RAM)

* Studio: drop the now-redundant compare-path validate sizing (the --fit guard skip makes it moot)

* Studio: address codex review round 9 (keep the training guard for fit loads, forward gpu_ids to validate, strip inherited manual tensor-split)

* Studio: address codex review round 10 (gate GPU-memory adoption on is_gguf, record manual knobs only in Manual mode)

* Studio: handle diffusion GGUFs symmetrically in the GPU Memory controls (preserve the standing mode preference, hide the inapplicable mode/TP controls)

* Studio: remember the GPU Memory settings per model

* Studio: consolidate --fit mode and Manual mode into a single Manual mode

* Studio: preserve the per-GPU layer split across GPU Layers changes

* Studio: trim overly long GPU Memory comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* address GPU memory config review comments

* trim redundant GPU memory tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reconcile manual-mode TP drops with the unslothai#6659 drop-site invariants

* Preserve quantized KV in manual --fit, charge GGUF companions in full, reconcile GPU pick on load

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Clear stale GPU baseline on non-GGUF loads so it can't read as dirty

* Fix no-context-shift test for the conditional -c flag

* Credit manual GPU-layer offload for cached HF GGUFs

* Reset per-model load knobs on GGUF quant switch

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Strip inherited tensor-split when manual ratio is cleared

* Match auto-load validation to safetensors placement

* Reset editable manual knobs after Auto GGUF loads

* Record a single device for diffusion GPU picks

* Reset per-model GPU knobs before applying saved settings

* Address review comments

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Guard manual tensor splits and keep remembered context on auto-load

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Snapshot compare knobs, seed splits from free VRAM, flag zero-offload loads

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Exempt CPU-only loads from the guard floor and harden compare and reseed paths

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reach full offload from the layers slider and charge extras drafters in the guard

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Warm the GPU device cache before pick reconciles and disable staged GPU controls

* Align the training guard with inherited extras, spec mode, and compare targets

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hide GPUs from companion-less zero-offload loads

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size diffusion picks per device, own manual offload flags, reject XPU picks

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop tensor flags at zero layers and exempt CPU-pinned drafters

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Allowlist the zero-layer tensor parallel drop site

* Keep validate and load guards on the same extras and refresh stale baselines

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop mismatched manual tensor splits before launch

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Gate XPU picks on the real backend field and harden split and hydration paths

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Weight full GPUs as zero, clamp split shares, and refine the zero-layer mask gate

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Carry fit context across mode changes and align drafter and picker gates

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Catch variant switches, uncached diffusion repos, and text-only mmproj skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Check companions on the first device and size native and remote zero-layer loads

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Replace the training guard's precise VRAM modeling with a conservative bound

* Baseline context pins on non-GGUF hydration and reprobe list-seeded staged GGUFs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size manual splits by their largest share and preserve resolved context from Default

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Default-deny unsized required companions and price KV at the effective cache dtype

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reserve MTP draft KV and MLA target-copy in the training guard

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size tensor-parallel loads per device and show GPU controls for native GGUFs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reserve MTP overhead for uncached remote GGUFs and the mmproj runtime factor

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop the training-coexistence VRAM estimation this PR added

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Gate remembered load settings to GGUF picks

* Lock the remaining load-time controls during a staged load

* Clear the stale native-path token on compare loads

* Drop a stale guard reference from the zero-offload masking comment

* Seed GPU baselines from the rollback response and drop never-emitted offload flags

* Match validate's training guard to load and keep the native reload token

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim verbose GPU-memory comments

* Thread the variants header walk off the event loop, honor device pins on zero-offload, and hold staged GPU edits

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Honor manual placement and classify pinned zero-offload loads

* Close diffusion admission and status hydration gaps

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Check the actual diffusion GPU during training

* Align staged baselines and manual reload dedupe

* Fix GGUF placement and rollback state

* Harden manual GGUF placement boundaries

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove unused resolve_tensor_parallel import in llama_cpp.py

The name is used only in llama_server_args.py, routes/inference.py, and tests,
not in llama_cpp.py; the unused hoisted import trips the import-hoist verifier
in the source-lint CI job.

* Fix diffusion GPU dedup and training guard for non-numeric device tokens

The diffusion runner drives only its single lowest device and the backend
records that one device (self._gpu_ids = [sorted(gpu_ids)[0]]), but the reload
dedupe compared it against the full requested list, so a multi-GPU pick that
resolves to the same device forced a needless reload. Normalize the request the
same way for a loaded diffusion model in both _already_in_target_state and the
route _request_matches_loaded_settings.

The chat-during-training coexistence guard called int() on the single-device
token and hard-rejected when it could not parse. A non-numeric token (a CUDA
UUID / MIG handle) now sizes against the whole visible pool like the GGUF guard
instead of falsely blocking the load, and an empty token (a CPU-only runner such
as a CPU diffusion GGUF) is allowed outright since it uses no GPU VRAM.

* Tighten comments added by the GPU memory config changes

* Harden GGUF placement from independent review: VRAM sizing, diffusion TP reset, tensor_split validation

- Training coexistence guard: a single-device runner pinned through an
  unresolvable UUID/MIG token was sized against the aggregate visible-VRAM pool,
  so a load could pass on capacity it cannot use and then OOM active training.
  Size against the worst-case visible device (min free) instead, keeping the
  guard's documented default-deny contract. The empty-token (CPU-only runner)
  allow path is unchanged.
- Diffusion startup: _start_diffusion_server now resets self._tensor_parallel to
  False alongside the other placement resets. A prior tensor-parallel chat load
  (process killed but not fully unload-reset) otherwise left /status misreporting
  tensor parallelism and made an identical diffusion re-Apply reload against the
  stale state.
- tensor_split: reject negative / non-finite / all-zero splits up front. They
  were dropped at launch but still compared raw in the reload dedupe, so an
  identical Apply reloaded indefinitely.
- Tests: the shared httpx stub was incomplete and, installed via setdefault
  before real httpx loaded, broke a combined pytest run (collection errors on
  httpx.Response). Import the real installed httpx instead.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
…ai#7235)

* Raise the opencode invoke timeout in Local Agent Guides CI

The connection (opencode) cell flakes with a 600s timeout reported as guide drift, but it is not a hang: in a passing run the same opencode run finishes in ~482s (08:12:31 to 08:20:33), right against the shared AGENT_INVOKE_TIMEOUT of 600s, so about one run in six drifts past the cap.

opencode is the slow outlier. The print-mode agents (claude -p, codex exec) run one turn against a minimal injected system prompt, while opencode run runs its own full turn with opencode's large system prompt plus a separate small_model call to name the session (start.py pins small_model to the same 4B the server hosts). On a CPU-served gemma-4-E4B that is about 8 minutes, leaving no margin under 600s.

Double opencode's per-invoke timeout in agent-guides-drive.sh and keep the tight 600s cap for the fast agents, so a genuine headless-TTY hang still fails quickly. 1200s stays well under the 40-minute job budget.

* Normalize the agent invoke timeout before doubling it for opencode

Strip an optional trailing 's' from AGENT_INVOKE_TIMEOUT so the opencode
arithmetic, and the "${TIMEOUT}s" timeout message, stay valid if a
timeout(1)-style suffix is ever configured.

* Only double the opencode timeout for a bare-integer seconds value

Guard the arithmetic so a GNU timeout(1) duration suffix (s/m/h/d, including
floats like 0.5s) is passed through unchanged instead of breaking the
expansion; timeout(1) parses those directly. Bare seconds still double.

---------

Co-authored-by: danielhanchen <[email protected]>
@Imagineer99

Copy link
Copy Markdown
Member Author

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

ℹ️ 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 +2295 to +2297
// selectModel owns superseding cancellation so it can preserve the
// working checkpoint as the rollback target for the replacement.
}

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 Keep the working model config when superseding loads

When a second cached/local model is chosen while another load is already in flight, this fallthrough reaches the existing currentRuntimePerModelConfig() snapshot below after the superseded load has already applied its own per-model settings. In the sequence A loaded → start loading B → choose C, C's previousConfig becomes B's config even though the preserved rollback checkpoint is A, so a failed stop or a failed C load can leave/reload A with B's max-context/GPU/speculative settings instead of A's.

Useful? React with 👍 / 👎.

replacementNeedsRollback =
replacementNeedsRollback ||
activeRun.previousCheckpointWasUnloaded;
if (loadIntentRef.current !== loadIntentId) return;

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 Report superseded selections as cancelled

When this selection loses the intent race after waiting for the previous load to stop, returning normally makes selectModel resolve as if nothing went wrong. Callers that pass throwOnError and do cleanup after the await can then treat a superseded load as successful; for example, the native model intent path clears the local-file chip after await stageOrLoad, so a quick Native chip load followed by another selection can drop the chip even though that file never loaded and may need to be re-picked.

Useful? React with 👍 / 👎.

useTransformersUpgradeDialogStore.getState().cancelPending(run);
loadAbortRef.current = null;
loadingModelRef.current = null;
useChatRuntimeStore.getState().clearLoadingModelPick(pickOf(model));

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 Keep shared loads visible until cancellation settles

When a load owned by another mounted surface is already being cancelled, clearing the shared loadingModelPick here makes other useChatModelRuntime instances see no in-flight pick, even though sharedModelLoadHandle remains active until /unload and run.completionPromise finish. A Chat selection made while a Hub-started load is stopping can therefore skip the shared.cancel(true) wait path and start a new load from an uncertain backend state, especially if the unload later fails.

Useful? React with 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member Author

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

ℹ️ 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 +719 to +721
replacementNeedsRollback =
replacementNeedsRollback ||
activeRun.previousCheckpointWasUnloaded;

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 Don't skip unloading after a completed rollback

When a superseded run is already in its rollback path, that rollback can successfully reload the previous checkpoint while activeRun.previousCheckpointWasUnloaded remains true. Propagating that flag here makes the replacement run initialize previousWasUnloaded to true and skip the currentCheckpoint unload later, so selecting model C while failed model B is rolling back to model A can start C's /load with A still resident. Clear the flag after rollback succeeds, or avoid carrying it into the replacement once the rollback restored the checkpoint.

Useful? React with 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member Author

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

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

store.modelLoading || store.loadingModelPick,
);
if (hadLocalLoad) {
const stopped = await cancelLoading();

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 the prior checkpoint when hosted switch aborts

When switching to an external provider during an in-flight local load, this calls the public cancelLoading() path, which clears the current checkpoint before /unload has succeeded. If that unload/cancel request fails, the code returns without selecting the hosted model, leaving the UI with neither the previous local checkpoint nor the requested external model even though the previous model may still be the only usable backend state. Use a preserving cancellation path here, or restore the saved checkpoint on the !stopped branch.

Useful? React with 👍 / 👎.

// in-flight backend load, so send it before waiting for the frontend
// task to observe the abort. The unload route waits for cancellation
// to settle before it returns, preventing a late /load activation.
await unloadModel({ model_path: model.id });

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 Track the rollback target when cancelling

When a failed switch is already rolling back to previousCheckpoint, this cancellation path still posts /unload for the failed target stored in model.id. For non-GGUF loads that means a Stop or a new selection during the rollback does not cancel the previous model that is currently loading; it waits for that rollback to finish and can leave the previous model reloaded/selected despite the user cancelling. Track the currently loading rollback checkpoint, or make the rollback load owned/abortable, before awaiting cancellation.

Useful? React with 👍 / 👎.

// only after it settles, because that install may unload the active
// backend model. Do not let a replacement start before the cancelled
// frontend task has observed that outcome.
await run.completionPromise;

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 Don't wait forever on unabortable preflights

This unconditional wait also covers frontend preflights that never receive the abort signal, such as the remote-code scan and HF-token validation (their new checks only run after those requests return). If the user switches models while one of those requests is slow or hung, /unload can succeed but the replacement load remains blocked on completionPromise until the preflight finishes. Either make those preflight requests abortable or avoid waiting for completion when the cancelled run never reached the backend load.

Useful? React with 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@Imagineer99

Copy link
Copy Markdown
Member Author

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

ℹ️ 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 (shared.run.rollbackConfig) {
previousConfig = shared.run.rollbackConfig;
}
const stopped = await shared.cancel(true);

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 replacing surface config during shared cancellation

When a replacement selection comes from another mounted runtime surface, this branch delegates cancellation through the shared handle but only advances this hook's loadIntentRef; the owning hook's aborted run still sees itself as latest and reapplies its rollbackConfig in the outer catch. Hub and the sampling dialog apply the new model config before calling selectModel, so a cross-surface switch can have that config overwritten before the replacement load snapshots context/GPU settings, causing the new model to load with the previous model's settings.

Useful? React with 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 2c355acc4b

ℹ️ 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 added a commit to wasimysaid/unsloth that referenced this pull request Sep 22, 2026
…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.
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 22, 2026
…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.
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 22, 2026
…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.
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 23, 2026
…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.
wasimysaid pushed a commit to wasimysaid/unsloth that referenced this pull request Sep 23, 2026
…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.
wasimysaid added a commit that referenced this pull request Sep 24, 2026
* 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 #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
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.