Repository navigation
Studio: stop compaction spending the room the compacted turn needs - #9442
Conversation
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 85e69ff8a7
ℹ️ 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".
| target = prompt_budget(context_length, max_tokens) | ||
| room = max(0, target - int(prompt_tokens or 0)) | ||
| if reply_returns: | ||
| room = min(room, int(target * _RETRIEVAL_BUDGET_SHARE)) |
There was a problem hiding this comment.
Split the remaining retrieval room
When the current prompt already exceeds half of the prompt target, this cap does not reserve anything for the returning reply because room is already smaller than target * 0.5. For example, with a 3,000-token context, a 2,250-token target, and a 1,800-token prompt, the helper still admits a 450-token retrieval; a following 750-token tool-calling reply then brings the protected exchange to n_ctx exactly, so the next tool-loop preflight cannot evict enough and llama-server refuses it. Base the split on the remaining shared room rather than half of the total target.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The cap does not bind in that example, so it describes main's behavior rather than a change here. With ctx 3000 and prompt 1800, target - prompt_tokens is 450 and target * 0.5 is 1125, so min returns 450, which is exactly what max(0, prompt_budget(...) - _spent) returned before this PR. The cap only binds while prompt_tokens < target / 2. Swept over 8 context lengths, 8 max_tokens values and 21 fill levels in both modes, _retrieval_budget never returns more than the old expression, so every retrieval path here is the same or smaller than main.
Basing the split on the remaining room would not establish the invariant either. Requiring prompt_tokens + retrieval + max_reply <= target in that example gives 2250 - 1800 - 750 = -300, so no positive retrieval is safe under that reading. That is because prompt_budget is defined as context_length - reserved_reply, so a prompt at target plus a full-length reply reaches n_ctx by construction, on main as well.
The residual case, a protected exchange with no evictable history left, is the remaining limitation the description already names: with dropped_total == 0 there is nothing to evict and no shortened prompt to serve. Halving the remainder would not fix it and would cut recall hardest on the conversations that need it, which the small-window matrix measured as not regressing at the current share.
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Confirmed this hits fit_rolling_context in studio/backend/core/inference/context_window.py, where an eviction that fits the physical window is still discarded in favour of the oversized original, and the frontend now keys the notice off dropped turns rather than fits. Will get this reviewed. |
A rescued fit reports `fits: false` while having evicted turns and been sent, so every consumer that read `fits: false` as "nothing was shortened, the request failed" now needs `dropped_messages` to tell the two apart. Five places still read the old meaning. `_fit_with_instruction_pins` refits without the user's standing instructions on any non-fitting result. Its docstring calls that "one extra fit, only on a path that was already failing" -- no longer true of a rescue, which is servable. At ctx 1000 the pinned attempt now lands at 920 tokens with the instruction, and the retry throws it away for 460 tokens without it. Gate the retry on a refusal that dropped nothing. `shouldAutoContinue` refuses to resume any `fits: false` turn. A rescue is the turn most likely to stop on `length`, since missing the reply reserve is what defines it, and the fitter can evict further to make room for the replayed partial. The genuinely irreducible case is already caught by the partialTokens check on its own merits. `compactionBoundary` falls back to `dropped_messages` when no boundary was recorded, which a rescue deliberately never records. That count is a per-refit SUM: a three-refit tool turn reports 16, and `showsNotice` treats it as a high-water mark, so every later real compaction in the thread goes silent. Confine the fallback to a fit that succeeded, which is the only shape the legacy records it exists for have. The rescue itself had no floor on reply room, so a prompt of `n_ctx - 1` was served: history evicted AND a one-token answer stopped on `length`, strictly worse than the refusal it replaced, which kept the turns and named the one that was too big. Require a sixteenth of the window, capped by the reserve the fit asked for. Measured over a 1.27M-case sweep against main this keeps 7,992 of the rescues and drops only the degenerate tail; every case the PR description cites still rescues. And `safetensors_agentic` sizes the same `search_conversation` against the same window "as the GGUF loop does", by its own comment, but kept the uncapped expression. Having no rolling fit to recover makes the shared reply room more important there, not less. Moved the policy next to `prompt_budget`, which is in `context_window` for exactly this reason, and called it from both.
danielhanchen
left a comment
There was a problem hiding this comment.
Thank you for the PR! The goal of this PR is to stop Studio hard-failing a request whose compacted prompt would have fitted the model's physical context window, and to stop a tool-loop retrieval spending the room the following reply needs. As a summary, it adds a third outcome to fit_rolling_context -- a "rescued" fit that reports fits: false because it missed the reply reserve, but has evicted turns and is what actually gets sent -- and updates the archive, boundary-recording and frontend-notice paths to cope with it.
The core change is right, and the bug is real. I reproduced the before/after directly: with a 500-token window main returns the original 1,350-token prompt and llama-server rejects it, while this branch returns the rescued 450-token prompt. The >= on initial_tokens and strict < on current_tokens are both correct against llama-server's per-slot task.n_tokens >= n_ctx_slot.
I ran a 1,270,080-case differential sweep of fit_rolling_context against origin/main (context lengths 0..131072 x max_tokens including None/0/huge x six conversation shapes x sticky/reserve/pin variations), asserting that every fit main accepted is byte-identical here, that a rescue only ever fires where main sent something the window could not hold, and that the prompt sent is never larger than main's. All held, on Python 3.10 through 3.13. Version skew is clean too: old persisted contextTruncation records read identically, and an old frontend against this backend degrades quietly rather than crashing, since nothing was removed or retyped.
What I did find is that the fits: false split is only half done. Five consumers still read fits: false as "nothing was shortened", and dropped_messages is what now tells the two apart. I have pushed a commit with the fixes and regression tests; details below, and each one fails without its fix.
| Reviewers | Severity | Finding |
|---|---|---|
| 12/12 | Medium | safetensors_agentic.py sizes the same search_conversation against the same window "as the GGUF loop does", but kept the uncapped expression |
| 5/8 | Medium | _fit_with_instruction_pins treats a rescue as a refusal and refits without the user's standing instructions, discarding a servable prompt that had them |
| 4/8 | Medium | compactionBoundary reads a rescue's summed dropped_messages as a boundary, silencing every later real compaction notice in the thread |
| 3/8 | Medium | The rescue has no floor on reply room, so a prompt of n_ctx - 1 is served: history evicted and a one-token answer stopped on length |
| 2/8 | Low-Med | shouldAutoContinue refuses to resume any fits: false turn, including the rescued turn that is most likely to stop on length |
| 1/8 | Low | routes/inference.py multi-choice tiebreak keys on dropped_messages alone, so a rescued and a cleanly-fitting choice tie and generation order decides the verdict |
Not changed, for the record: the retrieval half-share cap is sound (min(max(0, target - spent), target/2) <= max(0, target - spent) everywhere, verified over 1,080 cells; it binds iff prompt < target/2 and never silences retrieval at any usable window). studio_tool_loop.py deliberately uses a fixed page cap because an external provider's window is unmeasurable, which is a different design, not the same omission. The multi-choice tiebreak above I have left alone as a one-line ordering nit outside this PR's core.
Also verified safe and worth stating, since they were the things most likely to bite: the archived set is disjoint from the sent set at all five relaxed call sites; no prefix is archived twice across tool-loop iterations, and archive_turns is idempotent by content hash, so a chat permanently in the rescued regime writes zero duplicate rows and re-embeds nothing; a rescue can never inject a recall block, both via recall_done = not fits and independently because its budget is 0; and _thread_has_checkpoint flipping on a rolling turn is pre-existing, not something this PR changes.
CI on 6b97fcdd9c showed four red checks, but their logs had already expired (HTTP 410, empty steps array) so they could not be attributed. Locally, after installing the sqlite-vec extension that test_conversation_recall_injection.py needs, the Studio backend suites are green on both sides: 364 passed on origin/main, 373 on your head, and 441 with the fixes above. Frontend rolling-context-window 20/20 and chat-continuation 40/40, tsc --noEmit clean, ruff clean.
Detail
1. _fit_with_instruction_pins (studio/backend/core/inference/llama_cpp.py:303)
The retry exists so that pinning cannot turn a servable request into a refusal -- "one extra fit, only on a path that was already failing", per its own docstring. A rescue is not such a path. At context_length=1000, a chat with a pinned standing instruction:
pinned attempt : fits=False dropped=2 prompt_tokens_after=920 servable=True instruction kept=True
retry (no pins): fits=True dropped=4 prompt_tokens_after=460 servable=True instruction kept=False
The branch now builds a servable prompt that keeps the instruction, then discards it. Gated on not int(truncation.get("dropped_messages") or 0) so only a refusal that returned the originals retries.
2. shouldAutoContinue (studio/frontend/src/features/chat/utils/continuation.ts:346)
Refusing every fits: false turn now refuses the rescued one, which is precisely the turn that runs out of reply room and stops on length. Added a promptWasShortened option, passed from thread.tsx. The genuinely irreducible case still returns false via the existing partialTokens >= promptTarget check, which is tested.
3. compactionBoundary (studio/frontend/src/features/chat/utils/context-truncation.ts:42)
dropped_messages accumulates per refit -- which is the exact reason boundary_messages was introduced, per the function's own comment. A rescue records no boundary, so the fallback fires and a three-refit tool turn reports 16. showsNotice only announces a boundary that rose, so that turn becomes a high-water mark:
notices shown, before: [m1, m2] <- m3/m4/m5 silent forever
notices shown, after: [m1, m3, m4, m5]
The fallback is now confined to fits: true, which is the only shape the legacy records it was written for actually have.
4. Reply-room floor (studio/backend/core/inference/context_window.py:322)
current_tokens < context_length admits a prompt of n_ctx - 1. At context_length=200, max_tokens=128 that evicts eight messages and leaves one token to answer in, so the user loses the history and gets a stub. The refusal it replaced kept the turns and named the one that was too big, which is the more useful outcome down there. Now requires context_length // 16, capped by the reserve the fit asked for, so a caller that asked for 16 tokens is not held to more. Across the sweep this keeps 7,992 of 15,024 rescues and drops only that degenerate tail; every case in the PR description still rescues, and all four of your new tests pass unchanged.
5. safetensors_agentic.py:1329
Moved retrieval_budget next to prompt_budget in context_window.py, which is where that module's docstring says shared sizing formulas belong, and called it from both loops. llama_cpp._retrieval_budget is now an alias, so your existing tests are untouched. Added a test asserting the two cannot drift apart again.
6. Multi-choice tiebreak -- not changed, studio/backend/routes/inference.py:16684
Each choice runs its own preflight, so with n > 1 a rescued choice (dropped 12, fits false) and a cleanly-fitting one (dropped 12, fits true) tie on the key, and >= hands it to whichever generated later. Newly reachable because of this PR, but low impact and outside its core, so I left it. If you want it:
if _choice_context_truncation is not None and (
_context_truncation is None
or (
int(_choice_context_truncation.get("dropped_messages") or 0),
not _choice_context_truncation.get("fits"),
)
> (
int(_context_truncation.get("dropped_messages") or 0),
not _context_truncation.get("fits"),
)
):Two consequences of the fits:false split that I got wrong in the previous commit, both caught in review. A turn refits once per tool iteration, and `mergeContextTruncation` sums `dropped_messages` while taking `fits` from the last event. Deriving "was the prompt we sent shortened?" from that pair reads an early rescue followed by a final refusal -- originals sent, nothing dropped -- as a rescue, and re-opens the three auto-continue rounds the guard exists to stop. The merge now carries the last fit's own count beside the running total, and `lastFitShortened` asks that. `promptWasShortened` keeps the accumulated meaning, which is the right one for the notice: the turn did compact. And confining `compactionBoundary`'s fallback to a fit that succeeded left the rescue with no depth at all, since the backend gated every boundary write on `fits`. The transient toast fired and nothing survived a reload, so a turn compacted solely by the rescue path was never disclosed. A rescue evicts for real, so it now records its boundary like any other compaction. That does not make it replayable: `_sticky_compaction_boundary` declines any record whose `fits` is false before it reads the depth, which is where the distinction belongs, because replaying is what a missed reserve makes unsafe and being honest about what was dropped is not.
Comment-only. Same intent, fewer lines.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
I had this backwards. A rescue was let through on the grounds that the fitter could evict further to make room for the replayed partial. It cannot: the rescue branch is only reached once the eviction loop has run out of eligible turns, so the rescued prompt is ALREADY the floor -- system, pins and the latest turn. A continuation then replays the partial as the final assistant turn, which the fit protects, so each round asks for strictly more protected prompt against the same window. Measured on the 460-of-500-token rescue this branch added: the prompt leaves 40 tokens, a 10-character partial already refuses, and an 80-character one overflows the window outright. Auto-continue would spend three rounds failing where the Continue bar belongs. So the original guard was right, for a better reason than its comment gave, and it says so now. With it restored nothing consumes the per-last-fit signal from the previous commit, so `lastFitShortened` and the `last_fit_dropped_messages` key go too -- which settles the aggregate misclassification they were added for more thoroughly than tracking it did. `promptWasShortened` keeps the accumulated meaning it has always had, for the compaction notice and the toast.
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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-only. The boundary note still said a shortened refusal records none, which stopped being true once rescues started recording theirs.
`tsc -p tsconfig.test.json` infers a narrow literal for a `let` seeded with an object, so reassigning it from mergeContextTruncation -- whose boundary_messages is optional -- failed to typecheck. Only the app project was covered locally; the test project is the second half of `npm run typecheck", which is what CI runs.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Before/after evidence for the rescued fit, from two isolated installs: merge base Setup: Left, before the PR: the eviction is discarded, the original 1071-token prompt goes to llama-server, and the turn is refused with "Message too long: 1062 tokens exceeds the 1024-token context window". No answer. The composer counter still reads 122/1.0k because the turn never entered the context. Right, with the PR: the shortened prompt is sent, the turn is answered, and the reply carries the compaction notice, "2 messages dropped here." Numbers from the same servers, not read off the picture:
One caveat on the right-hand column, since it would otherwise be easy to over-read: the non-streaming API call accepts the prompt but comes back with empty content, because 947 of 1024 tokens leaves about 77 to answer in. The visible reply is from the streaming UI. The accept/refuse signal is the 400, not the reply length. |
Resolves the chat-adapter.ts import conflict: main added createImageGateRunOwner (unslothai#9425) while this branch added promptWasShortened. Both are used, so the resolution keeps both imports.

What went wrong
Studio compacts long conversations by removing older turns from the model request while keeping them saved and searchable. In one internal test with a 1,536-token context window, compaction reduced a 10,583-token conversation to 1,265 tokens. The reduced prompt fit the model, but Studio discarded it because it did not leave enough room for the preferred reply size. Studio then sent the original 10,583-token conversation, which the model rejected as too large.
Tool-loop retrieval could cause a similar failure. Recalled history was allowed to use nearly all available prompt space. After the model's reply was added for the next tool iteration, the request could exceed the context window with nothing eligible for further removal.
What changed
Before and after
Across the internal small-window matrix, hard errors fell from 5 to 2. All three errors where the compacted prompt fit the physical window were removed, and retrieval quality did not regress.
Remaining limitation
Compaction still cannot help when the system prompt, current user turn, or current tool exchange alone exceeds the context window. The two remaining 1,536-token failures have minimum prompt sizes of 2,295 and 1,598 tokens, so neither can fit that window.
Verification