Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop compaction spending the room the compacted turn needs (#9442)
oobabooga87a0d756013d
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.pyindex a3443757a4c..9613f915bff 100644--- a/studio/backend/core/inference/checkpoint.py+++ b/studio/backend/core/inference/checkpoint.py@@ -637,9 +637,8 @@ def fit_checkpoint_context(block = ""current_tokens = count_tokens(projected)if current_tokens > prompt_target:- # Refused, returning the ORIGINAL messages as the rolling fit does: the request- # fails either way, so dropping turns off a doomed request loses them for nothing.- # Same keys, because every consumer gates on `fits`.+ # Let the rolling fit retry from the originals; any projection made here would+ # be discarded by `_fit_context`.from core.inference.context_window import _latest_turn_tokens # noqa: PLC0415return messages, {"fits": False,diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex 8e3b2266874..ea7fe1d8805 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -215,6 +215,35 @@ def prompt_budget(context_length: int, max_tokens: Optional[int]) -> int:return context_length - min(requested, max(1, context_length // 4))+# Cap a tool-loop retrieval without reducing the allowance of smaller results.+_RETRIEVAL_BUDGET_SHARE = 0.5++# The least reply room a rescued prompt must leave, as a fraction of the window. Small on+# purpose: missing the reserve is survivable, so this only rules out the stub-answer end.+_RESCUE_REPLY_FLOOR_DIVISOR = 16+++def retrieval_budget(+ context_length: int,+ max_tokens: Optional[int],+ prompt_tokens: int,+ *,+ reply_returns: bool = False,+) -> int:+ """Return the prompt room available to one retrieval.++ In a tool loop the retrieved exchange and the reply are protected on the next fit, so+ one retrieval may use at most half the prompt budget; single-shot uses the remainder.+ Kept beside ``prompt_budget`` so every backend sizing ``search_conversation`` shares+ one policy rather than quietly disagreeing.+ """+ 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))+ return room++def _latest_turn_tokens(messages: list[dict], count_tokens: Callable[[list[dict]], int]) -> int:"""Tokens in the newest message, estimated if the template refuses to render it.@@ -315,17 +344,25 @@ def fit_rolling_context(current_tokens = count_tokens(fitted)if current_tokens > prompt_target:- # Evicted everything evictable and it still does not fit. Return the ORIGINAL- # messages, not the partial eviction: the request is refused either way, so- # dropping turns off a doomed request loses them for nothing. The diagnosis is- # still worth returning; llama-server's own error reports the size of the WHOLE- # conversation and advises shortening it, which cannot work when what is left is- # the system prompt plus the latest turn. Consumers all gate on `fits`.- return messages, {+ # Missing the prompt target only loses reserved reply room, so keep the original+ # if it fits the physical window, else an eviction that does. Strictly under on+ # both sides: llama-server refuses at `n_ctx` exactly. But not under by one token,+ # which would lose the history AND answer in one token, worse than the refusal it+ # replaces. Capped by the reserve, so the floor demands no room the target did not.+ reply_floor = min(+ max(1, context_length // _RESCUE_REPLY_FLOOR_DIVISOR),+ context_length - prompt_target,+ )+ rescued = (+ dropped_total > 0+ and initial_tokens >= context_length+ and current_tokens + reply_floor <= context_length+ )+ return (fitted if rescued else messages), {"fits": False,- "dropped_messages": 0,+ "dropped_messages": dropped_total if rescued else 0,"prompt_tokens_before": initial_tokens,- "prompt_tokens_after": initial_tokens,+ "prompt_tokens_after": current_tokens if rescued else initial_tokens,# Floor for the conversation, and how much of it is the message just sent:# together they say whether the chat or the single message is the problem."irreducible_tokens": current_tokens,diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex a83fcbc3218..56dbf83d765 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -56,6 +56,7 @@ from core.inference.context_window import (evicted_messages,fit_rolling_context,messages_have_media,+ retrieval_budget,)from core.inference.stream_errors import stream_error_from_chunkfrom core.inference.llama_server_args import (@@ -300,7 +301,16 @@ def _fit_with_instruction_pins(fitted, truncation = _fit_context(messages, protected_message_ids = (anchors | pins) or None, **kwargs)- if pins and truncation and not truncation.get("fits"):+ # Only a refusal that returned the ORIGINAL messages was "already failing". A rescue+ # reports `fits` false too but is servable, and dropping its pins would trade a working+ # prompt WITH the standing instruction for one without, the very thing this seam+ # prevents. `dropped_messages` separates them.+ if (+ pins+ and truncation+ and not truncation.get("fits")+ and not int(truncation.get("dropped_messages") or 0)+ ):return _fit_context(messages, protected_message_ids = anchors or None, **kwargs)return fitted, truncation@@ -798,6 +808,17 @@ def _branch_boundary(conversation: list[dict], branch: Optional[list[dict]]) ->return count+def _records_boundary(truncation: dict) -> bool:+ """Whether a fit removed turns from the prompt it sent, so its depth is worth saving.++ Not ``fits``: a rescue reports false yet really did evict, and the client reads this+ depth to place the compaction notice, so recording nothing compacts silently. Saving+ is not replaying -- `_sticky_compaction_boundary` still declines any `fits` false+ record, which is where a missed reserve belongs.+ """+ return bool(truncation.get("fits")) or bool(truncation.get("dropped_messages"))++def _branch_non_system(branch: Optional[list[dict]]) -> list[dict]:"""The branch as ``_branch_boundary`` counts it: system and developer turns removed."""return [@@ -1013,6 +1034,10 @@ def _prefix_user_text(message: dict, prefix: str) -> dict:return message+# A readable local name for the shared `context_window` policy, not a second implementation.+_retrieval_budget = retrieval_budget++def _recall_top_k(budget_tokens: int) -> int:"""How many archived chunks actually fit in the room a fit obtained.@@ -23273,7 +23298,7 @@ class LlamaCppBackend:tools_withheld = tools_withheld,),)- if truncation and truncation["fits"]:+ if truncation:# Inline, not a forged tool exchange: this path sends no tools array,# and strict templates reject a tool role with no catalogue._recalled = _archive_and_recall(@@ -23285,11 +23310,13 @@ class LlamaCppBackend:# Checkpoint mode recalls once, on the turn that reset; rolling has no# such key and keeps recalling on every turn that evicted anything.force_recall = bool(truncation.get("checkpoint_started", True)),- recall_done = False,- recall_budget_tokens = max(- 0,- prompt_budget(self._effective_context_length, payload["max_tokens"])- - int(truncation.get("prompt_tokens_after") or 0),+ # A rescued refusal may evict messages; archive them without recall.+ recall_done = not truncation["fits"],+ # This single-shot answer never returns to the prompt.+ recall_budget_tokens = _retrieval_budget(+ self._effective_context_length,+ payload["max_tokens"],+ truncation.get("prompt_tokens_after") or 0,),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(@@ -23304,7 +23331,7 @@ class LlamaCppBackend:)openai_messages = _recalled["conversation"]truncation = {**truncation, **_recalled["counts"]}- if truncation and truncation.get("fits"):+ if truncation and _records_boundary(truncation):truncation = {**truncation,"boundary_messages": _branch_boundary(openai_messages, _before_fit),@@ -23953,7 +23980,7 @@ class LlamaCppBackend:_prompt_token_offset = int(truncation.get("prompt_tokens_after") or 0) - estimate_messages_tokens(conversation)- if truncation and truncation["fits"]:+ if truncation:_recalled = _archive_and_recall(conversation,_before_fit,@@ -23970,11 +23997,14 @@ class LlamaCppBackend:# Checkpoint mode recalls once, on the turn that reset; rolling has# no such key and recalls on every turn that evicted anything.force_recall = bool(truncation.get("checkpoint_started", True)),- recall_done = _conversation_recall_done,- recall_budget_tokens = max(- 0,- prompt_budget(self._effective_context_length, max_tokens)- - int(truncation.get("prompt_tokens_after") or 0),+ # A rescued refusal may evict messages; archive them without recall.+ recall_done = _conversation_recall_done or not truncation["fits"],+ # Leave room for the answer appended on the next iteration.+ recall_budget_tokens = _retrieval_budget(+ self._effective_context_length,+ max_tokens,+ truncation.get("prompt_tokens_after") or 0,+ reply_returns = True,),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(@@ -23999,7 +24029,7 @@ class LlamaCppBackend:_rolling_anchor_ids.add(id(_message))for _ev in _recalled["events"]:yield _ev- if truncation and truncation.get("fits"):+ if truncation and _records_boundary(truncation):truncation = {**truncation,"boundary_messages": _branch_boundary(conversation, _request_branch),@@ -24097,11 +24127,9 @@ class LlamaCppBackend:tools_withheld = _memory_tool_withheld(thread_id, tools),),)- if truncation and truncation["fits"]:- # Archive only: this refit runs against a smaller replacement- # window with no reserve held back, so injecting a recall is- # exactly what would push the retry over. The next request can- # still recall these turns.+ if truncation:+ # Archive only. The replacement fit reserves no recall room, and a+ # rescued refusal may still have evicted messages.truncation.update(_archive_and_recall(conversation,@@ -24115,13 +24143,15 @@ class LlamaCppBackend:payload["messages"] = neutralize_control_markup_in_messages(conversation, _markup_cache, self.markup_profile)- if truncation and truncation["fits"]:- truncation["boundary_messages"] = _branch_boundary(- conversation, _request_branch- )- truncation["boundary_anchor"] = _branch_boundary_anchor(- conversation, _request_branch- )+ if truncation:+ if _records_boundary(truncation):+ truncation["boundary_messages"] = _branch_boundary(+ conversation, _request_branch+ )+ truncation["boundary_anchor"] = _branch_boundary_anchor(+ conversation, _request_branch+ )+ # Report every shortened retry, including a rescued refusal._respawn_truncations.append(truncation)except Exception as exc:logger.warning("Could not refit rolling context after respawn: %s", exc)@@ -25287,10 +25317,13 @@ class LlamaCppBackend:strict = False,))- kwargs["conversation_budget_tokens"] = max(- 0,- prompt_budget(self._effective_context_length, max_tokens)- - _spent,+ # The result and reply are protected on the next fit, so+ # the result cannot spend their entire shared budget.+ kwargs["conversation_budget_tokens"] = _retrieval_budget(+ self._effective_context_length,+ max_tokens,+ _spent,+ reply_returns = True,)if accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callback@@ -25493,7 +25526,7 @@ class LlamaCppBackend:),)_sticky_boundary_applied = True- if truncation and truncation["fits"]:+ if truncation:_recalled = _archive_and_recall(conversation,_before_final_fit,@@ -25506,11 +25539,13 @@ class LlamaCppBackend:# Checkpoint mode recalls once, on the turn that reset; rolling has no# such key and keeps recalling on every turn that evicted anything.force_recall = bool(truncation.get("checkpoint_started", True)),- recall_done = _conversation_recall_done,- recall_budget_tokens = max(- 0,- prompt_budget(self._effective_context_length, max_tokens)- - int(truncation.get("prompt_tokens_after") or 0),+ # A rescued refusal may evict messages; archive them without recall.+ recall_done = _conversation_recall_done or not truncation["fits"],+ # The synthesized final answer never returns to the prompt.+ recall_budget_tokens = _retrieval_budget(+ self._effective_context_length,+ max_tokens,+ truncation.get("prompt_tokens_after") or 0,),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(@@ -25530,7 +25565,7 @@ class LlamaCppBackend:_rolling_anchor_ids.add(id(_message))for _ev in _recalled["events"]:yield _ev- if truncation and truncation.get("fits"):+ if truncation and _records_boundary(truncation):truncation = {**truncation,"boundary_messages": _branch_boundary(conversation, _request_branch),@@ -25609,8 +25644,8 @@ class LlamaCppBackend:tools_withheld = True,),)- if truncation and truncation["fits"]:- # Archive only, for the same reason as the iteration refit above.+ if truncation:+ # Archive only; see the iteration respawn refit above.truncation.update(_archive_and_recall(conversation,@@ -25624,13 +25659,14 @@ class LlamaCppBackend:stream_payload["messages"] = neutralize_control_markup_in_messages(conversation, None, self.markup_profile)- if truncation and truncation["fits"]:- truncation["boundary_messages"] = _branch_boundary(- conversation, _request_branch- )- truncation["boundary_anchor"] = _branch_boundary_anchor(- conversation, _request_branch- )+ if truncation:+ if _records_boundary(truncation):+ truncation["boundary_messages"] = _branch_boundary(+ conversation, _request_branch+ )+ truncation["boundary_anchor"] = _branch_boundary_anchor(+ conversation, _request_branch+ )_final_respawn_truncations.append(truncation)except Exception as exc:logger.warning("Could not refit rolling context after respawn: %s", exc)diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex f5fd0b1c6e2..4a933c9e244 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -1317,7 +1317,7 @@ def run_safetensors_tool_loop():from core.inference.context_window import (estimate_messages_tokens_dense,- prompt_budget,+ retrieval_budget,)# Dense, unlike the eviction estimator: four characters per token@@ -1326,11 +1326,16 @@ def run_safetensors_tool_loop(# the next prompt over the window. Measured on an 81-message CJK# chat: 1295 estimated against 2737 real, reporting 1777 tokens of# room where 335 remained.- kwargs["conversation_budget_tokens"] = max(- 0,- prompt_budget(int(context_length), max_tokens)- - estimate_messages_tokens_dense(conversation)- - estimate_messages_tokens_dense(tools or []),+ #+ # `reply_returns`, as the GGUF loop does: result and reply are+ # both protected on the next fit, so one retrieval cannot spend+ # the budget they share.+ kwargs["conversation_budget_tokens"] = retrieval_budget(+ int(context_length),+ max_tokens,+ estimate_messages_tokens_dense(conversation)+ + estimate_messages_tokens_dense(tools or []),+ reply_returns = True,)if _accepts_output_callback(execute_tool):kwargs["output_callback"] = _output_callbackdiff --git a/studio/backend/tests/test_checkpoint_compaction.py b/studio/backend/tests/test_checkpoint_compaction.pyindex e04aa98c6b1..c19ecc9a5ad 100644--- a/studio/backend/tests/test_checkpoint_compaction.py+++ b/studio/backend/tests/test_checkpoint_compaction.py@@ -1289,6 +1289,38 @@ def test_a_checkpoint_boundary_is_not_replayed_once_the_policy_is_rolling(monkeyassert llama_cpp._sticky_compaction_boundary("t1") == 6+def test_a_rescued_boundary_is_recorded_but_never_replayed(monkeypatch):+ """Recording a rescue's depth must not make it sticky.++ Two different questions. "What did this fit evict?" places the compaction notice, and+ a rescue has a real answer worth persisting. "Which boundary should the next request+ re-apply?" is the one a missed reply reserve makes unsafe, and it is decided here, on+ `fits` alone -- so the depth can be honest without the replay becoming wrong.+ """+ from core.inference import checkpoint, llama_cpp++ stored = [+ {"role": "user", "content": "q"},+ {+ "role": "assistant",+ "content": "a",+ "metadata": {"custom": {"contextTruncation": {"fits": True, "boundary_messages": 6}}},+ },+ ]+ _stub_studio_db(monkeypatch, stored)+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")++ assert llama_cpp._sticky_compaction_boundary("t1") == 6++ # The same depth, from a fit that missed the reply reserve: not replayed.+ stored[1]["metadata"]["custom"]["contextTruncation"] = {+ "fits": False,+ "dropped_messages": 6,+ "boundary_messages": 6,+ }+ assert llama_cpp._sticky_compaction_boundary("t1") == 0++def test_the_tool_loop_reopens_only_where_an_epoch_actually_happened(monkeypatch):"""An archive is not a checkpoint, and only one of them justifies the override.diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.pyindex 8356efc8adc..c2c726e00f1 100644--- a/studio/backend/tests/test_context_overflow_truncation.py+++ b/studio/backend/tests/test_context_overflow_truncation.py@@ -481,6 +481,165 @@ def test_rolling_fit_keeps_original_when_protected_messages_still_do_not_fit():assert info["prompt_tokens_after"] == info["prompt_tokens_before"]+def test_an_irreducible_fit_serves_the_eviction_when_the_original_is_past_the_window():+ """Use an eviction that fits the window when the original does not."""+ # 450 chars: past the 400-token target, inside the 500-token window.+ latest = {"role": "user", "content": "latest" * 75}+ messages = [+ {"role": "user", "content": "old" * 100},+ {"role": "assistant", "content": "answer" * 100},+ latest,+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 500,+ max_tokens = 100,+ count_tokens = counter,+ )++ assert counter(messages) > 500 >= counter(fitted)+ assert fitted == [latest]+ # Still a refusal: the diagnosis is what the client explains the short reply with.+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] == 2+ assert info["prompt_tokens_after"] == counter(fitted) < info["prompt_tokens_before"]+ assert info["irreducible_tokens"] == counter(fitted)+++def test_an_irreducible_fit_keeps_the_original_while_it_still_fits_the_window():+ """Keep full history when only the reply reserve is exhausted."""+ messages = [+ {"role": "user", "content": "old" * 10},+ {"role": "assistant", "content": "answer" * 5},+ # 480 chars on its own, so evicting the pair still misses the 450-token target.+ {"role": "user", "content": "latest" * 80},+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 600,+ max_tokens = 150,+ count_tokens = counter,+ )++ assert 450 < counter(messages) <= 600+ assert fitted is messages+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] == 0+ assert info["prompt_tokens_after"] == info["prompt_tokens_before"]+++def test_an_irreducible_fit_refuses_an_eviction_that_fills_the_window():+ """An eviction landing on `n_ctx` exactly is refused, so it is not a rescue."""+ # 500 chars in a 500-token window: serving this would drop turns and still fail.+ messages = [+ {"role": "user", "content": "o" * 300},+ {"role": "assistant", "content": "a" * 600},+ {"role": "user", "content": "x" * 500},+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 500,+ max_tokens = 100,+ count_tokens = counter,+ )++ assert fitted is messages+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] == 0+ assert info["prompt_tokens_after"] == info["prompt_tokens_before"]+ assert info["irreducible_tokens"] == 500+++def test_an_irreducible_fit_serves_the_eviction_when_the_original_fills_the_window():+ """An original of exactly `n_ctx` is refused too, so an eviction under it wins."""+ latest = {"role": "user", "content": "x" * 450}+ messages = [+ {"role": "user", "content": "o" * 20},+ {"role": "assistant", "content": "a" * 30},+ latest,+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 500,+ max_tokens = 100,+ count_tokens = counter,+ )++ assert counter(messages) == 500 > counter(fitted)+ assert fitted == [latest]+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] == 2+ assert info["prompt_tokens_after"] == 450+++def test_an_irreducible_fit_refuses_a_rescue_that_leaves_no_room_to_answer():+ """A rescue has to buy an ANSWER, not just an accepted request.++ Serving a prompt one token under the window evicts the history and comes back with a+ one-token reply stopped on `length`: the turns are gone and the user has nothing. The+ refusal it replaces at least kept them and named the turn that was too big, so below a+ floor of reply room the old behaviour wins.+ """+ latest = {"role": "user", "content": "x" * 495}+ messages = [+ {"role": "user", "content": "o" * 300},+ {"role": "assistant", "content": "a" * 300},+ latest,+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 500,+ max_tokens = 100,+ count_tokens = counter,+ )++ # The eviction it reached is under the window, so the old gate would have served it+ # with five tokens to answer in. `irreducible_tokens` is that floor.+ assert counter(messages) > 500+ assert info is not None and info["irreducible_tokens"] == 495+ # Refused instead, with the history intact.+ assert fitted is messages+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] == 0+ assert info["prompt_tokens_after"] == info["prompt_tokens_before"]++ # And one that DOES leave room is still rescued: the floor is 500 // 16 = 31.+ roomy = [+ {"role": "user", "content": "o" * 300},+ {"role": "assistant", "content": "a" * 300},+ {"role": "user", "content": "x" * 460},+ ]+ fitted_roomy, info_roomy = fit_rolling_context(+ roomy,+ context_length = 500,+ max_tokens = 100,+ count_tokens = counter,+ )+ assert fitted_roomy == roomy[-1:]+ assert info_roomy["dropped_messages"] == 2+ assert info_roomy["prompt_tokens_after"] == 460++def test_an_irreducible_fit_says_WHOSE_turn_does_not_fit():"""A tool loop refits with the tool result appended.@@ -1217,6 +1376,69 @@ def test_a_pin_is_charged_for_everything_it_holds():}+def test_a_pinned_fit_that_only_missed_the_reserve_keeps_its_pins():+ """The pinless retry fires on a REFUSAL, not on a prompt that was merely reduced.++ `_fit_with_instruction_pins` drops the pins and refits when the pinned attempt does+ not fit, since pinning turning a servable request into a refusal is worse than losing+ the instruction. A rescued fit reports `fits` false too, but it is servable and is+ what gets sent, so retrying there loses the instruction for nothing.+ """+ from core.inference import instruction_pin, llama_cpp++ instruction = _instruction("A" * 300)+ messages = [+ {"role": "system", "content": "S" * 40},+ instruction,+ # Rides along with the pin: the evictor protects by GROUP.+ {"role": "assistant", "content": "B" * 160},+ {"role": "user", "content": "C" * 280},+ {"role": "assistant", "content": "D" * 280},+ {"role": "user", "content": "L" * 420},+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )+ # ctx 1000 -> prompt_target 872, reply floor 62. Pinned floor is 40+300+160+420 =+ # 920: past the target, and 920+62 is inside the window, so a rescue. Pinless floor+ # is 40+420 = 460, which fits outright -- which is exactly why the retry is tempting+ # and exactly why it must not fire.+ assert counter(messages) == 1480++ calls = []+ # Captured before the patch, or the spy calls itself.+ original = llama_cpp._fit_context++ def _spy(msgs, **kwargs):+ calls.append(kwargs.get("protected_message_ids"))+ return original(msgs, **kwargs)++ original_pins = instruction_pin.pinned_instruction_ids+ llama_cpp._fit_context = _spy+ # Stubbed: which turns get pinned is the pin heuristic's own business and has its own+ # tests. What is under test here is what the fitter does once something IS pinned.+ instruction_pin.pinned_instruction_ids = lambda *_a, **_k: {id(instruction)}+ try:+ fitted, info = llama_cpp._fit_with_instruction_pins(+ messages,+ anchor_ids = None,+ context_length = 1000,+ max_tokens = 128,+ count_tokens = counter,+ )+ finally:+ llama_cpp._fit_context = original+ instruction_pin.pinned_instruction_ids = original_pins++ # A rescue, not a refusal: shorter than the original and inside the window.+ assert info is not None and info["fits"] is False+ assert info["dropped_messages"] > 0+ assert counter(fitted) < 1000 <= counter(messages)+ # Fitted once. No pinless retry, so the standing instruction survived.+ assert len(calls) == 1+ assert any(message is instruction for message in fitted)++def test_a_pin_charges_token_dense_text_at_its_real_rate():"""The ceiling is only a ceiling if the turn is charged what it really costs.diff --git a/studio/backend/tests/test_conversation_recall_injection.py b/studio/backend/tests/test_conversation_recall_injection.pyindex 3c52395fe81..41cd73a785c 100644--- a/studio/backend/tests/test_conversation_recall_injection.py+++ b/studio/backend/tests/test_conversation_recall_injection.py@@ -157,6 +157,46 @@ def test_archive_and_recall_skips_recall_once_already_done(archived):assert "recalled_chunks" not in result["counts"]+def test_a_refused_fit_still_archives_what_it_evicted(archived):+ """`recall_done` skips recall without skipping the archive write."""+ before = _conversation() + [{"role": "user", "content": "a turn only the fit saw"}]+ after = _conversation()++ result = llama_cpp._archive_and_recall(+ after, before, thread_id = THREAD, style = "tool", recall_done = True+ )++ assert result["counts"]["archived_messages"] >= 1+ assert result["recalled"] is False+++def test_a_shrunken_window_hands_the_respawn_refit_a_reduced_refusal():+ """A smaller window can produce a reduced prompt with `fits` false."""+ from core.inference.context_window import fit_rolling_context++ latest = {"role": "user", "content": "latest" * 133} # 798 chars+ messages = [+ {"role": "user", "content": "old" * 133},+ {"role": "assistant", "content": "answer" * 66},+ latest,+ ]+ counter = lambda candidate: sum( # noqa: E731+ len(str(message.get("content", ""))) for message in candidate+ )++ fitted, info = fit_rolling_context(+ messages,+ context_length = 1000,+ max_tokens = 250,+ count_tokens = counter,+ )++ assert counter(messages) > 1000 >= counter(fitted)+ assert info["fits"] is False+ assert info["dropped_messages"] == 2+ assert fitted == [latest]++def test_archive_and_recall_is_a_noop_without_a_thread_id(archived):after = _conversation()@@ -778,6 +818,73 @@ def test_recall_is_sized_by_the_room_the_fit_actually_obtained():assert llama_cpp._recall_top_k(1_000_000) == 4+def test_a_tool_loop_retrieval_leaves_room_for_the_turn_it_enables():+ """A tool-loop retrieval leaves room for the reply that follows it."""+ from core.inference import llama_cpp++ # ctx 3000: budget 2250, fit landed at 747.+ single_shot = llama_cpp._retrieval_budget(3000, 3000, 747)+ in_loop = llama_cpp._retrieval_budget(3000, 3000, 747, reply_returns = True)++ assert single_shot == 2250 - 747+ assert in_loop == 1125+ assert in_loop < single_shot+++def test_a_retrieval_budget_is_only_capped_where_it_would_take_most_of_the_turn():+ from core.inference import llama_cpp++ # A window with room to spare is untouched: half of 24,576 is far more than the+ # 5,600-token remainder, so the cap never binds.+ assert llama_cpp._retrieval_budget(32768, 32768, 18976, reply_returns = True) == 24576 - 18976+ # And a fit that already used the whole budget gets nothing, not a negative number.+ assert llama_cpp._retrieval_budget(3000, 3000, 9000, reply_returns = True) == 0+++def test_a_recorded_boundary_is_still_not_a_replayable_one():+ """Recording a rescue's depth must not make it sticky.++ The two questions are different. "What did this fit evict?" is what the client needs+ to place the compaction notice, and a rescue has a real answer. "Which boundary should+ the next request re-apply?" is what a missed reply reserve makes unsafe, and that gate+ lives in `_sticky_compaction_boundary`, where it is decided on `fits` alone.+ """+ from core.inference import llama_cpp++ rescued = {"fits": False, "dropped_messages": 6, "boundary_messages": 6}+ fitted = {"fits": True, "dropped_messages": 6, "boundary_messages": 6}+ refused = {"fits": False, "dropped_messages": 0}++ # Recorded on anything that actually evicted...+ assert llama_cpp._records_boundary(rescued) is True+ assert llama_cpp._records_boundary(fitted) is True+ # ...and not on a refusal that returned the originals, which evicted nothing.+ assert llama_cpp._records_boundary(refused) is False+++def test_both_local_tool_loops_size_retrieval_with_the_same_policy():+ """One implementation, not a copy per backend.++ `search_conversation` is sized against the same window by the GGUF loop and by the+ safetensors loop, and the safetensors one says so in its own comment ("as the GGUF+ loop does"). A private copy in either file is a policy the other quietly disagrees+ with, which is how the two drifted in the first place.+ """+ import inspect++ from core.inference import context_window, llama_cpp, safetensors_agentic++ # The GGUF loop's name is an alias, not a second implementation.+ assert llama_cpp._retrieval_budget is context_window.retrieval_budget++ # And the safetensors loop calls the shared helper rather than rebuilding the+ # expression from prompt_budget.+ source = inspect.getsource(safetensors_agentic)+ assert "retrieval_budget(" in source+ budget_call = source[source.index('kwargs["conversation_budget_tokens"] = retrieval_budget(') :]+ assert "reply_returns = True" in budget_call[:400]++def test_the_sticky_boundary_is_applied_once_per_request():"""The tool loop refits on the conversation the previous fit returned.diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex a39e32e2d65..5359738791d 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -3739,6 +3739,80 @@ def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(moassert len(payloads[1]["messages"]) == 1+def test_a_respawn_refit_that_misses_its_target_still_archives_and_reports(monkeypatch):+ """A rescued respawn refit archives its evictions and emits metadata."""+ import httpx++ from core.inference import llama_cpp++ # Captured once: the second pass would otherwise wrap the first pass's spy.+ real_archive = llama_cpp._archive_and_recall++ for max_tool_iterations in (1, 0):+ payloads: list[dict] = []+ archived: list[tuple[int, int]] = []+ backend = _make_backend(+ monkeypatch,+ [+ httpx.ConnectError("server is down"),+ [_sse({"content": "Recovered."}), _done()],+ ],+ payloads,+ )+ backend._effective_context_length = 2000+ monkeypatch.setattr(+ backend,+ "count_chat_tokens",+ lambda candidate, *_args, **_kwargs: sum(+ len(str(message.get("content", ""))) for message in candidate+ ),+ )++ def spy(conversation, before, **kwargs):+ archived.append((len(before), len(conversation)))+ return real_archive(conversation, before, **kwargs)++ monkeypatch.setattr(llama_cpp, "_archive_and_recall", spy)++ def fake_respawn():+ backend._effective_context_length = 1000+ return True++ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)+ events = list(+ backend.generate_chat_completion_with_tools(+ messages = [+ {"role": "user", "content": "u" * 250},+ {"role": "assistant", "content": "a" * 250},+ {"role": "user", "content": "u" * 250},+ {"role": "assistant", "content": "a" * 250},+ {"role": "user", "content": "f" * 900},+ ],+ tools = [{"type": "function", "function": {"name": "python"}}],+ max_tool_iterations = max_tool_iterations,+ context_overflow = "truncate_oldest",+ )+ )++ notices = [event for event in events if event.get("type") == "context_truncated"]+ assert [notice["context_length"] for notice in notices] == [2000, 1000]+ refit = notices[1]+ # The rescued refusal reports what it evicted, boundary included: the client reads+ # that depth to place the compaction notice, so recording nothing would compact+ # silently. Reported is not REPLAYED, which `_sticky_compaction_boundary` still+ # declines for any `fits` false record.+ assert refit["fits"] is False+ assert refit["dropped_messages"] == 2+ assert refit["prompt_tokens_after"] == 900 < refit["prompt_tokens_before"]+ # 4, not the 2 of `dropped_messages`: the boundary counts against the REQUEST's+ # own leading messages, which the next request replays it against, while the drop+ # count is what this one fit removed.+ assert refit["boundary_messages"] == 4+ assert "boundary_anchor" in refit+ assert archived[-1] == (3, 1)+ assert len(payloads[1]["messages"]) == 1++def test_tool_loop_retries_preflight_when_counting_failed_on_the_dead_server(monkeypatch):import httpxdiff --git a/studio/frontend/src/components/assistant-ui/compaction-notice.tsx b/studio/frontend/src/components/assistant-ui/compaction-notice.tsxindex 0f49ff0ca0e..7c2701c6f07 100644--- a/studio/frontend/src/components/assistant-ui/compaction-notice.tsx+++ b/studio/frontend/src/components/assistant-ui/compaction-notice.tsx@@ -4,7 +4,10 @@import { ArchiveIcon } from "lucide-react";import type { FC } from "react";-import type { ContextTruncation } from "@/features/chat/utils/context-truncation";+import {+ type ContextTruncation,+ promptWasShortened,+} from "@/features/chat/utils/context-truncation";/*** Tells the user their conversation was compacted, on the turn where it STARTED.@@ -21,7 +24,7 @@ import type { ContextTruncation } from "@/features/chat/utils/context-truncationexport const CompactionNotice: FC<{ truncation: ContextTruncation }> = ({truncation,}) => {- if (!truncation?.fits || !truncation.dropped_messages) return null;+ if (!promptWasShortened(truncation)) return null;const dropped = truncation.dropped_messages;const archived = truncation.archived_messages ?? 0;diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex a84136a363f..d68d6e150e6 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -6702,9 +6702,7 @@ const ContinueMessageBarForLastMessage: FC = () => {const truncation = useAuiState(({ message }) => {const custom = (message.metadata as { custom?: Record<string, unknown> } | undefined)?.custom;- return (custom?.contextTruncation ?? null) as- | { fits?: boolean; prompt_target?: number }- | null;+ return (custom?.contextTruncation ?? null) as ContextTruncation | null;});// Hitting Max Tokens is the reply running out of room mid-sentence, not a decision thediff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex ed33ef6a97d..706f949fc9b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -174,7 +174,10 @@ import {createImageGateRunOwner,getImageInputUnavailableReason,} from "../utils/image-input-support";-import { mergeContextTruncation } from "../utils/context-truncation";+import {+ mergeContextTruncation,+ promptWasShortened,+} from "../utils/context-truncation";import {createThinkTagTracker,extractDeltaText,@@ -5724,12 +5727,11 @@ export function createOpenAIStreamAdapter(chunk.context_truncated,);const activeThreadId = useChatRuntimeStore.getState().activeThreadId;- // fits:false means the fitter could NOT make the request fit and returned- // the original messages. Toasting "older turns were removed" is untrue- // there, and burns the once-per-thread flag so a real one is silent.- const reallyCompacted =- chunk.context_truncated.fits === true &&- (chunk.context_truncated.dropped_messages ?? 0) > 0;+ // What must stay silent is a fit that returned the ORIGINAL messages:+ // toasting "older turns were removed" is untrue there, and burns the+ // once-per-thread flag. Not `fits`, which is also false for a shortened+ // prompt that really was sent.+ const reallyCompacted = promptWasShortened(chunk.context_truncated);if (reallyCompacted &&resolvedThreadId &&diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.tsindex ef3f23ec332..b0a7cc48f92 100644--- a/studio/frontend/src/features/chat/utils/context-truncation.ts+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts@@ -16,15 +16,32 @@ function spreadSum(return { [key]: (a ?? 0) + (b ?? 0) };}+/**+ * Whether the fit removed turns from the prompt that was actually sent.+ *+ * Not `fits`: a fit under the physical window that misses the reply reserve still sends+ * the shortened prompt with `fits: false`, and those turns are just as gone. Every path+ * that returned the ORIGINAL messages reports `dropped_messages` as zero.+ */+export function promptWasShortened(+ truncation: ContextTruncation | undefined,+): truncation is ContextTruncation {+ return (truncation?.dropped_messages ?? 0) > 0;+}+export function compactionBoundary(truncation: ContextTruncation | undefined,): number {- if (!truncation?.fits) return 0;- // boundary_messages is where the boundary sits in the saved transcript.- // dropped_messages accumulates what each fit removed, so a tool-heavy turn reports far- // more than the boundary moved and a later real advance looks like none. Fallback only,- // for turns saved before the boundary was recorded.- return truncation.boundary_messages ?? truncation.dropped_messages ?? 0;+ if (!promptWasShortened(truncation)) return 0;+ // boundary_messages is where the boundary sits in the saved transcript, and every fit+ // that evicts records one, rescues included. So the fallback is only for turns saved+ // before it existed, hence gated on `fits`, the one shape those turns have: elsewhere+ // dropped_messages is a per-refit total, not a position, and reading it as one sets a+ // high-water mark `showsNotice` never sees exceeded again.+ return (+ truncation.boundary_messages ??+ (truncation.fits ? (truncation.dropped_messages ?? 0) : 0)+ );}export function mergeContextTruncation(diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.tsindex 0c954b4876a..6584e02c539 100644--- a/studio/frontend/src/features/chat/utils/continuation.ts+++ b/studio/frontend/src/features/chat/utils/continuation.ts@@ -344,8 +344,12 @@ export function shouldAutoContinue(return false;}if (fits === false) {- // This turn's own fit was already refused. Resuming re-sends a partial that is only- // ever longer, so the next round cannot fit either.+ // Neither shape of `fits: false` can be resumed. A refusal never fitted, and a rescue+ // is reached only once eviction ran out of eligible turns, so its prompt is already+ // the floor. Nothing is left to evict either way, while a continuation replays the+ // partial as the final assistant turn, which the fit protects, asking for MORE prompt+ // against the same window: on a 460-of-500-token rescue a 10-character partial+ // already refuses.return false;}if (diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.tsindex db8449dc918..f36bfe56d9b 100644--- a/studio/frontend/tests/chat-continuation.test.ts+++ b/studio/frontend/tests/chat-continuation.test.ts@@ -407,6 +407,18 @@ test("a turn whose own fit was refused is never resumed automatically", () => {);});+test("a turn whose fit only missed the reply reserve is not resumed either", () => {+ resetAutoContinue();+ // A rescue reports `fits: false` too and is just as unresumable: it is reached only+ // once eviction ran out of eligible turns, so its prompt is already the floor, while+ // the continuation replays the partial as the final assistant turn, which the fit+ // protects. Measured on the 460-of-500-token rescue, a 10-character partial refuses.+ assert.equal(+ shouldAutoContinue("length", "parent-1", { fits: false }),+ false,+ );+});+test("a partial that already fills the budget is not resumed", () => {resetAutoContinue();// 3,217 tokens of partial against a 3,648-token target left no room for the system turndiff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.tsindex 7950a42ad3d..ac65f8a5088 100644--- a/studio/frontend/tests/rolling-context-window.test.ts+++ b/studio/frontend/tests/rolling-context-window.test.ts@@ -5,8 +5,10 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";import {+ type ContextTruncation,compactionBoundary,mergeContextTruncation,+ promptWasShortened,} from "../src/features/chat/utils/context-truncation.ts";const adapter = readFileSync(@@ -47,6 +49,105 @@ test("the compaction notice follows the boundary, not the accumulated drops", ()assert.equal(compactionBoundary(undefined), 0);});+test("a shortened prompt still counts as a compaction, whatever fits says", () => {+ // A fit that lands under the physical window but misses the reply reserve sends the+ // eviction with fits:false. The turns are gone from the model's view, so the notice+ // and the toast must fire; only a fit that returned the ORIGINAL messages stays quiet.+ assert.equal(promptWasShortened({ dropped_messages: 2, fits: false }), true);+ assert.equal(promptWasShortened({ dropped_messages: 0, fits: false }), false);+ assert.equal(promptWasShortened(undefined), false);+});++test("a shortened refusal records its boundary, so the notice survives a reload", () => {+ // A rescue evicts for real, so it reports its depth like any other compaction and the+ // persisted notice can find it. Saving the depth is not the same as replaying it:+ // `_sticky_compaction_boundary` still declines any record whose `fits` is false.+ const rescued = { fits: false, dropped_messages: 6, boundary_messages: 6 };+ assert.equal(compactionBoundary(rescued), 6);+ assert.equal(promptWasShortened(rescued), true);++ // A boundary is absolute, so refitting three times does not inflate it.+ let refits: ContextTruncation = {+ fits: false,+ dropped_messages: 4,+ boundary_messages: 4,+ };+ for (const chunk of [+ { fits: false, dropped_messages: 6, boundary_messages: 6 },+ { fits: false, dropped_messages: 6, boundary_messages: 6 },+ ]) {+ refits = mergeContextTruncation(refits, chunk);+ }+ assert.equal(refits.dropped_messages, 16);+ assert.equal(compactionBoundary(refits), 6);+});++test("a record with no boundary never guesses one from a summed drop count", () => {+ // The legacy fallback exists for turns saved before boundary_messages was recorded, and+ // those all fit. On anything else the count is a per-refit SUM, not a position, and+ // reading it as one sets a high-water mark `showsNotice` cannot see exceeded again.+ const oneRefit = { dropped_messages: 2, fits: false };+ let toolLoop: ContextTruncation = { fits: false, dropped_messages: 4 };+ for (const chunk of [+ { fits: false, dropped_messages: 6 },+ { fits: false, dropped_messages: 6 },+ ]) {+ toolLoop = mergeContextTruncation(toolLoop, chunk);+ }++ assert.equal(toolLoop.dropped_messages, 16);+ assert.equal(compactionBoundary(oneRefit), 0);+ assert.equal(compactionBoundary(toolLoop), 0);+ // The notice still fires: that reads promptWasShortened, not the boundary.+ assert.equal(promptWasShortened(toolLoop), true);+ // And a fit that SUCCEEDED still gets the legacy fallback, for turns saved before+ // boundary_messages existed.+ assert.equal(compactionBoundary({ dropped_messages: 3, fits: true }), 3);+ assert.equal(+ compactionBoundary({ dropped_messages: 16, fits: false, boundary_messages: 4 }),+ 4,+ );+});++test("a rescued turn cannot silence the compactions that follow it", () => {+ // The `showsNotice` scan in thread.tsx, which only announces a boundary that ROSE.+ const boundariesShown = (records: any[]) => {+ let high = 0;+ const shown: number[] = [];+ records.forEach((rec, index) => {+ const b = compactionBoundary(rec);+ if (b > high) {+ shown.push(index);+ high = b;+ }+ });+ return shown;+ };++ assert.deepEqual(+ boundariesShown([+ { fits: true, dropped_messages: 4, boundary_messages: 4 },+ { fits: false, dropped_messages: 16 }, // rescued, three refits+ { fits: true, dropped_messages: 2, boundary_messages: 6 },+ { fits: true, dropped_messages: 2, boundary_messages: 8 },+ ]),+ [0, 2, 3],+ );+});++test("the notice and the toast read the same predicate as the boundary", () => {+ const notice = readFileSync(+ new URL(+ "../src/components/assistant-ui/compaction-notice.tsx",+ import.meta.url,+ ),+ "utf8",+ );+ assert.match(notice, /promptWasShortened\(truncation\)/);+ assert.doesNotMatch(notice, /truncation\?\.fits/);+ assert.match(adapter, /promptWasShortened\(chunk\.context_truncated\)/);+});+test("the compaction boundary takes the latest value, never the sum", () => {// dropped_messages counts what each fit removed in front of it, this turn's tool// messages included, so summing it and re-applying the total advances the boundary@@ -285,10 +386,10 @@ test("a fits:false diagnosis is not a compaction", () => {"utf8",);// The fitter returned the ORIGINAL messages with dropped_messages 0, so "older turns- // were removed" is untrue, and toasting it burns the once-per-thread flag.- assert.match(source, /const reallyCompacted =/);- assert.match(source, /context_truncated\.fits === true/);- assert.match(source, /dropped_messages \?\? 0\) > 0/);+ // were removed" is untrue, and toasting it burns the once-per-thread flag. Asserted on+ // the predicate rather than the literal expression, so it survives a rewording.+ assert.match(source, /const reallyCompacted = promptWasShortened\(/);+ assert.equal(promptWasShortened({ dropped_messages: 0, fits: false }), false);});test("the advice depends on WHOSE turn does not fit", () => {