Skip to content

studio: preserve gguf settings across chat switches - #9562

Merged
Lyxot merged 4 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-switch-back-context
Aug 26, 2026
Merged

Lyxot merged 4 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-switch-back-context

Conversation

@mahiatlinux

@mahiatlinux mahiatlinux commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9546.

Persist each chat's GGUF variant in chat_threads and carry the resolved variant through queued model selection. ChatModelNotice now switches with the saved variant and restores its per-model context and llama.cpp settings instead of falling back to a 4096-token load.

Recover legacy GGUF variants only when one saved config matches the quant in the local model path. Ambiguous or unproven variants stay unset.

Keep history updates thread-scoped so queued initialization cannot leave the notice on stale model metadata. Backfill resolved queued models only for fresh empty thread rows.

chatModelSwitchMeta carries only the GGUF variant for a Hub repo id. /api/models/list already supplies isGguf and isLora, and a synthesized source: "hub" would send an already-downloaded model through the download manager, whose conflict and busy outcomes toast and return without loading.

Scope

A pre-existing chat on a Hub repo id such as unsloth/Qwen3-4B-GGUF still switches back at 4096. resolveChatModelSwitchTarget recovers a variant only from a quant token in the model path, and a Hub repo name has none, so guessing between saved configs would load a quant the chat may never have run. Chats created from this change onward record the variant on the thread row and are unaffected.

chatLocalModelOptions sets isDirectGguf for .gguf paths, which is what keeps a single-file GGUF loading as one. isGguf is left as it was on main: widening it to model_format === "gguf" changes the picker's format filter and row tags for GGUF directories, which is a separate change.

Checks

  • ruff check studio/backend/routes/chat_history.py studio/backend/storage/studio_db.py studio/backend/tests/test_chat_history_routes.py studio/backend/tests/test_chat_history_storage.py
  • python -m pytest -q tests/test_chat_history_storage.py tests/test_chat_history_routes.py (81 passed, run before the rebase onto main; the backend diff is unchanged since)
  • npm run typecheck
  • node --experimental-strip-types --test over the 68 frontend test files that read the changed modules (1084 passed)
  • git diff --check

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the switch-back path reloads with a default 4096 context instead of the saved per-model settings, and this carries the chat's resolved GGUF variant through so the stored config is found. Will get this reviewed.

@Lyxot Lyxot self-assigned this Aug 25, 2026

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Root cause is right, and I confirmed it against the branch: per-model settings key on (modelId, ggufVariant), so resolveInitialConfig("unsloth/Qwen3.8-27B-GGUF", "UD-IQ1_S") returns the saved 32768, while the same call without the variant returns remembered: false and falls through to DEFAULT_MAX_SEQ_LENGTH (4096). Storing the variant on the thread row is the right fix, and for local GGUF directory chats it works cleanly.

One issue in the new Hub branch of chatModelSwitchMeta. It returns:

{ source: 'hub', isLora: false, ggufVariant: 'UD-IQ1_S', isGguf: true }

with no isDownloaded. In stageOrLoad that makes wantManagerStage true, so an already-downloaded model gets routed through the download manager instead of loading directly:

const wantManagerStage =
  wantManagerDownload ||
  (selection.source === "hub" && hasGgufSource(selection) && !selection.isDownloaded);
if (wantManagerStage) { setPendingHubAutoLoad(...); return; }

It does recover — the pendingHubAutoLoad effect calls downloadManager.requestStart, the job completes immediately for a cached repo, and onComplete loads with the right variant and context. Tested in the UI on unsloth/qwen3.8-27b-gguf UD-IQ1_S: a "Downloading model" toast appears for a model with nothing to download, then it loads correctly. That toast is what the deleted comment was guarding — "Already on disk: without this the load shows a download progress bar for a model that has nothing to download."

Two requestStart outcomes don't recover, though: conflict (an earlier partial download on a different transport) and busy both toast and return without loading, where main loaded unconditionally. Narrow, but it's a new way for switch-back to do nothing.

isDownloaded: true on that branch fixes it. Worth considering dropping the synthesized source: "hub" instead — wantManagerStage and isDownloadableHubRepo both gate on source === "hub", and /api/models/list already gives selectModel the isGguf it needs, which is why the old code returned undefined here. { ggufVariant } alone would carry the fix without opting out of the resolver.

The test can't catch this — assert.deepEqual(..., { source: "hub", isLora: false, isGguf: true, ggufVariant: "Q8_0" }) pins the current shape exactly, so adding isDownloaded would fail it. A test over the selection → stageOrLoad predicate would be more useful than one over the meta shape.

Smaller notes:

  • meta.config is redundant. stageOrLoad already does selection.config ?? rememberedConfigFor(selection), which is the same resolveInitialConfig(id, ggufVariant) lookup — I checked, the two objects are deepEqual. Dropping it also removes the localStorage dependency that forced the new fake in the test file.
  • shouldPersistResolvedQueuedModel re-checks !queuedCheckpoint, which the caller already returned on four lines earlier.
  • resolveChatModelSwitchTarget never recovers a variant for a Hub repo id — the basename has no quant token. So existing chats on unsloth/…-GGUF still switch back at 4096; only chats created after this lands are fixed. Worth stating in the description.
  • local-model-options.ts: setting isDirectGguf for .gguf paths is load-bearing here (and incidentally fixes selectionMeta.isGguf being false for single-file GGUF picks in the chat picker). Widening isGguf to model_format === "gguf" is a separate change that affects the picker's format filter and row tags for GGUF directories — probably worth splitting out or calling out.
  • createChatModelHistoryReader.applyUpdate fires on every CHAT_HISTORY_UPDATED_EVENT for the thread, including renames and archives, returning a fresh object each time — three re-renders for one model read in my test.

@mahiatlinux
mahiatlinux force-pushed the fix/studio-switch-back-context branch from 89884cf to 2f102ba Compare August 25, 2026 22:50
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Thanks @Lyxot, all of it is addressed and the branch is rebased onto latest main (8194d50fc).

The Hub branch and the download manager. Took the second option: chatModelSwitchMeta in chat-model-notice-switch.ts now returns { ggufVariant } and nothing else for a row that is not in loraModels. isDownloaded: true would also have skipped the staging branch, but it asserts something the notice cannot know, and /api/models/list carries default_models that are not on disk. Dropping the synthesized source puts the pick on exactly the path a bare-id switch took on main, and selectModel derives isGguf from ggufVariant anyway (use-chat-model-runtime.ts, explicitIsGguf ?? (ggufVariant != null || ...)), so nothing is lost by not stating it. Return type is Partial<ModelSelectorChangeMeta>, and handleCheckpointChange takes the same, since it only ever reads optional fields off meta.

The predicate, and the test over it. stageOrLoad wrote the staging condition twice, identically, for wantBackgroundDownload and wantManagerStage. Both are now one wantsDownloadManagerStaging(selection), which lives in utils/model-download-staging.ts with the three predicates it composes (hasGgufSource, isLocalModelPath, isDownloadableHubRepo, moved out of chat-runtime-store.ts and re-exported from it so no importer changed). The move is what makes the test possible: importing the store in a bare node test fails on features/auth/login-page, so the predicate had to be reachable on its own. switching back to a hub GGUF loads it instead of staging a download builds the selection the way handleCheckpointChange does, runs the real predicate over it, and pins both the field mapping and the wantsDownloadManagerStaging(selection) call against chat-page.tsx. The assert.deepEqual shape pins are gone.

meta.config. Dropped from both branches. the switch back leaves the remembered config to stageOrLoad asserts the module no longer imports resolveInitialConfig, that stageOrLoad still does selection.config ?? rememberedConfigFor(selection), and that rememberedConfigFor is the same resolveInitialConfig(selection.id, selection.ggufVariant) lookup. The localStorage fake stays in the test file: resolveOnlyRememberedGgufVariant, which resolveChatModelSwitchTarget calls, reads it too.

shouldPersistResolvedQueuedModel. Now takes the stored thread alone. The queued-checkpoint check is gone, and the test asserts the caller in chat-adapter.ts still returns on queuedRunSettings.params.checkpoint first.

applyUpdate re-renders. createChatModelHistoryReader keeps the last emitted target and compares modelId and ggufVariant before calling onModel, so a rename or archive event for the thread is dropped. The first emit is always delivered, including one that is null. Covered by a history update that leaves the model alone is not re-emitted.

local-model-options.ts. Split out rather than kept: isGguf goes back to what it is on main, and only the isDirectGguf widening for .gguf paths stays, which is the part chatModelSwitchMeta reads. The picker's format filter and row tags for GGUF directories are untouched by this PR.

Not fixed: the variant for a pre-existing Hub chat. resolveChatModelSwitchTarget still recovers nothing for unsloth/...-GGUF, so those chats keep switching back at 4096 until they are recreated. resolveOnlyRememberedGgufVariant would answer for a repo with exactly one saved config, but with no quant token in the repo name there is nothing to check it against, and a wrong guess both loads a quant the chat never ran and makes the notice appear when the chat is already on its own model. Stated in the description instead.

One thing the rebase added: ThreadCreationClaim (#8908's send-time snapshot, which landed on main after this branch was cut) now carries modelGgufVariant alongside modelId, set at both claimThreadCreation sites in thread.tsx. Without it initialize() would take the model from the claim and the variant from the store, which is the pairing the claim exists to prevent.

Verification: npm run typecheck clean, and node --experimental-strip-types --test over the 68 test files that read any changed module, 1084 passing. ruff check clean on the backend files. The backend pytest run in the description predates the rebase; I have no Python environment here to repeat it, and no backend file changed in this round.

chatModelSwitchMeta synthesized source: "hub" for a Hub repo id, which is what
stageOrLoad keys the download manager off. An already-cached model was routed
through downloadManager.requestStart, and its conflict and busy outcomes toast
and return without loading, so the switch back did nothing. The Hub branch now
carries only ggufVariant: /api/models/list already supplies isGguf and isLora,
and selectModel derives the GGUF flag from the variant.

stageOrLoad wrote the same staging condition twice; both are now
wantsDownloadManagerStaging in utils/model-download-staging.ts, alongside the
three predicates it composes, so a test can load it without the whole store.

Other review items: meta.config is gone, since stageOrLoad already falls back
to rememberedConfigFor, the same resolveInitialConfig(id, ggufVariant) lookup;
shouldPersistResolvedQueuedModel drops the queued-checkpoint check its caller
returned on four lines earlier; createChatModelHistoryReader compares the model
before emitting, so a rename or archive event no longer re-renders the notice;
and chatLocalModelOptions goes back to main's isGguf, keeping only the
isDirectGguf widening this fix needs.

The meta-shape assertions are replaced by a test over the selection that
handleCheckpointChange builds and the staging predicate stageOrLoad applies to
it.
@mahiatlinux
mahiatlinux force-pushed the fix/studio-switch-back-context branch from 2f102ba to 5fa414c Compare August 26, 2026 03:47
@mahiatlinux

Copy link
Copy Markdown
Contributor 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: 5fa414c37a

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

"title": ("title", patch.get("title")),
"modelType": ("model_type", patch.get("modelType")),
"modelId": ("model_id", patch.get("modelId")),
"modelGgufVariant": ("model_gguf_variant", patch.get("modelGgufVariant")),

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 Clear the variant when patching to a different model

When a thread already stores a GGUF variant, a valid PATCH containing only a new modelId updates model_id but leaves model_gguf_variant attached to the old model. This differs from the new upsert logic, which explicitly clears the variant when the model changes. Such a row makes ChatModelNotice pass the stale quant to the new model during “Switch back,” potentially loading the wrong artifact or failing the load. Clear model_gguf_variant when modelId changes unless the patch supplies a replacement variant.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No caller sends that patch. The only two writers of modelId on an existing row both send modelGgufVariant in the same PATCH: persistResolvedQueuedModel in chat-adapter.ts ({ modelId, modelGgufVariant }) and the queued-run correction in thread.tsx (modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant).

Both are typed string | null, updateChatThread does JSON.stringify({ ...patch }) so an explicit null survives the wire, and patch_thread reads the body with model_dump(exclude_unset = True), so the key is present and update_chat_thread writes model_gguf_variant = NULL. Every other updateStoredChatThread call patches title, archived, projectId, settings or a container id, and the route is the only caller of update_chat_thread in the backend.

The upsert CASE is not there to clear the variant on a model change: plain model_gguf_variant = excluded.model_gguf_variant already does that. It exists to preserve the variant on a same-model save from a client that does not send the field. A modelId-only PATCH is not a shape the app produces, so there is no stale-quant row for ChatModelNotice to read.

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f040a3db4b

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

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

All addressed — verified against f040a3db4b rather than by reading the diff.

The Hub branch. chatModelSwitchMeta returning { ggufVariant } and nothing else puts the pick back on the path a bare-id switch took before, and wantsDownloadManagerStaging now answers false for it while still answering true for a genuinely uncached Hub GGUF — so staging wasn't disabled wholesale. Agreed this is the better of the two options: isDownloaded: true would have asserted something the notice can't know, and /api/models/list carrying undownloaded default_models is a case I hadn't considered.

Confirmed the load path is intact downstream, which is the part the PR doesn't touch: with no isGguf on the meta, use-chat-model-runtime.ts derives it from explicitIsGguf ?? (ggufVariant != null || …), so the pick still loads as a GGUF and stageOrLoad's rememberedConfigFor resolves the saved context off (id, ggufVariant).

The test. Reintroduced the exact defect ({ source: "hub", isLora: false, ggufVariant, isGguf: true }) and switching back to a hub GGUF loads it instead of staging a download fails, along with a saved GGUF variant is carried back exactly. It guards the behavior, not the shape.

The rest. meta.config dropped and still resolved by stageOrLoad; shouldPersistResolvedQueuedModel down to the thread alone; the reader emits once for a model read plus two unrelated thread updates instead of three; isGguf in local-model-options.ts back to what it was, with only the isDirectGguf widening kept. The wantsDownloadManagerStaging extraction is a faithful move — isLocalModelPath's regex is unchanged and the composed predicate is equivalent to the two duplicated expressions it replaces. Carrying modelGgufVariant on ThreadCreationClaim is a good catch on the rebase; without it the row would pair a claimed model with a store-read variant.

Checks: chat-remembers-its-model.test.ts 25 pass, npm run typecheck clean, backend test_chat_history_{storage,routes}.py 90 pass, test_multi_chat_prompt_queue_contract.py 13 pass. Merges clean into current main.

Two things I'd leave alone, noted only so they're on the record:

  • The "Downloading model…" toast and 0% progress bar still appear on a Hub switch-back, since isDownloaded is false going into selectModel. That's identical to the behavior before this PR, so it's pre-existing rather than introduced — worth a separate issue if it's worth fixing at all, as a correct fix needs a cache probe the notice doesn't have.
  • The pre-commit.ci commit reformatted an assert in test_health_answers_within_probe_budget.py, which this PR doesn't otherwise touch. Harmless, just unrelated diff noise.

Agreed on not guessing a variant for pre-existing Hub chats — a wrong guess would load a quant the chat never ran and pop the notice on a chat already sitting on its own model. Good that it's stated in the description.

LGTM.

@Lyxot
Lyxot merged commit 2785f01 into unslothai:main Aug 26, 2026
51 checks passed
@mahiatlinux
mahiatlinux deleted the fix/studio-switch-back-context branch September 25, 2026 05:32
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
…load (unslothai#15139)

The model picker, the compare pane and auto-load each built two payloads
from the same settings: one for the `/validate` preflight and one for
`/load`. `validateModel` then re-serialized the first through a
hand-kept allow-list. That is 13 payload literals across
`use-chat-model-runtime.ts`, `shared-composer.tsx`, `chat-adapter.ts`
and `chat-api.ts`, and every new load setting had to be added to each
one.

The history shows the copies drifting apart:
- unslothai#9410 added Checkpoints and the draft KV dtype to every load and never
to the allow-list.
- unslothai#13596 (vLLM/SGLang KV dtype, seed, memory limit) had to edit the
picker, compare and `chat-api.ts` separately.
- The managed-engine offer (unslothai#13135, then unslothai#13229) and GGUF settings
preservation (unslothai#9562, then unslothai#11311) each landed on the picker first and
needed a follow-up PR for compare and auto-load.

The preflight exists so Studio refuses a load before it unloads the
working model, and also to guard training. When `/validate` judges a
different command from the one `/load` runs, it approves a load that
`/load` then refuses after the unload, or refuses one that would fit.

## Changes

- **One request, sent twice.** Each path builds one `LoadModelRequest`
and sends it to both `/validate` and `/load`. Only the load-only fields
are added at the `/load` call: request id, lease, force flags and
`alongside`.
- **The allow-list is gone.** `/validate`'s body is the load request;
the route ignores load-only fields. `validateRequestBody` fills defaults
for the non-nullable fields only.
- **`llamaServerLoadFields`** owns the one rule for llama-server's
knobs, which the three paths used to spell out with slightly different
gating:
- reasoning budget, batch sizes, server tuning and pass-through args are
sent for GGUF only;
- diffusion GGUF requests omit custom reasoning overrides, server tuning
and pass-through args, while still forwarding batch sizes;
  - blank values are omitted, never sent as null.
- **The picker re-baselines once.** On a model switch it re-baselines
its per-model settings before `/validate`, instead of mirroring that
reset in a second set of `validate*` variables.
- **New module.** `lib/load-request.ts` holds the three helpers.
Production code is 225 lines shorter.

## Preflight and load now agree

- **The three dropped settings now reach `/validate`.** `validateModel`
dropped `ctx_checkpoints`, `spec_draft_cache_type` and `tensor_split`.
Checkpoints affect sizing; a load with Checkpoints set was priced at the
default 32. Forwarding the draft KV dtype and GPU split makes validation
apply the same explicit-setting precedence over inherited flags as
loading. The training coexistence guard does not directly price draft KV
memory.
- **The picker and compare preflights now send the speculative mode and
depth.** They omitted `speculative_type` and `spec_draft_n_max`, so
validation used the default Auto mode, which already counts some
drafters but can differ from the selected mode. The preflight now
receives the same selected values as loading. Auto-load already sent
them.
- **A model switch with a staged run-settings config is now sized like
the load.** The picker's preflight used Auto layers and no context pin,
while `/load` used the staged layer count and context length.
- **Compare and auto-load no longer send llama-server's pass-through
args or tuning to a diffusion GGUF.** The diffusion runner takes none of
them, and the picker already left them out.

## Validation

- **Wire check:** the same GGUF request was sent through the real
`chat-api.ts` of each checkout, comparing what `/validate` receives with
what `/load` receives. On `main`, `/validate` is missing `tensor_split`,
`spec_draft_cache_type` and `ctx_checkpoints`; here it is missing
nothing.
- **Contract test:** `chat-load-request-one-builder.test.ts` reads
`ValidateModelRequest` from `studio/backend/models/inference.py`. It
fails if any field it prices cannot ride `LoadModelRequest` or is not
forwarded. It also table-tests the llama-server knob rule and checks
that every path sends one request.
- **Frontend:** `npm test` gives 13,857 passed. The 3 failures are
HTML/TextEdit charset decoding tests that fail the same way on `main` in
this environment. Typecheck is clean with both `bun check` and `tsc`.
- **Python contract tests:** the 30 files in `tests/studio` that read
these sources give 807 passed and 63 skipped. The two Playwright files
cannot import here, on `main` too.
- **The auto-load harness** (`test_chat_autoload_failure_gate.py`) now
inlines the real `load-request.ts` instead of a copy; all 81 scenarios
pass.
- **Rewritten tests:** text-matching tests that counted the duplicated
literals now assert one request per path. The rule they pinned is tested
behaviourally in the new file.

| Case | Before | After |
|---|---|---|
| GGUF load with Checkpoints, draft KV dtype or a per-GPU split |
`/validate` sent none of the three; used default checkpoints and could
resolve inherited flags differently | Same fields as `/load` |
| Picker or compare load with a DFlash/DSpark drafter | Preflight sized
Auto rather than the selected speculative mode | Selected mode
forwarded, as in `/load` |
| Model switch from a staged config with a context length and manual
layers | Preflight sized Auto context and Auto layers | Sized like
`/load` |
| Compare or auto-load of a diffusion GGUF with remembered extra args |
Args and tuning sent to a runner that takes none | Not sent, as the
picker already did |

Not in this PR: auto-load still ignores a model's saved engine
(vLLM/SGLang) and loads it on the default engine. That looks deliberate
(background loads avoid starting a managed engine), so it is left as is.

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Prior Chats contain Links to "Switch Back to Original Model" but CTX of "Original Model" Loads @ 4096

3 participants