Skip to content

Studio: summarize long cloud chats instead of dropping their oldest turns - #17743

Merged
danielhanchen merged 11 commits into
mainfrom
studio-cloud-compaction
Nov 14, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-cloud-compaction

Conversation

@shimmyshimmer

@shimmyshimmer shimmyshimmer commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

What changes for users

A long chat on a cloud connection is now summarized instead of losing its oldest turns. Until now, a connection whose provider does not compact server-side (every chat-completions connection: OpenRouter, DeepSeek, Mistral, Gemini, vLLM, SGLang, llama-server, Ollama and the rest, including Claude reached through a gateway) dropped its oldest turns once the chat passed 75% of the model's window. The thread showed "Older messages were dropped from the model's context to make room", and the dropped turns were archived and recalled inline when a later turn asked about them, but nothing carried the gist of the dropped part forward.

  • Summary instead of eviction. When a request would pass the threshold, Studio asks the same connection and model for a structured summary of the older turns, keeps the recent turns verbatim (up to 15,000 tokens or 30% of the prompt budget) and sends summary plus tail. The system prompt and pinned instructions are kept as before. The full transcript stays in the thread.
  • The summary is a turn, not part of the system prompt. It is written from chat and tool text, so it goes in as a user turn (with a short acknowledgement so strict chat templates keep alternating) instead of gaining system-prompt authority, and the evicting fit never drops it. The summary request also tells the model to leave instructions found in pages, documents and tool results out of the summary: live, an 8B model that had copied a fetched page's "system notice" into its summary and then obeyed it no longer does.
  • Summary plus recall. The summarized turns are archived as before, and on every turn that runs on a summary the existing conversation recall adds the exact passages the newest turn asks about, inside the existing recall budget. The summary gives continuity, recall gives the exact wording.
  • The summary is saved per thread and reused on later turns, so a chat is summarized once per compaction, not on every message. An edited or branched history gets its own summary.
  • Fallback. If the summary call fails, the previous behaviour (dropping the oldest turns, with recall) runs, so a chat never fails because of it.
  • /compact works on a cloud model. Anthropic and OpenAI (Responses) compact server-side, so /compact lowers their native trigger for that request. Everything else uses the summary call.
  • "Auto-compact after" in the connection form, in tokens, stored with the connection. It replaces the 75% default and can raise the trigger past the 200K default cap on server-side compaction, up to the model's window (neither vendor documents an upper limit, only Anthropic's 50K floor). Blank keeps today's defaults.
  • Overflow recovery. If a provider refuses a request as too long before any output, Studio compacts once and resends. A second refusal is shown as the error. This is off when auto-compact is off.
  • It is visible. The context meter shows a cloud model's window with a tick where the chat compacts, and the tooltip names the trigger. The thread shows "Earlier messages summarized" or "Older messages dropped" with a matching toast, and a progress state while the summary is written.
  • Compact chip. On a cloud thread over 50,000 tokens that has been idle past the provider's prompt cache lifetime, a Compact chip appears next to send. With auto-compaction on it starts on, and the next message is sent after a summary; one click keeps the full history for that message. With auto-compaction off it starts off, and only a click queues the summary.
  • Coding agents get the window of a hosted connection, and use more of it. unsloth start asks Studio for the window it passes to Claude Code, Codex and opencode. Hosted Anthropic and OpenRouter connections used to answer nothing, so the agents fell back to their own defaults (Claude Code assumes 200K for an ID it does not know). Studio now reads the window from the provider's model listing (Anthropic max_input_tokens, Gemini inputTokenLimit, OpenRouter context_length floored at its default route), under the same saved-key gate as the chat path, and from the daily models.dev catalog Studio already caches for providers whose listing has none (OpenAI), preferring its prompt cap where that is lower. Claude Code launched by unsloth start keeps 10% headroom only up to 32K tokens, so a 1M window compacts at 96% instead of 90%.

Local GGUF, MLX and managed engines (including the NPU checkpoint compaction from #17616) are unchanged.

Which path each connection takes

Connection Auto-compact
Anthropic (direct, models with server compaction) Server-side, compact_20260112 edit
OpenAI (direct, Responses) Server-side, context_management compaction
Every other chat connection, including Claude through OpenRouter or another gateway Unsloth summary plus recall
vLLM, SGLang, llama-server with no catalogued window Unsloth summary plus recall, trigger at 75% of the window the server reports (max_model_len, meta.n_ctx)

Things a reviewer should know

  • The first compaction on a thread adds one extra model call before the reply, billed on the same connection. A backlog too long for one call is folded in over several calls, eight at most.
  • A saved summary keeps applying to its thread, including after auto-compact is switched off, the same way a manual compaction of a local chat does.
  • Cloud models now show used / window with the ring in the chat header where the catalogue has a window. Before, they showed a bare token count.
  • New storage: table chat_thread_summaries in the chat database (removed with its thread) and a nullable auto_compact_tokens column on saved connections. Both are created on first use and older builds ignore them.
  • New request fields: compaction_uncapped, and compact_context is now honoured for cloud connections.
  • Merged with main: managed engines keep the checkpoint fit [Feature] AMD NPU: auto compaction for NPU chats instead of stopping at a full context window #17616 added for /compact epochs; cloud connections take the summary fit.

How it was checked

  • Backend: tests/test_cloud_summary_compaction.py covers the summary fit, reuse of a saved summary, the fallback to eviction, recall alongside a fresh and a reused summary, /compact on a cloud model including the native path, the connection setting and its clamps, the overflow retry with and without tools (refitted from the transcript, so a summarized thread folds its saved summary in rather than stacking a second one), archiving of summarized turns when more turns must also be dropped, every registered chat connection without server compaction, Claude through OpenRouter, and vLLM / SGLang / llama-server reached without a catalogued window. tests/test_connection_catalog_window.py covers the window reported to agents. The NPU, compaction, provider and tool transport test files pass with it.
  • Frontend: tests/cloud-compaction.test.ts plus the updated compaction tests. npm run typecheck and npm test pass.
  • Live against OpenRouter with the trigger set low: a 16.8K-token chat with a fact stated in its first turn was summarized by Unsloth to a few hundred tokens and both anthropic/claude-haiku-5.5 and meta-llama/llama-3.1-8b-instruct still answered with the fact. The window lookup returned 1,000,000, 1,047,576 and 131,072 for three listed models.

Not testable here

  • Server-side compaction on direct Anthropic and OpenAI (the /compact trigger and the raised cap) is covered by request-body tests only. No keys for those were available.
  • Recall in a live chat (it needs the embedding model); it is covered by tests with stub embeddings.
  • CPU-only machine: nothing here touches training or local inference.

Screenshot

Settings > Connections, new OpenRouter connection: the "Auto-compact after" field (left: main, right: this PR).

Before and after: Auto-compact after field

…urns

A chat on a cloud connection that outgrew its window lost its oldest turns
unless the provider compacted server-side. Every connection on the plain
chat-completions path went that way, including models reached through a
gateway.

- Summary compaction: when a request would pass the threshold, Studio asks the
  same connection and model for a structured summary of the older turns, keeps
  the recent ones verbatim (up to 15,000 tokens or 30% of the prompt budget)
  and sends summary plus tail. The summary joins the system prompt, pinned
  instructions stay verbatim, and the summarized turns are archived so
  search_conversation still reaches them. A backlog too long for one call is
  folded in oldest first.
- The summary is saved per thread (chat_thread_summaries, keyed by a digest of
  the turns it covers) and reused on later turns; an edited or branched
  history does not match and gets its own. The transcript itself is untouched.
- If the summary call fails, the old eviction runs, so the chat never fails
  because of it.
- /compact works on a cloud model. Providers with server-side compaction do
  it natively for that request (their trigger is lowered to the documented
  floor); everything else, and a thread too short for the native floor, uses
  the summary call.
- Connections have an "Auto-compact after" token setting, stored with the
  connection. It replaces the default of 75% of the window and may pass the
  200K default cap on server-side compaction up to the model's window. The
  documented 50K floor stays where it applies.
- If a provider refuses a request as too long before any output, Studio
  compacts once and resends. A second refusal is shown as the error. Off when
  auto-compact is off.
- The context meter shows a cloud model's catalogued window, marks where the
  chat compacts and names the trigger in its tooltip. The thread says
  "Earlier messages summarized" or "Older messages dropped" instead of one
  generic notice, and a progress frame is sent while the summary is written.
- A Compact chip appears next to send on a cloud thread over 50,000 tokens
  that has been idle past the provider's prompt cache lifetime. While it is
  on, the next message is sent after a summary; a click keeps the full history
  for that message.

Local GGUF, MLX and managed engines are unchanged.
@shimmyshimmer

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T14:40:16.546759Z 4053ad1 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

ℹ️ 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 +83 to +85
if (eligible && !kept && offeredRef.current !== offerKey) {
offeredRef.current = offerKey;
store.request(threadId);

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 Honor the auto-compaction preference before queuing a summary

When auto-compaction is disabled, returning to a saved cloud chat with at least 50,000 tokens after its cache lifetime still automatically queues compaction here: the chip never reads autoCompactEnabled. chat-adapter.ts consumes this request as compactNow, and apiCompactionRequestFields deliberately allows explicit compaction even with auto-compaction off, so the next message unexpectedly summarizes and replaces history despite the user's setting. Gate the chip's automatic request on that preference while preserving explicitly requested /compact operations.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Nov 14, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 7613dcd: with auto-compaction off the chip still offers the summary but only a click queues it.

Resolve against the NPU auto compaction (#17616): managed engines keep main's
checkpoint fit for /compact epochs, cloud connections keep the summary fit.
The summary gives continuity; the archive already holds the turns it replaced, so
recall their exact wording for the newest turn within the existing recall budget.
Covers each registered chat provider, Claude through OpenRouter, and vLLM, SGLang and
llama-server reached with no catalogued window (the served window sets the trigger).
unsloth start asks the served-window route for the window it passes to Claude Code,
Codex and opencode. Hosted Anthropic and OpenRouter connections answered nothing, so
agents fell back to their own defaults. Read the window from the provider's model
listing, under the chat path's saved-key gate; OpenRouter is floored at its default
route's window.
…it overflow from the transcript

When the summary was followed by an eviction, only the evicted turns were archived, so the
summarised ones were not searchable until a later turn. An overflow refusal refitted the
prompt that already carried the summary, adding a second summary block and saving a summary
whose boundary counted the tail instead of the transcript.

[skip ci]
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 14, 2026
…ructions out of it

The summary is written from chat and tool text, so it no longer joins the system prompt:
it is a user turn with an acknowledgement (strict templates keep alternating) that the
evicting fit protects. The summary request now tells the model to leave instructions found
in pages, documents and tool results out of the summary; live, an 8B model that copied a
fetched page's 'system notice' into the summary and obeyed it no longer does.
Gemini's listing carries inputTokenLimit. OpenAI's has no window, so hosted providers fall
back to the daily models.dev catalog Studio already caches, preferring its prompt cap
(limit.input) over the full window where it is lower.
The 90% auto-compact override held back 100k tokens on a 1M window. Keep 10% headroom only
up to 32k tokens, so a 1M window compacts at 96% (Claude Code's own default is ~967K) and
windows up to 320k keep 90%.

[skip ci]
… is on

With auto-compaction off the chip still offers the summary, but only a click queues it.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 7613dcda4e

ℹ️ 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 +514 to +516
if seen <= covered and id(message) not in keep_ids:
continue
result.append(message)

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 turn alternation when retaining pinned instructions

With ROLLING_INSTRUCTION_PIN_GROUPS enabled, pinned_instruction_ids() returns only the instruction message's identity, so this loop retains that user message but removes its assistant reply. A compacted conversation can therefore become system, user(summary), assistant(ack), user(pinned), user(latest), which strict chat templates reject. The subsequent _fit_external_context() returns immediately when the summarized prompt fits, so it does not repair this sequence. Preserve an assistant separator or the pinned turn's reply when retaining these instructions so compaction does not break chats on strict-template connections.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 4053ad1: pinned instructions inside the summarised range now go verbatim into the summary user turn, so the summary, acknowledgement and tail keep alternating; test updated.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 4053ad1393

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

@danielhanchen
danielhanchen merged commit b607a05 into main Nov 14, 2026
@danielhanchen
danielhanchen deleted the studio-cloud-compaction branch November 14, 2026 16:46
meefs pushed a commit to meefs/unsloth that referenced this pull request Nov 14, 2026
… and new connection types (unslothai#17753)

## What changes for the user

**Connections page**

- The page follows the standard settings layout: a "Your connections"
section and an "Add a connection" section, with no boxed panels.
- "Enable connections" is a pill switch in the page header.
- Every connection has a status: Connected, Needs API key, Key rejected,
No credit, Rate limited, Unreachable, Timed out, Sign in again or Off. A
healthy row shows its endpoint and models; a broken one shows a short
fix, with the server's full message on hover.
- Opening the page checks each connection at most once per ten minutes.
The header button shows how old the answers are ("Checked 2m ago") and
re-checks all of them.
- Every connection has an on/off switch. A switched-off connection stays
in the list, dimmed, and is offered in no model picker. The backend
already refused disabled connections; the UI could neither set the flag
nor show a row that had it.
- A provider gallery replaces the dropdown as the way to add a
connection. It has four groups (Popular, Local, More providers, and a
folded "Even more") and a search box. An empty list now shows the
gallery instead of opening a form with one provider preselected.

**Connection form**

- A pasted API key is checked as soon as it stops changing. The models
it reaches are listed and, for a new connection, the newest ones are
ticked. A rejected key is reported under the key field.
- "Add connection" with nothing ticked lists the models and ticks the
suggestions, instead of failing with "Load available models first".
- "Test connection" checks the form as typed, before saving.
- Token limit, extra headers, reasoning and new-model checks fold under
"Advanced settings", which opens by itself when one of them is in use.
- The provider dropdown uses the same groups and order as the gallery,
with pill hovers and a fade at the edge when there is more to scroll.
- The model list sits in a rounded box with edge fades and a scrollbar
that shows on hover. Rows show the model name only; hovering a row opens
a card with its inputs, reasoning levels and context window.
- Models released more than a year ago fold behind an "Older models"
link. A ticked model stays visible, search still finds folded ones, and
"Select all" only ticks what is showing. Release dates come from the
daily catalog refresh, so an existing install starts folding after its
next refresh.
- Each provider links to the page where its API key is created.
- Descriptions across the form are shorter.

## New connection types

Added to the gallery: xAI, NVIDIA NIM, Perplexity, Cohere, Vercel AI
Gateway, Azure OpenAI, Amazon Bedrock, Google Vertex AI and SGLang.

- Azure OpenAI, Amazon Bedrock and Google Vertex AI use the self-hosted
form: an endpoint, a key and typed model IDs.
- SGLang is a preset over the plain OpenAI-compatible form with its
default local URL.
- Types with no usable model list are checked by sending one 16-token
chat to the first model.

None of these was exercised with a real key. They were wired from each
service's published API reference.

## Backend

- `POST /api/providers/test` returns `error_kind` (`auth`, `billing`,
`rate_limit`, `not_found`, `unreachable`, `timeout`, `invalid_url`,
`other`) and has its own sentence for 402, 429 and read timeouts.
- A custom endpoint check reports a named cause from `/models` instead
of asking for a model ID or surfacing the fallback probe's plain 404.
- `GET /api/providers/registry` carries `api_key_url`.
- Catalog entries carry `released` (the model's release date) when the
source has a well-formed one.

All of these are additive. An older frontend ignores the new fields; the
new frontend falls back when an older backend omits them.

## Logos

- New transparent logos for the added connection types, plus transparent
single-colour marks for four existing ones that sat in a white or black
box. Single-colour marks invert in dark mode.
- The Microsoft logo used by the Model hub lost its grey background
square so one file serves both places.

## Fixes found on the way

- A model list answer that arrived after the form had moved to another
connection was written into that connection's form.
- The settings page and the sync it starts each fetched the registry;
they now share one request.
- The show/hide key button drifted off the input when a message rendered
below it.

## Behaviour changes worth a look

- An empty Connections page no longer jumps into the add form.
`tests/connections-empty-opens-form.test.ts` is rewritten for the new
behaviour.
- Opening the page now sends one check per enabled connection (a
`/models` call, at most every ten minutes). Connections without a key
are skipped.
- The form's "Clear" button on a new connection is now "Cancel" and
returns to the list.
- A manual connection check no longer toasts on success; the row's
status shows it. Failures still toast.
- The "Selected" filter in the model list is removed.
- Models over a year old are hidden by default in the model list.

## Branch history

The branch contains a commit for cloud summary compaction and a later
commit that takes it out again. That work has its own pull request
(unslothai#17743), so the net diff here is the Connections work only.

## Fixes during review

- SGLang is saved as a plain custom server. The preset fell through to
the OpenAI backend type, which sent every turn to `/v1/responses`,
applied OpenAI's sampling rules and skipped reading the server's window.
- A connection checked by a short chat (Azure, Bedrock, Perplexity,
Vertex) now reports Unreachable and Timed out; the client turns those
failures into error frames, which the check read as a plain failure.
- A shared connection of those types is checked with one chat on a model
the account may use, instead of a model listing it does not have.
- Switching provider while models load no longer leaves the form on
"Loading" with Save disabled.
- The shared-connection check test expects the new `error_kind` field.
- A switched-off connection keeps its browser-only options (output cap,
headers, prompt caching) across a reload; the off rows are now saved
like the on ones.
- Azure chats and checks no longer send `temperature`, `top_p` or
`presence_penalty`, which reasoning deployments reject; the deployment
name hides the model, as on the custom Azure path.
- NVIDIA NIM no longer offers an effort selector or thinking toggle: no
request field reaches its models.
- SGLang and Vertex read Studio tools, vision and thinking from the
registry type they are sent as (`custom`, `gemini`), so Search, Tools,
MCP and Docs stay on.
- A Gemini connection on Vertex's OpenAI-compatible `/endpoints/openapi`
URL stays on chat completions with Bearer auth, as before this PR;
native Vertex URLs use the Gemini API.
- Merged with main after unslothai#17743: the connection form keeps the
"Auto-compact after" field in this layout.

## How it was checked

- `npm run typecheck`, `npm test` (16286 pass, 0 fail) and `npm run
build` in `studio/frontend`.
- `pytest` on the provider test files in `studio/backend/tests`
(connection checks, model capabilities, new cloud providers): 105
passed.
- Driven by hand in a local CPU-only Studio against a mock provider: the
list with each status, the switch, the gallery and its search, the
grouped dropdown, the form with Advanced open, the model list with the
older-models fold and hover card, dark and light themes for the gallery.

## Not checked

- No real provider keys were used, so no new connection type has made a
live request.
- No cross-platform staging run.
- Desktop builds were not run.



## Screenshot

An empty Connections page (left: main, right: this PR): the provider
gallery replaces the form that opened by itself, with the new connection
types listed.

![Before and after: Connections page provider
gallery](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/17753/pr17753_q-0547a381b5fb.png)

---------

Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Nov 14, 2026
… of racing the drainer (#17782)

## Problem


`studio/backend/tests/test_orchestrator_switch_waits.py::test_worker_crash_mid_frame_cannot_block_the_shutdown_deadline`
failed three times today on PRs that do not touch the orchestrator
(#17645, #17743 and #17776), all with the same signature:

```
tests/test_orchestrator_switch_waits.py:385: assert runner.exitcode == 0
E   AssertionError: assert 1 == 0
  File ".../test_orchestrator_switch_waits.py", line 366, in crash_after_drain
    assert proc.exitcode == 1
```

The worker in that test does `replies.put(<1 MiB frame>)` and then
`assert replies._reader.poll(30)` on its own end of the reply pipe
before crashing. But the code under test, `_shutdown_subprocess` ->
`_drain_unread_replies`, starts a drainer thread that reads that same
pipe. When the drainer gets the whole frame first, the worker's poll
finds nothing and waits its full 30 s, while the parent's
`proc.join(30)` expires first and sees `exitcode is None`.
`test_forced_shutdown_does_not_read_an_interrupted_queue_frame` polls
the same pipe from the parent and has the same race.

The orchestrator is fine. The tests depended on thread scheduling.

## Fix

A helper, `_write_partial_frame`, writes a length header claiming the
whole 1 MiB frame plus the first 32 KiB of it straight to the pipe, then
the worker crashes (or sleeps, for the interrupted-writer test). This is
less than one pipe buffer, so the write never blocks. Any reader is left
inside a partial frame every time, which is the state both tests mean to
set up. The interrupted-writer test now waits on a `wrote` event instead
of polling the shared pipe. On Windows, where `PipeConnection` has no
raw write, the helper falls back to the old `put`.

## Tests

- Reproduced the CI failure on main by adding `time.sleep(1)` in the
worker before its poll: `assert 1 == 0`, the same error as CI. With the
same delays added around the new partial write, both tests still pass.
- `test_orchestrator_switch_waits.py`: 14 passed, three times under `-n
8`.
- Both tests ran 30 times on 10 concurrent loops, base and head. Both
passed every time locally, so the flake is not reproducible here without
the forced delay above.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 18, 2026
…marizing (unslothai#18211)

Fixes unslothai#18189

## What changes for users

A connection (Settings > Connections > edit) gains **When the chat is
full**, next to "Auto-compact after":

- **Summarize older turns** (default, unchanged): the summary call added
in unslothai#17743.
- **Drop oldest turns**: no summary call. Once the chat passes the
trigger, just enough of the oldest whole turns leave the prompt on each
message to fit. This is exactly what cloud chats did before unslothai#17743: the
dropped turns go to the thread's archive and are recalled inline, and
`search_conversation` finds them.
- **Reset to latest turn**: no summary call. Once the chat passes the
trigger, everything before the latest turn leaves the prompt at once and
stays out for the following turns, the checkpoint policy local models
use. The prompt prefix stays stable between resets, so provider prompt
caching keeps working; older turns come back through
`search_conversation` and inline recall.

The thread shows "Context compacted" instead of "Earlier messages
summarized" for both drop modes.

| | Summarize older turns | Drop oldest turns | Reset to latest turn |
|---|---|---|---|
| Extra model call | yes, once per compaction | no | no |
| What stays in the prompt | summary + recent turns | as many recent
turns as fit | the latest turn (plus pinned instructions) |
| Compact chat / `/compact` | summarizes now | not applied (the chat
only drops turns once it is full) | starts a checkpoint, kept with
auto-compact off |
| Provider refuses a prompt as too long | summarize and resend once |
evict below the refused size and resend once | evict below the refused
size and resend once |

With either drop mode, a summary saved for the thread before the switch
is not replayed; the turns it covered are evicted like any others. The
transcript is kept on disk in every mode, as before.

Anthropic and OpenAI models that compact on the provider's side keep
doing so; the option only applies where Unsloth compacts the chat
itself. A deployment that advertises native compaction but refuses it
falls back exactly as on main (a summary).

## How

- `compaction_mode` (`"summary"` | `"rolling"` | `"checkpoint"`, null =
summary) on the connection: new nullable `llm_providers.compaction_mode`
column (added by the existing schema migration), `ProviderCreate` /
`ProviderUpdate` / `ProviderResponse`, create/update/restore in
`routes/providers.py`. The values match the existing `context_policy`
names.
- `compaction_mode` request field (`[x-unsloth]`) on
`ChatCompletionRequest`. The chat adapter sends it from the connection
for the two drop modes; the default sends nothing, so requests from
other clients are unchanged.
- `routes/inference.py`: a `"rolling"` request calls
`_fit_external_context` with `can_reset=False` and
`replays_manual=False`, the exact arguments the cloud path used before
unslothai#17743. A `"checkpoint"` request takes the evicting fit the managed
engines use (`can_reset` / `replays_manual`), so archive, recall and
`/compact` epochs behave as they do locally. An overflow refit tries
half of the refused prompt, loosens in eighths, then a bound one token
under the refused prompt, each on its own copy of the transcript, until
the fit drops turns and fits; the reply cap stays clamped to the window.
With auto-compaction off, only a `"checkpoint"` `/compact` epoch is
applied.
- Frontend: `compactionMode` on the connection config, synced from the
backend, saved by the dialog (editing back to the default clears it to
null).

## Testing

- **Drop oldest turns matches the pre-unslothai#17743 cloud fit byte for byte.**
The same five chats went through the old tree (`8fc3ae284`, the parent
of unslothai#17743's merge) and through this branch with `compaction_mode:
"rolling"`, using the same proxy harness: three plain long chats (12, 16
and 30 turns at different triggers) and two archive-enabled chats with
tools off and on. The provider received identical messages in all five,
with the same dropped, archived and recalled counts. With an archive,
`"checkpoint"` sent 2 messages where the old fit and `"rolling"` sent 6.
- `studio/backend/tests/test_cloud_evict_compaction.py` (31 tests): no
summary call, whole-turn eviction, saved summary not replayed, archive +
recall, `/compact` epochs and their replay with auto-compaction off,
overflow refusals, connection storage, and two new ones: rolling keeps
more turns than checkpoint on the same chat (both recall), and rolling
never starts a checkpoint on `/compact`. Both new tests fail when
`"rolling"` is routed like `"checkpoint"`.
- Overflow retries (both drop modes): keep the reply cap the window
allows, evict every older turn when the latest turn is larger than half
the refused prompt, drop an older exchange inside one tool turn, handle
a latest turn that dominates the refused prompt, and keep a whole
attachment when dropping turns is enough. A thread switched from Reset
to latest turn to Drop oldest turns no longer replays its old
checkpoint, and Reset to latest turn resets under a rolling process
default. Each of these tests fails on the commit before its fix.
- Backend compaction, provider, external-provider, archive, recall,
attachment and overflow suites: 516 passed, 42 skipped.
- Frontend: `node scripts/typecheck.mjs --tests` clean; full `npm test`
16652 passed, 1 skipped, 0 failed.

## Follow-up fixes

- With auto-compact off, the chat now still sends the drop mode, so a
`/compact` checkpoint stays in force on later turns (before, the next
turn forwarded the whole chat).
- An overflow refusal now evicts to half of the prompt that was refused,
not half of the unfitted transcript, and the tool loop keeps that bound
on later passes (before, the retry could be as large as the refused
prompt and fail again).
- Compact chat with tools off starts a checkpoint, decided by the
model's tool support as on managed engines; overflow refits use the same
gate.
- A replayed boundary with `context_overflow: "error"` no longer turns
threshold eviction back on.


## Connection form, base vs this PR

![Connection form before and after: the "When the chat is full" field
and its three
options](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/18211/pr18211_before_after-b8e1d780b422.png)

The same saved OpenRouter connection on the merge base and on this
branch, edited in Settings > Connections. The base form has no
compaction field; this branch shows "When the chat is full" with
Summarize older turns (default), Drop oldest turns and Reset to latest
turn.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants