Skip to content

Studio: add Chat settings to disable or ease GGUF auto-compaction - #9774

Merged
mahiatlinux merged 48 commits into
unslothai:mainfrom
Souravrajvi0:feat/auto-compaction-settings-7bf8
Aug 27, 2026
Merged

mahiatlinux merged 48 commits into
unslothai:mainfrom
Souravrajvi0:feat/auto-compaction-settings-7bf8

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #9671.

Local GGUF chats always sent context_overflow: "truncate_oldest", so Studio compacted at the configured context length (not free VRAM), then either reset the conversation (checkpoint, the default) or trimmed extra history (~25% of the prompt budget) so the boundary could stay put.

This adds Chat settings to control that, without changing VRAM estimation:

  • Auto-compact long chats (default on). Off omits context_overflow, so a full window errors instead of silently dropping history.
  • When context fills
    • Reset conversation (default) — same as today
    • Drop oldest turns, with extra trim of ~25% / ~10% / ~5% / none

Checkpoint vs sliding window is a per-request context_policy override of UNSLOTH_CONTEXT_POLICY. The extra trim is a per-request compaction_headroom_ratio override of ROLLING_COMPACTION_HEADROOM_RATIO. Unset requests keep process defaults, so API clients are unchanged.

Tests

  • Frontend: tests/auto-compaction-settings.test.ts, tests/rolling-context-window.test.ts, settings search / chat-settings payload round-trip tests
  • Backend: headroom override, context_policy=rolling forces the sliding window even when checkpoint is the process default, Chat settings payload bounds

Local GGUF chats always opted into truncate_oldest, then compacted at the
prompt budget with a 25% extra trim (or a full checkpoint reset). Settings
now let you turn that off, switch to a sliding window, and choose how much
extra room a rolling compaction takes. Compaction still keys off the
configured context length, not free VRAM.
@mahiatlinux

Copy link
Copy Markdown
Contributor

@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: 53cdb3e071

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Resolved
Send checkpoint/error overflow fields from Studio so Chat settings override
UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin
sticky boundaries when a request forces rolling, and route search_conversation
from the same effective policy as the fitter.
@danielhanchen

Copy link
Copy Markdown
Member

The direction here is right, but chat-adapter.ts re-implements the same branching that ggufCompactionRequestFields already covers, so the tested helper is never called on the real request path. Could you have the adapter spread that helper instead?

@Souravrajvi0

Souravrajvi0 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Done in 0d87970 — createOpenAIStreamAdapter now spreads ggufCompactionRequestFields(...) on the live GGUF request instead of inlining the overflow / policy / headroom branch. The unit tests cover that helper, and the adapter is the call site.

@mahiatlinux

Copy link
Copy Markdown
Contributor

Fixed and pushed in a47aaf7cb after merging the latest PR head.

Findings and fixes

  1. Prior Studio local-tool turns could bypass context fitting. The backend only recognized the legacy search_conversation history shape, so histories containing other Studio tools such as python could be classified as upstream tool passthrough and sent around rolling or checkpoint compaction. The frontend now marks surviving history only when every prior tool call has local Studio provenance. The backend accepts that marker only when the request has real tool history and no supplied upstream tools catalog. Mixed, unmarked, and catalog-backed histories stay on the conservative path. The strict legacy fallback remains for older clients.

  2. The frontend default silently overrode the server compaction policy. A new chat sanitized to rolling and always serialized that policy, so a server started with UNSLOTH_CONTEXT_POLICY=checkpoint still received rolling requests. The settings model now has an explicit inherit state and uses it by default. Inherit sends context_overflow: truncate_oldest without request-level policy or headroom fields, so the backend process setting remains authoritative. Explicit checkpoint and rolling selections are unchanged.

  3. Explicit zero headroom still discarded at least 5% of the fitted context. The rolling fitter applied its minimum chunk clamp even when headroom_ratio=0, so "none" did not mean none. The minimum chunk cap now applies only when positive headroom was requested. Zero headroom trims to the exact target.

Regression coverage

  • Added frontend tests for inherited, explicit checkpoint, and explicit rolling request payloads.
  • Added frontend provenance tests for local-only, mixed, unmarked, and no-tool histories.
  • Added backend tests proving zero-headroom compaction drops only the required oldest turn.
  • Added backend tests proving inherited policy preserves the server setting.
  • Added backend tests proving prior local python tool history still reaches rolling compaction while mixed or unmarked history does not gain the exemption.

Validation

  • Frontend serial full suite: 5,210 passed.
  • Frontend typecheck, production build, i18n parity, model catalog, and bundle budget: passed.
  • Focused backend compaction, settings, and tool-history suites: passed.
  • Backend full suite reached 21,495 passed and 170 skipped before the local run was stopped. Its one recorded failure was the existing static controller-sanitization guard in test_control_markup_neutralize_7066.py, outside these compaction changes.
  • Full official workflows are running on the staging PR: PR #9774 staging CI mahiatlinux/unsloth#4

The fixes are split across eight focused commits, plus merge commits needed to bring the branch onto current main and the latest contributor head.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

Souravrajvi0 and others added 8 commits August 27, 2026 04:04
…n-settings-7bf8

Keep main's checkpoint-recall helper on the GGUF tool-loop gate, and pass
the request into _checkpoint_needs_search so Chat compaction settings still
override the process context policy.
… moves

Source-inspection contracts still pointed at openai_chat_completions after
unslothai#9187 split produce_openai_chat_completions out, and at strings that unslothai#7880
and unslothai#9683 moved. Point them at the live sites and defer PEP 604 unions in
the new kv-cache estimate tests.
tests/studio/test_pip_cache_naming.py was already listed at line 141 of
.github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites
step collected it twice. The trailing newline it also removed goes back.
fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`,
but keeps_boundary = False zeroes the headroom for every threadless API request
and incognito chat. Those callers send no new field, so they were handed the
"no extra trim" behaviour anyway: on a 201-message transcript at
context_length 1100 eviction fell from 12 messages to 2.

Gate it on the requested ratio instead, so only a caller that actually asked
for no extra trim gives the floor up.
_sticky_compaction_boundary rejected any boundary whose recorded policy differed
from the process policy, in both directions. The rolling-to-checkpoint direction
is only unsafe where fit_checkpoint_context would read the boundary as an epoch
already in force and skip the reset's recall, and that needs _can_reset_epoch.

Threads it refuses -- a template that cannot render tools, --disable-tools, no
conversation archive -- compact through fit_rolling_context and record a rolling
boundary, so on a checkpoint-default server every later turn discarded it and the
boundary slid again. Measured on a stored boundary of 6: base restored 6, this
branch returned 0.

Each call site now computes _can_reset_epoch once and hands the same value to the
boundary read and to the fit.
refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried
it through extra = "allow", which coerces nothing. A client sending the JSON
string "false" reached _only_studio_tool_history as a truthy value and moved the
count onto the Unsloth tool path the completion never takes, so the context-usage
bar priced a different prompt. The model's own bypass_permissions field is
declared for the same reason.
Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced
its docstring with three lines that say what the marker is and no longer say why
the strict route exists: a replayed tool pair read as a client contract sends the
turn to the llama-server passthrough, which runs no context fit, so the epoch,
the carried-forward block and the automatic recall are gone one turn after the
compaction that created them. Put that back, and match the sentence case the rest
of the file and the api.ts field comments use.
@mahiatlinux

Copy link
Copy Markdown
Contributor

Review and fixes

Reviewed the branch at ecc9e4f against its merge base 54367e5, ran the A/B where behaviour could differ, and pushed five commits. Every claim below was measured, not read off the diff.

Environment: macOS 27.0.0, Python 3.13 in a per-worktree uv venv, Node 24.16.0. No GPU, so no training, CUDA, Triton or quantisation checks ran.

What was found

1. A rolling boundary was discarded on every turn for threads that cannot start an epoch (studio/backend/core/inference/llama_cpp.py)

The _sticky_compaction_boundary policy check rejected any boundary whose recorded policy differed from the effective policy, in both directions. The checkpoint-to-rolling direction is right: a reset-sized cut replayed under rolling hands nothing back. The other direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs the request to be able to reset at all.

_can_reset_epoch returns false whenever the model's template cannot render tools, the tool loop is off, or the conversation archive is unavailable. Those requests compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn threw it away and the boundary slid again, which is the thing sticky_dropped exists to stop.

Measured on a stored boundary of 6 with UNSLOTH_CONTEXT_POLICY=checkpoint:

base 54367e5 head ecc9e4f fixed
_sticky_compaction_boundary("t1"), request cannot reset 6 0 6
same, request can reset 6 0 0
checkpoint-origin boundary under UNSLOTH_CONTEXT_POLICY=rolling 0 0 0

Each of the three call sites now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit, so the two cannot disagree.

2. The eviction bite changed for requests that sent no new field (studio/backend/core/inference/context_window.py)

fit_rolling_context gated the 5% floor on each eviction bite on headroom > 0. keeps_boundary = False zeroes the headroom for every threadless API request and every incognito chat, none of which chose anything, so they were handed the "no extra trim" behaviour anyway. That contradicts the PR description's "Unset requests keep process defaults, so API clients are unchanged".

Measured on a 201-message transcript with keeps_boundary = False and no headroom_ratio, context_length = 1100, max_tokens = 100:

dropped prompt after
base 54367e5 12 941
head ecc9e4f 2 991
fixed 12 941

The floor is now gated on the requested ratio, so only a caller that actually picked "no extra trim" gives it up. The zero-headroom behaviour the PR added is unchanged where it was asked for: test_zero_headroom_drops_only_the_oldest_turn_needed_to_fit still passes untouched.

3. studio_tool_history was undeclared on the token-count request (studio/backend/models/inference.py)

refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for exactly this reason and says so in its description. Declared it the same way; "false" now coerces to False.

4. A duplicate entry in .github/workflows/workflow-trigger-lint.yml

tests/studio/test_pip_cache_naming.py was already listed at line 141, so the Workflow guard suites step collected it twice. Unrelated to this PR, along with the trailing newline it removed. Both reverted to the base file.

5. The renamed tool-history helper lost the constraint it documented (studio/backend/routes/inference.py)

_only_studio_memory_tool_history to _only_studio_tool_history replaced the docstring with three lines that say what the marker is and no longer say why the strict route matters: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Restored that, and matched the sentence case the rest of the file and the neighbouring api.ts field comments use.

Verification

Each fix ships with a regression test, and each test was mutation-checked by reverting only the source change:

  • test_a_request_that_cannot_reset_still_replays_its_rolling_boundary fails with the two-way policy check (assert 0 == 6)
  • test_a_request_that_chose_nothing_keeps_the_eviction_size_it_always_had fails with the headroom > 0 gate (assert 2 == 12)
  • test_the_count_request_declares_the_studio_tool_history_marker fails without the field declaration (studio_tool_history == 'false')

Suites run:

  • studio/backend/tests/test_checkpoint_compaction.py, test_context_overflow_truncation.py, test_chat_settings_payload.py, test_conversation_recall_injection.py: 287 passed. The one failure, test_the_reachability_probe_closes_the_connection_it_opens, reads /proc/self/fd and fails identically on the base commit; it is a macOS-only environment limit, not a regression.
  • Whole studio/backend/tests suite, head versus this branch on the same interpreter and dependency set: the failure sets compare equal name for name. The only difference across runs was test_streaming_stripper.py::test_early_markup_is_not_slower_than_the_code_it_replaces, a timing-sensitive test that flipped between runs on both trees. The ~248 failures common to both are this laptop missing torch, transformers, peft and torchao, which CI installs.
  • tests/studio modules this PR touches: 306 passed.
  • Frontend: npm test 5653 passed, 0 failed. npm run typecheck clean. npm run i18n:check:strict reports 0 missing keys across all 12 locales, and all 11 new keys are present in each.
  • ruff check studio/backend clean.
  • Merges cleanly into current main.

Not covered

  • No GPU here, so no live GGUF chat drove a real compaction end to end. The fits, the boundary reads and the request shapes are covered by unit tests against the real functions.
  • No UI screenshots. The two new Chat settings rows render from existing SettingsRow, Switch and Select primitives with translated labels; nothing about their appearance is new.
  • Whether an already-compacted thread that switches policy mid-conversation behaves well over many turns in a real session, as opposed to per-fit, is untested on either tree.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@mahiatlinux
mahiatlinux force-pushed the feat/auto-compaction-settings-7bf8 branch from 3a0ce7e to ecc7384 Compare August 27, 2026 05:21
@mahiatlinux

Copy link
Copy Markdown
Contributor

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

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

pre-commit-ci Bot and others added 2 commits August 27, 2026 05:28
A request that may not reset still takes the checkpoint REPLAY branch in
_fit_context under a checkpoint policy, so the rolling-origin boundary the
previous commit restored reached fit_checkpoint_context and read as an epoch
already in force. The fit returned checkpoint_started false, and
_archive_and_recall reads that as "already recalled" and injected nothing.
Measured at context_length 1800 with a stored boundary of 30: the reply lost the
archived turns the rolling fallback would have pulled back.

_sticky_compaction_state now returns the depth and whether a checkpoint reset
recorded it, mixed provenance across surviving rows counting as rolling since
min(boundaries) may pick either row. _fit_context takes that as
sticky_is_checkpoint and enters the replay branch only for a real epoch;
otherwise the count stays on the rolling fitter, which reports no
checkpoint_started and still recalls.
@mahiatlinux

Copy link
Copy Markdown
Contributor

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

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

Phase one of fit_rolling_context re-applies the saved boundary before anything
else and returns as soon as the result fits, so an already-compacted chat that
moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and
never reached the phase that reads the new ratio. Lowering the setting did
nothing at all, and the history the client had re-sent stayed dropped.

The persisted truncation now carries boundary_headroom_ratio beside
boundary_messages and boundary_anchor, written through one _boundary_metadata
helper so the three cannot drift apart. _sticky_compaction_state refuses a
rolling boundary recorded under a larger ratio than this request wants; a larger
request needs no refusal, since phase two moves the boundary out by itself. Rows
saved before the ratio existed carry no key and replay as they did, and a
checkpoint reset ignores headroom so its depth is never refused over it.
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 07f9db9fcc

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

@mahiatlinux

Copy link
Copy Markdown
Contributor

@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: 07f9db9fcc

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

The previous commit only refused a boundary recorded under MORE headroom than
the request asked for, on the reasoning that phase two would widen a shallower
one by itself. It does not: phase one re-applies the saved count and phase two
runs only when the result still does not fit, so a shallower boundary that
already fits is just as inert. Measured on a 121-message transcript at
context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and
0.25, so raising the setting did nothing either.

Compare for equality instead. With the 5%-origin boundary of 86 above, a request
at 0.05 still replays it and a request at 0.25 recomputes to 94.
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: b790abb8c6

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

@mahiatlinux mahiatlinux 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.

All reviewed and fixed, LGTM. https://github.com/unslothai/unsloth/actions/runs/33053837580

Eight fix commits on top of the original work, Codex converged clean on b790abb8c ("Didn't find any major issues"), and all ten review threads are resolved.

CI on b790abb8c: 41 passing, 6 failing. Every one of the six is a pre-existing main breakage that reproduces with this branch absent, at the identical job and step:

Failing check Step Reproduced on main
Frontend build + bundle sanity Browser smoke for ANSI tool output 33044821662, 33041836046, 33040513019
Repo tests (CPU) Repo tests (CPU, auto-discovered) 33052756239, 33052084858, 33049388996
Core (HF=default + TRL=default) unsloth_zoo @ main — full pytest (CPU) 33049388896
Core (HF=4.57.6 + TRL<1) unsloth_zoo @ main — full pytest (CPU) 33049388896
Core (HF=latest + TRL=latest) unsloth_zoo @ main — full pytest (CPU) 33049388896
Chat UI, API, Update and GGUF inference Assert llama.cpp loads on this macOS 33044821603, 33041836104

The frontend one is a real bug and worth its own fix: the ANSI smoke dies on Cannot access 'CHAT_GPU_MEMORY_MODE_KEY' before initialization, a module cycle reached through the @/features/chat barrel. Same error text on a main-only run. Frontend CI last passed on main at fd31302d1 and has been red on every commit since 3fd9dc0e8 / 54367e591, the latter being this PR's own merge base. The three Core legs fail against unsloth_zoo @ main, a moving external dependency, and all three fail on main where only two fail here. main additionally fails (Python 3.13) :: Backend tests, which passes on this branch.

None of the six is caused by this PR, and none is fixable from inside it without mixing an unrelated main repair into a feature change.

What the eight commits fixed

Backend correctness, each with a regression test that was mutation-checked by reverting only the source change:

  1. A rolling boundary was discarded every turn for threads that cannot start an epoch. _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. _can_reset_epoch is false whenever the model's template cannot render tools, the tool loop is off, or the archive is unavailable, and those threads compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server the boundary slid again on every reply. Measured on a stored boundary of 6: base restored 6, the branch returned 0.
  2. A rolling boundary reached the checkpoint replay branch. A request that may not reset still takes that branch, so the boundary restored by (1) was read as an epoch already in force: fit_checkpoint_context returned checkpoint_started false and _archive_and_recall injected nothing. Measured at context_length=1800 with a boundary of 30. _sticky_compaction_state now reports provenance and the branch fires only for a real epoch.
  3. Changing the extra-trim ratio did nothing on an already-compacted chat. Phase one of fit_rolling_context re-applies the saved count and stops once the result fits, so the phase that reads the new ratio never ran. Measured on a 121-message transcript at context_length=1600: a stored boundary of 86 gave dropped=86 under both 0.05 and 0.25. The truncation now carries boundary_headroom_ratio and a changed ratio forces a refit. Both directions, after Codex correctly pointed out my first attempt only handled decreases.
  4. The eviction bite changed for requests that sent no new field. The 5% floor on each bite was gated on headroom > 0, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Measured at context_length=1100: eviction fell from 12 messages to 2 for a caller sending nothing new, contradicting "API clients are unchanged". Gated on the requested ratio instead.
  5. studio_tool_history was undeclared on ChatCountTokensRequest. It arrived through extra = "allow", which coerces nothing, so the JSON string "false" read as truthy and moved the count onto the Unsloth tool path the completion never takes.
  6. A duplicate tests/studio/test_pip_cache_naming.py in .github/workflows/workflow-trigger-lint.yml, already listed at line 141, plus a removed trailing newline. Unrelated to this PR; reverted to the base file.
  7. The renamed tool-history helper lost the constraint it documented, and its docstring was restored along with the sentence case the rest of the file uses.

Verification

  • test_checkpoint_compaction.py, test_context_overflow_truncation.py, test_chat_settings_payload.py, test_conversation_recall_injection.py: 291 passed. The single failure, test_the_reachability_probe_closes_the_connection_it_opens, reads /proc/self/fd and fails identically on the base commit; a macOS-only environment limit.
  • Whole studio/backend/tests suite, unmodified head versus this branch on the same interpreter and dependency set: failure sets compare equal name for name across four runs. The ~248 common failures are this laptop missing torch, transformers, peft and torchao.
  • Frontend: npm test 5653 passed, 0 failed. npm run typecheck clean. npm run i18n:check:strict reports 0 missing keys across all 12 locales.
  • ruff check studio/backend clean. Merges cleanly into current main.

Not covered

  • No GPU here, so no live GGUF chat drove a real compaction end to end. The fits, boundary reads and request shapes are covered by unit tests against the real functions.
  • No UI screenshots; the two new Chat settings rows render from existing SettingsRow, Switch and Select primitives.
  • Multi-turn behaviour of a policy switch in a real session, as opposed to per-fit, is untested on either tree.

@mahiatlinux
mahiatlinux merged commit 2ea0a3c into unslothai:main Aug 27, 2026
45 of 51 checks passed
danielhanchen pushed a commit that referenced this pull request Aug 27, 2026
)

* Studio: add Chat settings to disable or ease GGUF auto-compaction

Local GGUF chats always opted into truncate_oldest, then compacted at the
prompt budget with a 25% extra trim (or a full checkpoint reset). Settings
now let you turn that off, switch to a sliding window, and choose how much
extra room a rolling compaction takes. Compaction still keys off the
configured context length, not free VRAM.

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

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

* Studio: honor Chat compaction settings over process defaults

Send checkpoint/error overflow fields from Studio so Chat settings override
UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin
sticky boundaries when a request forces rolling, and route search_conversation
from the same effective policy as the fitter.

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

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

* honor zero compaction headroom

* test zero-headroom rolling compaction

* preserve server compaction policy by default

* test server policy inheritance

* mark studio-owned tool history

* keep studio tool history on the fitted path

* isolate studio tool history provenance

* test compaction after local tool use

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

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

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

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

* complete locale settings translations

* fix sanitized catalog guard coverage

* run pip cache guard on workflow changes

* set utf-8 for pip cache guard reads

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

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

* mark studio tool history in token counts

* reset boundaries when context policy changes

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

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

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

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

* mark studio tool history from replayed calls

Hosted server builtins such as web_search are dropped during OpenAI
serialization, so ownership must be derived from the calls that actually
go on the wire. Mixed hosted-plus-local history can then keep the
studio_tool_history marker and stay on the compaction path.

* align prune contract test with token-count history builder

The send and count paths both prune through pruneOutboundHistory into
survivingMessages; the source contract still expected the old
outboundMessages name on the count path.

* align sticky and token-count harnesses with current compaction APIs

Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY
to rolling when faking studio_db. Recount and prune harnesses follow the
renamed token-count builder, a tighter setActiveThreadId slice, and the
send-path prune call rather than the earlier count-path copy.

* test(studio): follow main's chat-completions extract and VRAM/keyless moves

Source-inspection contracts still pointed at openai_chat_completions after
#9187 split produce_openai_chat_completions out, and at strings that #7880
and #9683 moved. Point them at the live sites and defer PEP 604 unions in
the new kv-cache estimate tests.

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

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

* drop the duplicate workflow guard entry this pr added

tests/studio/test_pip_cache_naming.py was already listed at line 141 of
.github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites
step collected it twice. The trailing newline it also removed goes back.

* keep the eviction bite for requests that chose no compaction setting

fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`,
but keeps_boundary = False zeroes the headroom for every threadless API request
and incognito chat. Those callers send no new field, so they were handed the
"no extra trim" behaviour anyway: on a 201-message transcript at
context_length 1100 eviction fell from 12 messages to 2.

Gate it on the requested ratio instead, so only a caller that actually asked
for no extra trim gives the floor up.

* replay a rolling boundary where the fit cannot start an epoch

_sticky_compaction_boundary rejected any boundary whose recorded policy differed
from the process policy, in both directions. The rolling-to-checkpoint direction
is only unsafe where fit_checkpoint_context would read the boundary as an epoch
already in force and skip the reset's recall, and that needs _can_reset_epoch.

Threads it refuses -- a template that cannot render tools, --disable-tools, no
conversation archive -- compact through fit_rolling_context and record a rolling
boundary, so on a checkpoint-default server every later turn discarded it and the
boundary slid again. Measured on a stored boundary of 6: base restored 6, this
branch returned 0.

Each call site now computes _can_reset_epoch once and hands the same value to the
boundary read and to the fit.

* declare studio_tool_history on the token-count request

refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried
it through extra = "allow", which coerces nothing. A client sending the JSON
string "false" reached _only_studio_tool_history as a truthy value and moved the
count onto the Unsloth tool path the completion never takes, so the context-usage
bar priced a different prompt. The model's own bypass_permissions field is
declared for the same reason.

* restore the constraint the renamed tool-history helper documented

Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced
its docstring with three lines that say what the marker is and no longer say why
the strict route exists: a replayed tool pair read as a client contract sends the
turn to the llama-server passthrough, which runs no context fit, so the epoch,
the carried-forward block and the automatic recall are gone one turn after the
compaction that created them. Put that back, and match the sentence case the rest
of the file and the api.ts field comments use.

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

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

* keep a rolling boundary off the checkpoint replay branch

A request that may not reset still takes the checkpoint REPLAY branch in
_fit_context under a checkpoint policy, so the rolling-origin boundary the
previous commit restored reached fit_checkpoint_context and read as an epoch
already in force. The fit returned checkpoint_started false, and
_archive_and_recall reads that as "already recalled" and injected nothing.
Measured at context_length 1800 with a stored boundary of 30: the reply lost the
archived turns the rolling fallback would have pulled back.

_sticky_compaction_state now returns the depth and whether a checkpoint reset
recorded it, mixed provenance across surviving rows counting as rolling since
min(boundaries) may pick either row. _fit_context takes that as
sticky_is_checkpoint and enters the replay branch only for a real epoch;
otherwise the count stays on the rolling fitter, which reports no
checkpoint_started and still recalls.

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

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

* discard a boundary cut with more extra trim than the request asks for

Phase one of fit_rolling_context re-applies the saved boundary before anything
else and returns as soon as the result fits, so an already-compacted chat that
moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and
never reached the phase that reads the new ratio. Lowering the setting did
nothing at all, and the history the client had re-sent stayed dropped.

The persisted truncation now carries boundary_headroom_ratio beside
boundary_messages and boundary_anchor, written through one _boundary_metadata
helper so the three cannot drift apart. _sticky_compaction_state refuses a
rolling boundary recorded under a larger ratio than this request wants; a larger
request needs no refusal, since phase two moves the boundary out by itself. Rows
saved before the ratio existed carry no key and replay as they did, and a
checkpoint reset ignores headroom so its depth is never refused over it.

* refuse a replayed boundary on any change of extra trim, not just a cut

The previous commit only refused a boundary recorded under MORE headroom than
the request asked for, on the reasoning that phase two would widen a shallower
one by itself. It does not: phase one re-applies the saved count and phase two
runs only when the result still does not fit, so a shallower boundary that
already fits is just as inert. Measured on a 121-message transcript at
context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and
0.25, so raising the setting did nothing either.

Compare for equality instead. With the 5%-origin boundary of 86 above, a request
at 0.05 still replays it and a request at 0.25 recomputes to 94.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: mahiatlinux <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

3 participants