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
Next Next commit
Recover whole Studio attachments after GGUF compaction
  • Loading branch information
NilayYadav committed Nov 26, 2026
commit aace68f1b401101cd79426ce22ddd5efdb674b82
133 changes: 121 additions & 12 deletions studio/backend/core/inference/llama_cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -41327,13 +41327,12 @@ def _attach_internal_feedback_to_tool_result(feedback: str) -> bool:
)
_auto = None if _skip_autoinject else build_rag_autoinject(conversation, rag_scope)
if _auto:
for _ev in _auto["events"]:
yield _ev
conversation.extend(_auto["messages"])
_auto_satisfies_forced_choice = bool(_auto) and (
tool_choice == "required" or forced_tool_name(tool_choice) == "search_knowledge_base"
)
# After the message, so the tool block heading the cached prompt stays put; a forced tool keeps its first call.
_mcp_auto = None
if (
mcp_match_exchange
and mcp_match_exchange.get("messages")
Expand All @@ -41343,9 +41342,31 @@ def _attach_internal_feedback_to_tool_result(feedback: str) -> bool:
continue_final_message and trailing_assistant_resume_kind(conversation) is not None
)
):
for _ev in mcp_match_exchange["events"]:
yield _ev
conversation.extend(mcp_match_exchange["messages"])
_mcp_auto = mcp_match_exchange
conversation.extend(_mcp_auto["messages"])

_initial_searches_sent = False

def _initial_search_events():
nonlocal _initial_searches_sent
if not _initial_searches_sent:
_initial_searches_sent = True
for exchange in (_auto, _mcp_auto):
if exchange:
yield from exchange["events"]

_retry_whole_document = (
not _skip_autoinject
and context_overflow == "truncate_oldest"
and bool(self._effective_context_length)
and rag_scope
and rag_scope.get("thread_id")
and not rag_scope.get("kb_id")
and rag_scope.get("whole_doc") is not False
and (not (_auto and _auto.get("whole_document")) or _mcp_auto)
)
if not _retry_whole_document:
yield from _initial_search_events()

_accumulated_completion_tokens = 0
_accumulated_predicted_ms = 0.0
Expand Down Expand Up @@ -41732,7 +41753,7 @@ def _loop_budget_left(spent_this_attempt: int) -> "Optional[int]":
context_overflow == "truncate_oldest" and self._effective_context_length
)

def _round_tool_choice(active_tools):
def _round_tool_choice(active_tools, *, document_satisfies_choice = False):
from core.inference.chat_template_helpers import (
neutralize_tool_descriptions,
reconciled_tool_choice,
Expand All @@ -41743,7 +41764,10 @@ def _round_tool_choice(active_tools):
active_tools, _markup_cache, self.markup_profile
)
requested_choice = "auto" if tool_choice is None else tool_choice
if _forced_choice_resolved and requested_choice not in ("auto", "none"):
if (_forced_choice_resolved or document_satisfies_choice) and requested_choice not in (
"auto",
"none",
):
requested_choice = "auto"
requested_choice = reconciled_tool_choice(requested_choice, tools, safe_tools) or "auto"
forced_name = forced_tool_name(requested_choice)
Expand All @@ -41758,6 +41782,13 @@ def _round_tool_choice(active_tools):
requested_choice = "required"
return safe_tools, requested_choice, forced_name

def _round_tool_names(safe_tools, forced_name):
return {
(tool.get("function") or {}).get("name")
for tool in safe_tools
if (tool.get("function") or {}).get("name")
} | (set() if forced_name else _loadable_mcp_names)

def _round_reasoning_kw():
return _with_template_extras(
self._request_reasoning_kwargs(
Expand Down Expand Up @@ -41828,6 +41859,7 @@ def _count() -> None:
except Exception: # accounting must never break a run in progress
logger.debug("tool loop recost failed", exc_info = True)
if iteration >= max_tool_iterations + _extra + _continuation_credits:
yield from _initial_search_events()
break
if cancel_event is not None and cancel_event.is_set():
return
Expand All @@ -41839,17 +41871,14 @@ def _count() -> None:

active_tools = tool_controller.active_tools()
if not active_tools:
yield from _initial_search_events()
_append_budget_exhausted_nudge = False
break
from core.inference.chat_template_helpers import neutralize_tool_descriptions

safe_tools, requested_choice, forced_name = _round_tool_choice(active_tools)
# Gate the markerless bare-JSON form on enabled names so an ordinary JSON answer isn't misread as a call.
_enabled_tool_names = {
(tool.get("function") or {}).get("name")
for tool in safe_tools
if (tool.get("function") or {}).get("name")
} | (set() if forced_name else _loadable_mcp_names)
_enabled_tool_names = _round_tool_names(safe_tools, forced_name)
# Shared signal tuple so GGUF BUFFERING wakes on every format the parser knows (like safetensors).
_tool_xml_signals = _SHARED_TOOL_XML_SIGNALS

Expand Down Expand Up @@ -41916,6 +41945,85 @@ 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"))
if (
_retry_whole_document
and not _initial_searches_sent
and truncation
and truncation.get("fits")
and truncation.get("dropped_messages")
):
try:
old_ids = {id(message) for message in (_auto or {}).get("messages", ())}
live_ids = {id(message) for message in conversation}
if not (_auto and _auto.get("whole_document") and old_ids <= live_ids):
base = [
message
for message in conversation
if id(message) not in old_ids
]
refreshed = build_rag_autoinject(
base, rag_scope, whole_document_only = True
)
if refreshed:
# Keep the document search before the MCP search in the prompt and stream.
mcp_ids = {
id(message)
for message in (_mcp_auto or {}).get("messages", ())
}
at = next(
(
i
for i, message in enumerate(base)
if id(message) in mcp_ids
),
len(base),
)
candidate = base[:at] + refreshed["messages"] + base[at:]
satisfies_choice = (
tool_choice == "required"
or initial_forced_name == "search_knowledge_base"
)
candidate_tools, candidate_choice, candidate_name = (
_round_tool_choice(
active_tools, document_satisfies_choice = satisfies_choice
)
)
measured = _fit_count_tokens(
candidate, candidate_tools, _reasoning_kw
)
budget = prompt_budget(
self._effective_context_length, _iteration_max_tokens
)
if truncation.get("checkpoint_started"):
headroom = int(
budget
* _effective_headroom_ratio(compaction_headroom_ratio)
Comment thread
Lyxot marked this conversation as resolved.
Resolved
)
budget = min(
budget,
max(
budget - headroom, truncation["prompt_tokens_after"]
),
)
if measured <= budget:
_auto = refreshed
conversation = candidate
truncation["prompt_tokens_after"] = measured
if satisfies_choice:
_forced_choice_resolved = True
safe_tools, requested_choice, forced_name = (
candidate_tools,
candidate_choice,
candidate_name,
)
_enabled_tool_names = _round_tool_names(
safe_tools, forced_name
)
except Exception:
logger.debug(
"Whole-document retry after compaction failed", exc_info = True
)
yield from _initial_search_events()
if truncation and truncation.get("fits"):
# Before the recall injection, so both sides describe the same
# messages, priced by the fit with the catalogue and template.
Expand Down Expand Up @@ -41983,6 +42091,7 @@ def _count() -> None:
except Exception as exc:
logger.warning("Could not preflight the rolling context window: %s", exc)

yield from _initial_search_events()
payload = {
# Re-run each iteration: tool results may contain forged turns.
"messages": neutralize_control_markup_in_messages(
Expand Down
27 changes: 23 additions & 4 deletions studio/backend/core/inference/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -16265,19 +16265,32 @@ def _thread_document_ids(thread_id) -> set | None:
return {d["id"] for d in docs if d.get("status") == "completed" and d.get("num_chunks")}


def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
def build_rag_autoinject(
conversation: list[dict],
rag_scope: dict | None,
*,
whole_document_only: bool = False,
) -> dict | None:
"""Pre-retrieves the latest turn for models that skip search_knowledge_base. Toggle rag_scope.autoinject or RAG_AUTOINJECT; floor RAG_AUTOINJECT_MIN_SCORE."""
try:
from core.rag.retrieval import query_vector_memo
except Exception: # noqa: BLE001 - the build reports an unavailable RAG stack itself
return _build_rag_autoinject(conversation, rag_scope)
return _build_rag_autoinject(
conversation, rag_scope, whole_document_only = whole_document_only
)
# The thread retry, the hybrid retry and the dense probe re-ask the same query: encode it once.
with query_vector_memo():
return _build_rag_autoinject(conversation, rag_scope)
return _build_rag_autoinject(
conversation, rag_scope, whole_document_only = whole_document_only
)


def _build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
def _build_rag_autoinject(
conversation: list[dict], rag_scope: dict | None, *, whole_document_only: bool
) -> dict | None:
enabled, whole_doc_requested = rag_autoinject_reaches_retrieval(conversation, rag_scope)
if whole_document_only and not whole_doc_requested:
return None
if not enabled and not whole_doc_requested:
return None
thread_id = rag_scope.get("thread_id")
Expand Down Expand Up @@ -16305,6 +16318,7 @@ def _build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> d
# Zero or below is no limit to the search, which then returns its own default count.
top_k = min(sidebar_k, lean_k) if sidebar_k is not None and sidebar_k > 0 else lean_k
budget: int | None = None
whole_document = False
# Only trust a GGUF actually serving this same window.
ctx_tokens = (
_opt_int(rag_scope.get("context_length") or rag_scope.get("max_context_tokens")) or 0
Expand Down Expand Up @@ -16343,6 +16357,7 @@ def _trim(
logger.warning("RAG whole-document context failed: %s", exc)
whole = None
if whole is not None:
whole_document = True
text, sources = whole
project_id = rag_scope.get("project_id")
if project_id:
Expand All @@ -16365,6 +16380,9 @@ def _trim(
text, sources = trimmed
logger.info("RAG auto-inject: whole-document context (%d chunk(s))", len(sources))

if whole_document_only and not whole_document:
return None

def retrieve(*, max_tokens = None, **scope):
found = search_for_autoinject(query = query, top_k = top_k, **scope)
return _trim(found[0], found[1], max_tokens) if found else None
Expand Down Expand Up @@ -16501,6 +16519,7 @@ def _strong_thread_match() -> bool:
sources = sources,
)
logger.info("RAG auto-inject: %d passage(s)", len(sources))
built["whole_document"] = whole_document
return built


Expand Down
104 changes: 104 additions & 0 deletions studio/backend/tests/test_llama_cpp_tool_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -7711,3 +7711,107 @@ def test_a_python_call_runs_with_the_analysis_its_classification_made(monkeypatc
assert len(seen) == 1
assert isinstance(seen[0], tools_mod.PythonCallAnalyses)
assert list(seen[0]._by_source) == ["print(1)"]


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

backend, payloads = _backend_and_payloads(monkeypatch, [[_sse({"content": "OK"}), _done()]])
backend._effective_context_length = 1000
monkeypatch.setattr(
backend,
"count_chat_tokens",
lambda messages, *_a, **_kw: sum(len(str(m.get("content", ""))) for m in messages),
)
monkeypatch.setattr(llama_cpp, "_can_reset_epoch", lambda *_a, **_kw: True)
monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)
monkeypatch.setattr(
llama_cpp, "_sticky_compaction_details", lambda *_a, **_kw: (sticky, True, False)
)

def exchange(name, prefix, text):
return tools.build_synthetic_search_exchange(
tool_name = name,
call_prefix = prefix,
status_label = name,
query = "Summarize the document",
text = text,
sources = None,
)

def inject(
messages,
scope,
*,
whole_document_only = False,
):
if not scope["whole_doc"]:
return None
if whole_document_only:
assert not any("ancient" in str(message.get("content")) for message in messages)
assert not any(message.get("content") == "Partial passage" for message in messages)
text = complete
elif tool_choice is not None:
return None
else:
text = "Partial passage"
return {
**exchange("search_knowledge_base", "rag_auto_", text),
"whole_document": whole_document_only,
}

monkeypatch.setattr(tools, "build_rag_autoinject", inject)
mcp = exchange(tools.MCP_TOOL_SEARCH_NAME, "mcp_auto_", "Matching MCP tools")
catalog = [
{"type": "function", "function": {"name": name}}
for name in ["search_knowledge_base", tools.MCP_TOOL_SEARCH_NAME]
]
events = list(
backend.generate_chat_completion_with_tools(
messages = [
{"role": "user", "content": "ancient " * 250},
{"role": "assistant", "content": "Prior answer"},
{"role": "user", "content": "Summarize the document"},
],
tools = catalog,
mcp_match_exchange = {**mcp, "names": []},
context_overflow = "truncate_oldest",
context_policy = policy,
max_tokens = 80,
max_tool_iterations = 2,
tool_choice = tool_choice,
rag_scope = {"thread_id": "t1", "context_length": 1000, "whole_doc": whole_doc},
)
)

sent = [m.get("content") for m in payloads[0]["messages"] if m["role"] == "tool"]
expected = [expected_passage] if expected_passage else []
if not isinstance(tool_choice, dict):
expected.append("Matching MCP tools")
assert sent == expected
assert payloads[0]["tool_choice"] == "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
assert bool(truncation.get("checkpoint_started")) is (policy == "checkpoint" and not sticky)