Skip to content

Studio: compact long chats on API models too - #12786

Merged
Lyxot merged 30 commits into
unslothai:mainfrom
NilayYadav:enable-auto-compaction-external-api
Oct 6, 2026
Merged

Lyxot merged 30 commits into
unslothai:mainfrom
NilayYadav:enable-auto-compaction-external-api

Conversation

@NilayYadav

Copy link
Copy Markdown
Collaborator

Auto-compact only applied to local GGUF and MLX chats. A long chat with an API model kept sending every turn until the provider refused it with a "maximum context length" error, even with Auto-compact on.

With Auto-compact on, Claude models that support compaction and OpenAI models now summarize older turns on the provider side at three quarters of the model's window, capped at 200k tokens. The summary is saved with the reply and sent back on later turns. Other API models drop their oldest complete turns before the request goes out, leaving room for the full Max Tokens reply in the window. If Max Tokens would leave almost no room, it is lowered for that request so recent turns still fit. The existing notice and toast say when a chat was compacted.

With Auto-compact off, requests are exactly as before.

Lyxot added 2 commits October 6, 2026 14:28
The item only reached the client as a tool event, so every later round of the same turn resent the uncompacted history and the provider compacted it again. The loop now replays it after the messages it covers on each later request.
… that fit

Retrieved passages and tool results grow the prompt after the route fitted it, so the transport fits each request again, without the saved-transcript boundary. The reply cap is only lowered when the prompt plus the cap would overflow the window.
@Lyxot

Lyxot commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Pushed two follow-up commits after reviewing and live-testing this branch.

What changed

  • 357c26b25e replays an OpenAI Responses compaction item on later rounds of the same tool-loop turn. It previously only reached the client as a tool event, so every later round resent the uncompacted history and the provider compacted it again.
  • 6088a26eb9 fits every request the tool loop sends for providers Unsloth trims itself, since retrieved passages and tool results grow the prompt after the route's fit. These refits ignore the saved-chat boundary, which counts messages of the saved transcript rather than the loop's working copy. Max Tokens is now only lowered when the prompt plus the cap would overflow the window, so a short chat keeps a large reply cap.

Tested

  • Each new test fails when its production change is reverted. The touched backend suites pass locally (147 tests).
  • Live against OpenRouter (meta-llama/llama-3.2-3b-instruct, real 131072 window): with Auto-compact off a 122-message chat is rejected with the provider's maximum-context error, and with it on the same chat is answered after the oldest 58 messages are dropped.
  • Live in the UI at the real window: a chat of six ~13k-token turns compacted, showed the notice, kept its boundary on the next turn and recalled the latest turn.
  • Live tool-loop run (web_search) with Auto-compact on completes.
  • Not exercised live: Anthropic and OpenAI server-side compaction (mocked tests only).

Known and left out to keep this small

  • An Azure deployment that rejects compact_threshold is retried without compaction and gets no local trimming.
  • Trims made inside a tool loop are not announced; the next user turn's notice reports them.
  • The token estimate charges long unbroken text at 2 characters per token, so minified JSON compacts at about 40% of the window where source code compacts at about 61%.

Lyxot added 3 commits October 6, 2026 14:43
…ction

The retry after `compact_threshold is not enabled` only dropped context_management and resent the whole history, so such a deployment got neither compaction nor trimming. The retry now sends the locally fitted history and reply cap.
previous_response_id and the image replay items gathered before the compaction item stayed set, so the request mixed stateless compaction replay with response chaining.
@Lyxot

Lyxot commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Follow-up on the changes pushed above: the head 761b563677 was checked on a staging PR with the same head, and both the Codex review and CI have finished.

Codex review: converged on 761b563677 with "Didn't find any major issues": Lyxot#137 (comment)

CI on the same head: 60 passed, 2 failed, 4 skipped. Neither failure comes from this PR:

  • seam-guard fails because main added the qwen-image-layered family without a vae_tile_configs.json entry. This PR touches no VAE or image file.
  • Frontend build + bundle sanity fails at the "Locale parity" step because the settings.data.manageFiles.* keys are missing from the locale overlays on main. That step stops the job before typecheck and unit tests, so both were run locally on this head: npm run typecheck is clean and npm test passes 10617 of 10617.

What changed during this round:

  • 7a40dc6c00 trims locally when a deployment refuses server-side compaction. Previously the retry dropped context_management and resent the full history, which the deployment then rejected for length.
  • Merged the latest main.
  • 761b563677 drops the image-generation chain state that a replayed compaction item already covers, so the request no longer references items the provider has compacted away.

Raised in review and left out to keep this PR small:

  • A saved compaction summary can sit at a different position in a tool round's working copy than in the saved transcript.
  • Non-streaming Responses calls do not return the compaction item or truncation metadata.
  • Trims made between tool-loop rounds are not announced in the chat.
  • Durable stream recovery does not restore the provider compaction metadata.
  • Image, audio, and video parts count as zero tokens in the local fit, so a media-heavy chat sitting right at the threshold can still be rejected. The 25% headroom absorbs about twenty full-size images on a 128k window.

Each of these behaves the same as it does without this PR, so none is a regression.

@mahiatlinux

Copy link
Copy Markdown
Contributor

Review and verification evidence

Reviewed and repaired source head 37f59149d22a582ef771337a98181379f406dfdf. Its tree eb524c410239be1fc7e40157631f6d50cc2af9ed exactly matches converged mirror head 7471e3c2f93796eac34e82776ee2f37e6d005246, based directly on the contributor's updated pre-review head 761b5636778aa854567f32c55d526da693aa7391. Twenty genuine findings across sixteen review rounds were reproduced and fixed. The repaired paths now:

  • fall back to local fitting when a Responses endpoint rejects context_management, remember that rejection across tool-loop turns, and return context_truncated for successful non-stream Responses completions after either direct fitting or rejection fallback;
  • clear incompatible OpenAI replay/image-chain state at a compaction boundary, refit every external tool-loop request, and replay live provider compaction on the assistant subturn that produced it;
  • persist and replay Anthropic summary/encrypted compaction state once, accumulate fragmented deltas, treat failed content: null compaction as a no-op, and include separately billed compaction iterations in usage totals;
  • budget external media and the exact Studio/MCP tool schemas, preserve compaction and its serialized tool-call boundary through durable recovery, and ignore provider-summarized boundaries during local fitting;
  • scope opaque replay to the exact provider, model, saved connection and endpoint/API identity, and preserve that complete compatible tuple across continuation runs.

The contributor's later image-chain fix and updated-main reconciliation were retained. One additional review suggestion was rejected because a positive tool-call boundary makes that turn ineligible for continuation by construction; the continuation gate regression pins that behavior. The comment/docstring cleanup remained AST-equivalent.

Functional verification

  • Final-tree focused compaction matrix (external_auto_compaction, openai_compaction, anthropic_compaction, custom_provider_api_type) -> 82 passed, with five pre-existing async response-cleanup warnings.
  • Final-tree expanded provider, Studio tool-loop, durable replay, usage and cancellation matrix across nine changed backend test modules -> 285 passed, with nine pre-existing async response-cleanup warnings.
  • Final-tree checkpoint-compaction suite -> 166 passed.
  • Final-tree focused frontend compaction, continuation, recovery, approvals and context-window matrix -> 241 passed.
  • Frontend TypeScript typecheck and production build passed; the build emitted only existing CSS pseudo-element and large-chunk warnings.
  • Ruff passed on all reconciled backend implementation and regression files; git diff --check passed.
  • GitGuardian passed on the converged mirror tree, and every review thread is resolved.
  • Regression tests were mutation/negative-checked against the corresponding pre-fix heads, including rejection fallback, tool-loop rejection memory, failed Anthropic compaction, cross-connection replay, provider-summary boundary handling, continuation state, and non-stream truncation metadata.
  • A user-authorized low-cost live OpenRouter smoke call to openai/gpt-4o-mini returned exactly OK (10 prompt tokens, 1 completion token). The credential was kept only in a transient environment and unset immediately; all compaction edge cases used deterministic mocked providers.

Review convergence

Codex reviewed the exact tree at mirror commit 7471e3c2f9 and reported no major issues: final exact-head review. All prior inline findings were answered and resolved. No approval was submitted.

UI evidence

Expected: the merge base says older messages were dropped and reports 4 messages dropped here; the repaired head says the provider summarized older messages and reports 4 messages summarized here.

Observed on both isolated exact-tree Studio builds: provider-summarized false -> true, Unsloth-dropped true -> false, summarized count false -> true, and dropped count true -> false.

Before and after compaction notice

Full baseline image | Full repaired image | Evidence branch

The refreshed UI run used isolated full Studio installs on Linux x86_64 with Chrome for Testing 153.0.8010.12, a 1440x900 viewport, and device scale factor 1.5. The photographed refs are source merge base 9df22eb1ec80848ae1849ad939be2ac381cbfb7b and reconciled mirror head 7471e3c2f93796eac34e82776ee2f37e6d005246, whose tree is byte-identical to landed source head 37f59149d22a582ef771337a98181379f406dfdf. The composite was opened and visually confirmed against the expected wording.

@mahiatlinux

Copy link
Copy Markdown
Contributor
image

@Lyxot

Lyxot commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Pushed three small commits on top of 37f59149d2 after reviewing and re-testing the new head locally.

What changed

  • 05092ce786 (tests only): three older tests still assumed the previous tool-loop replay shape and the old fit_messages argument, so they failed on 37f59149d2. They now follow the current behaviour.
  • 61ca0ee499: when a resumed reply (continue_final_message) was compacted and then called a tool, the loop merged the new assistant turn over the compaction replay message. The history had already been replaced by that message, so the follow-up request carried neither the history nor its summary. The loop now stops treating the turn as a continuation once the conversation has been replaced.
  • 5eeb6e7a14: tool-enabled chats on providers without server-side compaction no longer read the chat's saved trim boundary, so the cut point moved on every turn and the provider's prompt cache kept missing. Every tool-loop fit now starts from the saved boundary, and the unused saved_transcript switch is removed.

How it was tested

  • The eleven backend test files this work touches pass (302 tests). Each new test failed before its fix.
  • Frontend typecheck is clean and the unit tests pass (10623).
  • Live against OpenRouter: a chat past a 131072-token window is rejected with Auto-compact off and answered with it on; with a local tool in the Unsloth tool loop, the request is refitted on the second round after the tool result and both trims are announced in the stream.

Not covered: Anthropic and OpenAI server-side compaction have unit coverage only here; no keys for those providers were available for a live run.

Seen in review and left as is: Anthropic compaction tokens are folded into prompt_tokens, so the context bar overstates usage on the turn that compacts; a non-streaming custom Responses reply with a compaction item returns list content rather than a string; after a mid-loop compaction on Anthropic, a promoted MCP image is no longer folded into the tool result.

@Lyxot

Lyxot commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The current head 3f75ed6141 was checked on a staging PR with the same head; the Codex review and CI have both finished.

Codex review: converged on 3f75ed6141 with "Didn't find any major issues": Lyxot#137 (comment)

CI on the same head: 60 passed, 2 failed, 4 skipped. Neither failure comes from this PR, and both fail the same way without it:

  • seam-guard: main added the qwen-image-layered family without a vae_tile_configs.json entry. This PR touches no VAE or image file.
  • Frontend build + bundle sanity: fails at the "Locale parity" step on settings.data.manageFiles.* keys missing from the locale overlays on main. That step stops the job before typecheck and unit tests, so both were run locally on this branch: typecheck is clean and the unit tests pass (10623).

Changed since the previous update

  • e57d18cd82: formatted test_anthropic_compaction.py, which the repo's formatter check flagged. Formatting only.
  • 3f75ed6141: tests/studio/test_cancelled_turn_history_prune.py runs the chat send path lifted out of chat-adapter.ts, which now reads the provider compaction target. The harness declares those values so its five failing tests pass again. Test only.

Live check of Anthropic server-side compaction

Run through Unsloth Studio with Claude Sonnet 4.6 reached over OpenRouter's Anthropic-shaped endpoint, on a 60k-token chat with a 50k threshold:

  • A long chat compacts, shows the summarized notice and answers correctly.
  • The next turn replays the saved compaction: the prompt was 164 tokens rather than 60k and nothing was compacted again.
  • In the tool loop, a request that starts with the compaction message is accepted, the tool runs and the answer is correct.
  • With tools defined, Anthropic returned a compaction block with content: null on the first round every time. That block is skipped, the full history is kept, and the real compaction lands on the next round, so such a turn pays for compaction twice.

OpenAI server-side compaction still has unit coverage only: OpenRouter accepts context_management but drops it, so it needs a direct OpenAI or Azure key to exercise.

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

Reviewed and tested locally and live. Local trimming works against OpenRouter, and Anthropic server-side compaction works end to end with Claude Sonnet 4.6, including the tool loop. Codex found no major issues on this head, and the two failing checks come from main, not this PR.

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.

4 participants