Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(studio): keep compaction headroom and recall room for whole-docum…
…ent retries

Budget the post-compaction whole-document retry against the compaction headroom and the conversation-recall reserve on every fit, including boundary replays, so the next tool round and the recall that follows the fit still fit. Cap that fit's recall below the headroom line only when the document grew the prompt, skip the retry when audio or video parts are present (every fit leaves them uncounted), and keep a forced search_knowledge_base choice forced. Drop the trim_target field the rolling fit no longer needs to report.
  • Loading branch information
Lyxot committed Nov 27, 2026
commit cf2dca71ae04a21fe6f1662de4efe464eecbd784
1 change: 0 additions & 1 deletion studio/backend/core/inference/context_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -1000,7 +1000,6 @@ def fit_rolling_context(
"prompt_tokens_before": initial_tokens,
"prompt_tokens_after": current_tokens,
"context_length": context_length,
"trim_target": trim_target,
"fits": True,
}

Expand Down
71 changes: 41 additions & 30 deletions studio/backend/core/inference/llama_cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1681,6 +1681,19 @@ def _branch_boundary(conversation: list[dict], branch: Optional[list[dict]]) ->
return count


def _has_unpriced_media(messages: list[dict]) -> bool:
"""Audio or video, which every fit leaves uncounted; images are priced."""
from core.inference.context_window import _IMAGE_PART_TYPES, _UNPRICED_MEDIA_TYPES

uncounted = _UNPRICED_MEDIA_TYPES - _IMAGE_PART_TYPES
return any(
isinstance(part, dict) and part.get("type") in uncounted
for message in messages
if isinstance(message.get("content"), list)
for part in message["content"]
)


def _records_boundary(truncation: dict) -> bool:
"""Not the fits flag: a rescued fit still evicts, and skipping the save compacts silently. Saving is not replaying: sticky logic declines fits-false records."""
return bool(truncation.get("fits")) or bool(truncation.get("dropped_messages"))
Expand Down Expand Up @@ -41945,12 +41958,14 @@ def _count() -> None:
# Accounted for in this request now, whatever the fit decided.
_sticky_boundary_applied = True
_loop_cut = _loop_cut or bool(truncation and truncation.get("dropped_messages"))
_fit_recall_cap = float("inf")
if (
_retry_whole_document
and not _initial_searches_sent
and truncation
and truncation.get("fits")
and truncation.get("dropped_messages")
and not _has_unpriced_media(conversation)
):
try:
old_ids = {id(message) for message in (_auto or {}).get("messages", ())}
Expand Down Expand Up @@ -41979,10 +41994,8 @@ def _count() -> None:
len(base),
)
candidate = base[:at] + refreshed["messages"] + base[at:]
satisfies_choice = (
tool_choice == "required"
or initial_forced_name == "search_knowledge_base"
)
# A forced name stays forced: this fit priced and worded the prompt for that one tool.
satisfies_choice = tool_choice == "required"
candidate_tools, candidate_choice, candidate_name = (
_round_tool_choice(
active_tools, document_satisfies_choice = satisfies_choice
Expand All @@ -41991,29 +42004,24 @@ def _count() -> None:
measured = _fit_count_tokens(
candidate, candidate_tools, _reasoning_kw
)
# Leave the compaction headroom and, when recall runs, its reserve free, also on a replay.
budget = prompt_budget(
self._effective_context_length, _iteration_max_tokens
)
if truncation.get("checkpoint_started"):
headroom = int(
budget
* _effective_headroom_ratio(compaction_headroom_ratio)
)
budget = min(
budget,
max(
budget - headroom, truncation["prompt_tokens_after"]
),
)
elif "trim_target" in truncation:
budget = min(
budget,
max(
truncation["trim_target"],
truncation["prompt_tokens_after"],
),
)
if measured <= budget:
headroom_line = budget - int(
budget
* _effective_headroom_ratio(compaction_headroom_ratio)
)
reserve = (
_conversation_recall_reserve(thread_id)
if truncation.get("checkpoint_started", True)
else 0
)
fitted_tokens = truncation["prompt_tokens_after"]
if measured <= max(headroom_line - reserve, fitted_tokens):
# A larger prompt leaves this fit's recall the room up to the headroom, not into it.
if measured > fitted_tokens:
_fit_recall_cap = max(0, headroom_line - measured)
_auto = refreshed
conversation = candidate
truncation["prompt_tokens_after"] = measured
Expand Down Expand Up @@ -42055,12 +42063,15 @@ def _count() -> None:
# 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,
# As above: the cap this iteration will actually send.
_iteration_max_tokens,
truncation.get("prompt_tokens_after") or 0,
reply_returns = True,
recall_budget_tokens = min(
_retrieval_budget(
self._effective_context_length,
# As above: the cap this iteration will actually send.
_iteration_max_tokens,
truncation.get("prompt_tokens_after") or 0,
reply_returns = True,
),
_fit_recall_cap,
),
count_tokens = lambda fitted: self.count_chat_tokens(
neutralize_control_markup_in_messages(
Expand Down
62 changes: 46 additions & 16 deletions studio/backend/tests/test_llama_cpp_tool_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -7714,27 +7714,35 @@ def test_a_python_call_runs_with_the_analysis_its_classification_made(monkeypatc


@pytest.mark.parametrize(
"policy, tool_choice, whole_doc, sticky, complete, expected_passage",
"policy, tool_choice, whole_doc, sticky, reserve, audio, complete, expected_passage",
[
("checkpoint", None, True, 0, "Complete document", "Complete document"),
("checkpoint", "required", True, 0, "Complete document", "Complete document"),
("checkpoint", None, True, 0, 0, False, "Complete document", "Complete document"),
("checkpoint", "required", True, 0, 0, False, "Complete document", "Complete document"),
(
"checkpoint",
{"type": "function", "function": {"name": "search_knowledge_base"}},
True,
0,
0,
False,
"Complete document",
"Complete document",
),
("rolling", None, True, 0, "Complete document", "Complete document"),
("rolling", None, True, 0, "Large document " * 50, "Partial passage"),
("checkpoint", None, True, 2, "Complete document", "Complete document"),
("checkpoint", None, True, 0, "Large document " * 50, "Partial passage"),
("checkpoint", None, False, 0, "", None),
("rolling", None, True, 0, 0, False, "Complete document", "Complete document"),
("rolling", None, True, 0, 0, False, "Large document " * 50, "Partial passage"),
("checkpoint", None, True, 2, 0, False, "Complete document", "Complete document"),
("checkpoint", None, True, 2, 0, False, "Medium document " * 45, "Partial passage"),
("rolling", None, True, 2, 0, False, "Medium document " * 45, "Partial passage"),
("rolling", None, True, 2, 0, False, "Medium document " * 25, "Medium document " * 25),
("rolling", None, True, 2, 300, False, "Medium document " * 25, "Partial passage"),
("rolling", None, True, 2, 100, False, "Medium document " * 25, "Medium document " * 25),
("checkpoint", None, True, 0, 0, False, "Large document " * 50, "Partial passage"),
("checkpoint", None, True, 0, 0, True, "Complete document", "Partial passage"),
("checkpoint", None, False, 0, 0, False, "", None),
],
)
def test_first_context_fit_retries_whole_document_in_prompt_order(
monkeypatch, policy, tool_choice, whole_doc, sticky, complete, expected_passage
monkeypatch, policy, tool_choice, whole_doc, sticky, reserve, audio, complete, expected_passage
):
from core.inference import tools

Expand All @@ -7749,15 +7757,18 @@ def test_first_context_fit_retries_whole_document_in_prompt_order(
monkeypatch.setattr(
llama_cpp, "_keeps_compaction_boundary", lambda thread_id: thread_id == "t1"
)
monkeypatch.setattr(
llama_cpp,
"_archive_and_recall",
lambda conversation, *_a, **_kw: dict(conversation = conversation, counts = {}, recalled = False),
)
recall_budgets = []

def archive_and_recall(conversation, *_a, recall_budget_tokens, **_kw):
recall_budgets.append(recall_budget_tokens)
return dict(conversation = conversation, counts = {}, recalled = False)

monkeypatch.setattr(llama_cpp, "_archive_and_recall", archive_and_recall)
monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)
monkeypatch.setattr(
llama_cpp, "_sticky_compaction_details", lambda *_a, **_kw: (sticky, True, False)
)
monkeypatch.setattr(llama_cpp, "_conversation_recall_reserve", lambda _thread_id: reserve)

def exchange(name, prefix, text):
return tools.build_synthetic_search_exchange(
Expand Down Expand Up @@ -7791,6 +7802,7 @@ def inject(
}

monkeypatch.setattr(tools, "build_rag_autoinject", inject)
audio_part = [{"type": "input_audio", "input_audio": {"data": "", "format": "wav"}}] * audio
mcp = exchange(tools.MCP_TOOL_SEARCH_NAME, "mcp_auto_", "Matching MCP tools")
catalog = [
{"type": "function", "function": {"name": name}}
Expand All @@ -7801,7 +7813,10 @@ def inject(
messages = [
{"role": "user", "content": "ancient " * 250},
{"role": "assistant", "content": "Prior answer"},
{"role": "user", "content": "Summarize the document"},
{
"role": "user",
"content": [{"type": "text", "text": "Summarize the document"}, *audio_part],
},
],
tools = catalog,
mcp_match_exchange = {**mcp, "names": []},
Expand All @@ -7821,8 +7836,23 @@ def inject(
if not isinstance(tool_choice, dict):
expected.append("Matching MCP tools")
assert sent == expected
assert payloads[0]["tool_choice"] == "auto"
assert payloads[0]["tool_choice"] == ("required" if isinstance(tool_choice, dict) else "auto")
assert [e["result"] for e in events if e["type"] == "tool_end"] == sent
truncation = next(e for e in events if e["type"] == "context_truncated")
assert truncation["fits"] and truncation["dropped_messages"] == 2
if not audio:
assert truncation["prompt_tokens_after"] == sum(
len(str(m.get("content", ""))) for m in payloads[0]["messages"]
)
if policy == "rolling":
from core.inference.context_window import prompt_budget, retrieval_budget

prompt = truncation["prompt_tokens_after"]
recall = retrieval_budget(1000, 80, prompt, reply_returns = True)
if expected_passage == complete:
target = prompt_budget(1000, 80)
recall = min(recall, target - int(target * 0.25) - prompt)
assert recall_budgets[0] == recall
if isinstance(tool_choice, dict):
assert [t["function"]["name"] for t in payloads[0]["tools"]] == ["search_knowledge_base"]
assert bool(truncation.get("checkpoint_started")) is (policy == "checkpoint" and not sticky)
19 changes: 19 additions & 0 deletions studio/backend/tests/test_rag_whole_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,25 @@ def test_build_rag_autoinject_large_model_auto_falls_back_over_budget(rag_conn,
assert _injected_text(result) == "TOPK_LARGE_MODEL_FALLBACK"


def test_build_rag_autoinject_whole_document_only_follows_the_history_budget(rag_conn, monkeypatch):
_add_doc(
rag_conn, store.thread_scope("t1"), "d1", "doc.pdf", "h1", ["whole body"], tokens = [600]
)
scope = {"thread_id": "t1", "context_length": 4000}
long_history = [{"role": "user", "content": "x" * 10_000}, *_convo()]
sentinel = ("TOPK_TEXT", [{"citationId": 1, "filename": "doc.pdf", "text": "x"}])
searches = []
monkeypatch.setattr(tool, "search_for_autoinject", lambda **kw: searches.append(kw) or sentinel)
excerpts = inf_tools.build_rag_autoinject(long_history, scope)
assert _injected_text(excerpts) == "TOPK_TEXT" and excerpts["whole_document"] is False

searches.clear()
assert inf_tools.build_rag_autoinject(long_history, scope, whole_document_only = True) is None
assert searches == []
whole = inf_tools.build_rag_autoinject(_convo(), scope, whole_document_only = True)
assert "whole body" in _injected_text(whole) and whole["whole_document"] is True


def test_build_rag_autoinject_fallback_is_thread_first_and_budgeted(rag_conn, monkeypatch):
monkeypatch.setattr(tool, "whole_document_context", lambda **kw: None)
monkeypatch.setattr(inf_tools, "_thread_document_ids", lambda thread_id: None)
Expand Down