Skip to content

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.

Studio: keep and search the turns rolling context evicts (#9074)

Daniel Han18b97f8b72ad
diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.py
index e25a5e21bd8..8e3b2266874 100644
--- a/studio/backend/core/inference/context_window.py
+++ b/studio/backend/core/inference/context_window.py
@@ -6,11 +6,21 @@
from __future__ import annotations
import json
+import os
from collections.abc import Callable
from typing import Any, Optional
_OMITTED_TOOL_EXCHANGE = "[Earlier tool exchange omitted from the rolling context window.]"
+# How far BELOW the prompt budget a compaction trims, as a fraction of that budget.
+# Trimming to exactly the budget puts the next turn over it again, so the boundary creeps
+# forward every turn: llama-server's prefix cache dies each time and there is no discrete
+# compaction event to report. Taking a chunk out in one go buys a stretch of turns with a
+# fixed head, at the cost of the headroom itself, hence a minority of the budget.
+_COMPACTION_HEADROOM_RATIO = max(
+ 0.0, min(0.9, float(os.environ.get("ROLLING_COMPACTION_HEADROOM_RATIO", "0.25")))
+)
+
def estimate_message_tokens(message: dict) -> int:
try:
@@ -23,21 +33,39 @@ def estimate_messages_tokens(messages: list[dict]) -> int:
return sum(estimate_message_tokens(message) for message in messages)
-def truncate_oldest_messages(
- messages: list[dict],
- keep_ratio: float,
- *,
- protected_message_ids: Optional[set[int]] = None,
-) -> tuple[list[dict], int]:
- """Drop complete oldest turns while preserving system messages and the latest turn.
+def estimate_messages_tokens_dense(messages: list[dict]) -> int:
+ """The same estimate, but honest about text that tokenises densely.
+
+ Four characters per token is about right for English and badly wrong for CJK and
+ emoji, which run closer to one token per character. Measured on an 81-message CJK
+ chat: 1295 estimated against 2737 real, a 2.1x undercount, which a caller sizing a
+ search budget spends as room it does not have. `_conversation_search_tokens` already
+ charges non-ASCII a token each when pricing the result; this is the same rule applied
+ to the spend, which is the half that was missing.
- Normal user/assistant turns stay together. Each assistant tool call starts a
- separate group containing its tool results, so long agent runs can evict old
- exchanges without orphaning results or losing the task that initiated them.
+ Deliberately NOT the default. `truncate_oldest_messages` evicts on the flat estimate,
+ and making eviction pessimistic would drop history a request could have kept. Only a
+ caller deciding how much room is LEFT wants this, where erring high is the safe side.
"""
- if not messages or keep_ratio >= 1.0:
- return messages, 0
+ total = 0
+ for message in messages:
+ try:
+ text = json.dumps(message, ensure_ascii = False)
+ except Exception:
+ total += 1
+ continue
+ dense = sum(1 for char in text if ord(char) > 127)
+ total += max(1, dense + (len(text) - dense) // 4)
+ return total
+
+def group_turns(messages: list[dict]) -> list[list[dict]]:
+ """Split messages into the turn groups the rolling window evicts as single units.
+
+ Each assistant tool call starts its own group holding its tool results, so long agent
+ runs evict old exchanges without orphaning results. Exposed so callers that act on
+ evicted turns use the same unit the evictor does.
+ """
groups: list[list[dict]] = []
for message in messages:
starts_tool_exchange = message.get("role") == "assistant" and bool(
@@ -54,6 +82,35 @@ def truncate_oldest_messages(
groups.append([message])
else:
groups[-1].append(message)
+ return groups
+
+
+def evicted_messages(before: list[dict], after: list[dict]) -> list[dict]:
+ """Messages present in ``before`` and absent from ``after``, in their original order.
+
+ Identity, not equality: the truncation helpers reuse the same dict objects, and a
+ chat can contain two byte-identical turns ("continue" twice) that equality collapses.
+ """
+ kept = {id(message) for message in after}
+ return [message for message in before if id(message) not in kept]
+
+
+def truncate_oldest_messages(
+ messages: list[dict],
+ keep_ratio: float,
+ *,
+ protected_message_ids: Optional[set[int]] = None,
+ min_dropped: int = 0,
+) -> tuple[list[dict], int]:
+ """Drop complete oldest turns while preserving system messages and the latest turn.
+
+ ``min_dropped`` keeps evicting past the point where the prompt fits, so a thread can
+ re-apply the boundary it already compacted to instead of one that slides every turn.
+ """
+ if not messages or (keep_ratio >= 1.0 and min_dropped <= 0):
+ return messages, 0
+
+ groups = group_turns(messages)
if len(groups) <= 1:
return messages, 0
@@ -102,7 +159,7 @@ def truncate_oldest_messages(
dropped_groups: set[int] = set()
for unit in eviction_units:
- if current_estimate <= target_estimate:
+ if current_estimate <= target_estimate and dropped >= min_dropped:
break
dropped_groups.update(unit)
for group_index in unit:
@@ -117,8 +174,8 @@ def truncate_oldest_messages(
for index, group in enumerate(groups):
if index not in dropped_groups:
if kept and kept[-1].get("role") == "user" and group and group[0].get("role") == "user":
- # Strict chat templates reject adjacent user turns. This occurs when
- # an internal tool re-prompt follows an evicted exchange.
+ # Strict chat templates reject adjacent user turns, which an internal
+ # tool re-prompt after an evicted exchange would produce.
kept.append({"role": "assistant", "content": _OMITTED_TOOL_EXCHANGE})
kept.extend(group)
return kept, dropped
@@ -132,11 +189,9 @@ def messages_have_media(messages: list[dict]) -> bool:
for part in content:
if not isinstance(part, dict):
continue
- # `input_video` is llama.cpp's own part type, written by `_inject_video_part`
- # into the same message list this fit then sees. Missing from the list, a video
- # prompt ran the rolling preflight even though `/apply-template` does not count
- # the sampled video tokens, so it could be certified as fitting when it does
- # not, or lose history it did not need to lose.
+ # `input_video` is llama.cpp's own part type (written by `_inject_video_part`);
+ # missing it here would let a video prompt take the rolling preflight, whose
+ # `/apply-template` count omits the sampled video tokens.
if part.get("type") in (
"image_url",
"input_audio",
@@ -148,6 +203,33 @@ def messages_have_media(messages: list[dict]) -> bool:
return False
+def prompt_budget(context_length: int, max_tokens: Optional[int]) -> int:
+ """Tokens available to the PROMPT, once room for the reply is set aside.
+
+ Exported so the recall sizing and the client's over-long-request explanation share
+ this formula rather than each keeping a copy that drifts from the actual fit.
+ """
+ if context_length <= 1:
+ return context_length
+ requested = max_tokens if max_tokens is not None and max_tokens > 0 else context_length
+ return context_length - min(requested, max(1, context_length // 4))
+
+
+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.
+
+ A tool loop can reach the does-not-fit diagnosis with a tool result last, which strict
+ templates reject on its own; letting that raise would abort the fit and tell the user
+ nothing. An approximate number beats a diagnosis that never arrives.
+ """
+ if not messages:
+ return 0
+ try:
+ return count_tokens(messages[-1:])
+ except Exception:
+ return estimate_messages_tokens(messages[-1:])
+
+
def fit_rolling_context(
messages: list[dict],
*,
@@ -155,27 +237,72 @@ def fit_rolling_context(
max_tokens: Optional[int],
count_tokens: Callable[[list[dict]], int],
protected_message_ids: Optional[set[int]] = None,
+ reserve_tokens: int = 0,
+ sticky_dropped: int = 0,
+ keeps_boundary: bool = False,
) -> tuple[list[dict], Optional[dict[str, Any]]]:
"""Fit a chat into its real context by dropping oldest complete turns.
- The exact tokenizer/template count decides whether trimming is needed. The
- inexpensive estimator only chooses candidate turns; exact recounts verify the
- result. The current turn is never clipped, so an irreducibly large request still
- reaches llama-server's normal context-length error.
+ The exact tokenizer/template count decides whether trimming is needed; the cheap
+ estimator only picks candidate turns. The current turn is never clipped, so an
+ irreducibly large request still reaches llama-server's context-length error.
+
+ ``reserve_tokens`` leaves room for what the caller adds back after fitting (recalled
+ turns). It deliberately does not affect whether to trim at all, so a chat that fits
+ today is never evicted just because the reserve would not fit alongside it.
+
+ ``sticky_dropped`` is the boundary this thread last compacted to, in messages,
+ re-applied before anything else and moved only if what is left still does not fit.
+ Without it the fit is stateless (the client re-sends the whole transcript each turn)
+ so the boundary slides every reply; with it plus ``_COMPACTION_HEADROOM_RATIO`` of
+ slack, compaction is an occasional event the prefix cache can survive.
+
+ Acceptance is still checked against the untightened ``prompt_target``: falling short
+ of the headroom is not a failure to fit.
"""
if context_length <= 1:
return messages, None
- requested_headroom = max_tokens if max_tokens is not None and max_tokens > 0 else context_length
- output_headroom = min(requested_headroom, max(1, context_length // 4))
- prompt_target = context_length - output_headroom
+ prompt_target = prompt_budget(context_length, max_tokens)
fitted = list(messages)
initial_tokens = count_tokens(fitted)
current_tokens = initial_tokens
dropped_total = 0
- while current_tokens > prompt_target:
- keep_ratio = min(0.95, prompt_target / max(1, current_tokens))
+ # Phase one: put the boundary back where this thread already had it, so a compacted
+ # thread stops compacting further every turn. Gated on the prompt not already
+ # fitting: a saved boundary describes the branch it was measured on, and after a
+ # rollback it would evict most of a chat that comfortably fits.
+ if sticky_dropped > 0 and initial_tokens > prompt_target:
+ candidate, dropped = truncate_oldest_messages(
+ fitted,
+ 1.0,
+ protected_message_ids = protected_message_ids,
+ min_dropped = sticky_dropped,
+ )
+ if dropped:
+ fitted = candidate
+ dropped_total = dropped
+ current_tokens = count_tokens(fitted)
+
+ # Phase two, only if what is left still does not fit: move the boundary, taking a
+ # chunk out rather than skimming to the brim so it can stay put for a while.
+ trim_target = prompt_target
+ if current_tokens > prompt_target:
+ # Summed, not max()'d: the reserve is spent immediately on recalled passages, so
+ # counting it as headroom would hand back room that is already taken.
+ #
+ # And only for a caller that can put the boundary back next request. The headroom
+ # buys quiet turns between compactions by cutting deeper than needed, which is a
+ # bargain only if the deeper cut is remembered. An incognito chat, an API request
+ # with no persisted thread, or a request whose turns are not saved gets neither
+ # the boundary nor a recall of what went, so there it is simply 25% less history
+ # than plain eviction would have kept.
+ headroom = int(prompt_target * _COMPACTION_HEADROOM_RATIO) if keeps_boundary else 0
+ trim_target = max(1, prompt_target - reserve_tokens - headroom)
+
+ while current_tokens > trim_target:
+ keep_ratio = min(0.95, trim_target / max(1, current_tokens))
candidate, dropped = truncate_oldest_messages(
fitted,
keep_ratio,
@@ -187,7 +314,29 @@ def fit_rolling_context(
dropped_total += dropped
current_tokens = count_tokens(fitted)
- if dropped_total == 0 or current_tokens > prompt_target:
+ 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, {
+ "fits": False,
+ "dropped_messages": 0,
+ "prompt_tokens_before": initial_tokens,
+ "prompt_tokens_after": 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,
+ "latest_turn_tokens": _latest_turn_tokens(messages, count_tokens),
+ # ...and whose message that is. In a tool loop the last message is often a
+ # tool result, which the user did not write and cannot shorten.
+ "latest_turn_role": str(messages[-1].get("role") or "") if messages else "",
+ "context_length": context_length,
+ "prompt_target": prompt_target,
+ }
+ if dropped_total == 0:
return messages, None
return fitted, {
"dropped_messages": dropped_total,
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 9e556b5db92..d454f90acb4 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -1035,6 +1035,9 @@ class InferenceBackend:
rag_scope = rag_scope,
reasoning_prefilled = reasoning_prefilled,
continue_final_message = continue_final_message,
+ # So a conversation search can be sized against what this model can hold.
+ context_length = _model_info.get("context_length"),
+ max_tokens = max_new_tokens,
)
def generate_chat_response(
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 38ed378b10e..dbf5da7f379 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -49,7 +49,14 @@ from typing import (
import httpx
-from core.inference.context_window import fit_rolling_context, messages_have_media
+from core.inference.context_window import (
+ prompt_budget,
+ estimate_messages_tokens,
+ estimate_messages_tokens_dense,
+ evicted_messages,
+ fit_rolling_context,
+ messages_have_media,
+)
from core.inference.llama_server_args import (
_GPU_LAYER_FLAGS,
_LAYER_OFFLOAD_FLAGS,
@@ -86,6 +93,7 @@ from core.inference.tool_call_parser import (
StreamingMarkupStripper as _StreamingMarkupStripper,
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
+ RAG_SEARCH_TOOLS,
parse_tool_calls_from_text as _shared_parse_tool_calls_from_text,
strip_leading_bare_json_call,
strip_llama3_leading_sentinels,
@@ -124,7 +132,6 @@ from state.tool_approvals import (
new_approval_id,
wait_tool_decision,
)
-from utils.paths.path_utils import is_appledouble_metadata
logger = get_logger(__name__)
@@ -464,6 +471,448 @@ def _native_linux_system_rocm_lib_dirs(binary_dir: str = "") -> "list[str]":
# enough for reasoning-heavy GGUFs and max_tokens-omitting API clients.
_DEFAULT_MAX_TOKENS_FLOOR = 32768
_DEFAULT_FIRST_TOKEN_TIMEOUT_S = 1200.0 # 20 min
+
+
+def _conversation_recall_reserve(thread_id: Optional[str]) -> int:
+ """Room to hold back during a fit for the turns recalled straight after it."""
+ if not thread_id:
+ return 0
+ try:
+ from core.rag import config as rag_config
+ from core.rag import conversation_archive
+
+ # Eligibility, not just availability. A temporary chat is never archived, so the
+ # reserve stays empty while still being subtracted from the trim target. Measured
+ # on a 4K chat: 15 tokens of conversation survived instead of 1,615.
+ if not conversation_archive.can_archive(thread_id):
+ return 0
+ # And that it works: sqlite-vec can be present while the embedder cannot start,
+ # so archiving fails quietly and the reserved room is pure loss on every
+ # compaction, forgetting more history than having the feature off.
+ if conversation_archive.degraded():
+ return 0
+ return max(0, int(rag_config.CONVERSATION_RECALL_RESERVE_TOKENS))
+ except Exception:
+ return 0
+
+
+def _keeps_compaction_boundary(thread_id: Optional[str]) -> bool:
+ """Whether this request's boundary will be there to restore next time.
+
+ The boundary rides on the assistant turn's saved metadata, so a thread with no saved
+ messages (incognito, or an API caller that persists nothing) never gets one back. The
+ fit uses this to decide whether cutting deeper than needed buys anything.
+ """
+ if not thread_id:
+ return False
+ try:
+ from storage import studio_db
+ return bool(studio_db.chat_thread_has_messages(str(thread_id)))
+ except Exception:
+ return False
+
+
+def _archive_branch_transcript(
+ branch_messages: Optional[list[dict]], roles: Optional[tuple[str, ...]] = None
+) -> Optional[list[str]]:
+ """The active branch, one normalised string per message, or None if there is nothing."""
+ if not branch_messages:
+ return None
+ try:
+ from core.rag import conversation_archive
+ return conversation_archive.branch_message_texts(branch_messages, roles)
+ except Exception:
+ return None
+
+
+def _branch_boundary(conversation: list[dict], branch: Optional[list[dict]]) -> int:
+ """How many of the REQUEST's own leading messages a fit has evicted.
+
+ The boundary is persisted and re-applied to the NEXT request's saved transcript, so it
+ must be counted in those terms. ``dropped_messages`` is not: the tool loop refits each
+ iteration and the client sums the counts, so a long agent run also counts the tool
+ exchanges it created, which the next request's transcript does not contain.
+
+ Counted by identity. Instruction messages are skipped rather than treated as the front
+ of the branch, or a Studio request (always system-prefixed) would report zero on every
+ compaction and the boundary would slide every turn again. Everything from the newest
+ USER turn on is excluded: it is never evicted, and an inline recall rewrites that turn
+ into a new dict, which an identity scan reads as an eviction. Excluding just the last
+ message is not the same thing, since a continued assistant message follows it.
+ """
+ messages = list(branch or ())
+ cutoff = max(
+ (index for index, message in enumerate(messages) if message.get("role") == "user"),
+ default = max(0, len(messages) - 1),
+ )
+ messages = messages[:cutoff]
+ live = {id(message) for message in conversation}
+ count = 0
+ for message in messages:
+ if message.get("role") in ("system", "developer"):
+ continue
+ if id(message) in live:
+ break
+ count += 1
+ return count
+
+
+def _branch_non_system(branch: Optional[list[dict]]) -> list[dict]:
+ """The branch as ``_branch_boundary`` counts it: system and developer turns removed."""
+ return [
+ message for message in (branch or ()) if message.get("role") not in ("system", "developer")
+ ]
+
+
+def _branch_boundary_anchor(conversation: list[dict], branch: Optional[list[dict]]) -> str:
+ """The text of the first message a fit KEPT, as the branch spells it, or "".
+
+ ``boundary_messages`` is a count against one particular transcript, and the next
+ request's transcript is not guaranteed to be that one plus new turns: deleting an
+ already-evicted prompt shortens the front, so replaying the count unchanged lands the
+ boundary two messages too deep and evicts history that is still live. The anchor names
+ the message the boundary was meant to land ON, which survives a deletion in front of it.
+
+ Text, not an id or an index: ids are per-request objects and an index is the very thing
+ that goes stale. Read back by ``_sticky_compaction_boundary``, which only ever lets the
+ anchor make the boundary SHALLOWER, so a stale or ambiguous anchor costs one extra
+ compaction and can never evict a live turn.
+ """
+ messages = _branch_non_system(branch)
+ live = {id(message) for message in conversation}
+ for message in messages:
+ if id(message) in live:
+ return _anchor_text(message)
+ return ""
+
+
+# Bounded so one long tool argument cannot bloat the metadata the UI stores per turn. The
+# name plus the head of the arguments is already enough to tell two calls apart.
+_ANCHOR_ARGS_CHARS = 200
+# And the anchor as a whole. It rides in every `context_truncated` event and is persisted
+# on every assistant turn for as long as the boundary stays sticky, so returning a large
+# pasted prompt whole duplicated it across the thread's SSE payloads and history rows. A
+# head is enough to name a message, and the read side clamps only ever SHALLOWER, so two
+# messages sharing a head cost one extra compaction rather than a live turn.
+_ANCHOR_TEXT_CHARS = 200
+
+
+def _anchor_text(message: dict) -> str:
+ """A message as the anchor spells it: its text, or its tool calls when it has none.
+
+ A normal OpenAI assistant tool-call message carries empty ``content`` and puts its
+ substance in ``tool_calls``. Reading only ``content`` recorded an empty anchor there,
+ which silently disables the rebase: the next request cannot re-derive the boundary
+ against a shortened transcript and replays the stale count, evicting one more live
+ message per deleted one. Both sides of the comparison use this, so what is written is
+ what is looked for.
+ """
+ text = _archive_message_text(message.get("content"))
+ if text:
+ return text[:_ANCHOR_TEXT_CHARS]
+ parts = []
+ for call in message.get("tool_calls") or ():
+ function = (call or {}).get("function") or {}
+ name = str(function.get("name") or "tool")
+ arguments = str(function.get("arguments") or "").strip()[:_ANCHOR_ARGS_CHARS]
+ parts.append(f"{name}: {arguments}" if arguments else name)
+ return "\n".join(parts)[:_ANCHOR_TEXT_CHARS]
+
+
+def _archive_message_text(content) -> str:
+ """One stored message flattened the way the branch check flattens it, or ""."""
+ try:
+ from core.rag import conversation_archive
+ return conversation_archive.message_text(content)
+ except Exception:
+ return ""
+
+
+def _archive_content_on_branch(content, transcript: Optional[list[str]]) -> bool:
+ if transcript is None:
+ return True
+ try:
+ from core.rag import conversation_archive
+ return conversation_archive.content_on_branch(content, transcript)
+ except Exception:
+ return True
+
+
+def _sticky_compaction_boundary(
+ thread_id: Optional[str], branch_messages: Optional[list[dict]] = None
+) -> int:
+ """How many leading messages this thread last compacted away, or 0.
+
+ The fit is otherwise stateless: the client re-sends the whole transcript each request,
+ so "keep the newest N tokens" slides forward every turn, which tells the user nothing
+ useful and throws away llama-server's prefix cache each time the head moves. Reading
+ the boundary back makes compaction an occasional event.
+
+ Read from the thread's newest assistant turn, which already persists this number for
+ the UI, so nothing new is stored and it survives a restart. Never raises: no history,
+ a non-persisting API client, or a storage error all mean "no boundary".
+ """
+ if not thread_id:
+ return 0
+ try:
+ from storage import studio_db
+
+ # The stored rows are the whole DAG, so the newest assistant turn can belong to a
+ # sibling branch left by Retry, whose boundary is sized for history this branch
+ # does not have. Skip rows the request's own messages do not contain.
+ # Assistant messages only: the rows being checked are assistant replies, and
+ # against every role a short abandoned one ("Done") rides in on a live user
+ # message that merely contains it ("not done yet"), taking its boundary with it.
+ _branch = _archive_branch_transcript(branch_messages, ("assistant",))
+ if branch_messages and not _branch:
+ # A branch with no reply of its own has no boundary to restore.
+ return 0
+ candidates = [
+ message
+ for message in reversed(studio_db.list_chat_messages(thread_id) or [])
+ if message.get("role") == "assistant"
+ and _archive_content_on_branch(message.get("content"), _branch)
+ ]
+ if not candidates:
+ return 0
+
+ # The newest on-branch assistant turn decides, except that the branch check is
+ # textual, so two Retry siblings that both read "Done" are indistinguishable here
+ # and the first match could apply a much deeper branch's boundary. Where the text
+ # cannot separate them, take the SMALLEST boundary: too small costs one extra
+ # compaction, too large evicts live history.
+ # That check is also a substring test (an archived turn is matched against
+ # fragments of itself), so an abandoned "Done" can ride in on a live "Not done
+ # yet" and then decide the boundary alone. Prefer exact matches where any exist.
+ _live = set(_branch or ())
+ _exact = [
+ message
+ for message in candidates
+ if _archive_message_text(message.get("content")) in _live
+ ]
+ if _exact:
+ candidates = _exact
+
+ newest = _archive_message_text(candidates[0].get("content"))
+ boundaries = []
+ for message in candidates:
+ if _archive_message_text(message.get("content")) != newest:
+ continue
+ metadata = message.get("metadata") or {}
+ if not isinstance(metadata, dict):
+ return 0
+ truncation = metadata.get("contextTruncation") or (metadata.get("custom") or {}).get(
+ "contextTruncation"
+ )
+ if not isinstance(truncation, dict):
+ return 0
+ # Only a fit that SUCCEEDED describes a boundary worth restoring.
+ if not truncation.get("fits"):
+ return 0
+ # Counted against the request's own transcript, which is what it is applied
+ # to. `dropped_messages` is the fallback for turns saved before that was
+ # recorded: equal for a single fit, too large for a turn that refit often.
+ recorded = truncation.get("boundary_messages")
+ if recorded is None:
+ recorded = truncation.get("dropped_messages")
+ recorded = max(0, int(recorded or 0))
+ # A count is only valid against the transcript it was counted on. Deleting an
+ # already-evicted turn shortens the front, and replaying the count then evicts
+ # that many LIVE messages instead. Re-derive it from the anchor's position on
+ # this request's own branch. Only ever downward: an anchor that has moved back
+ # (a repeated text, an edited turn) must not deepen the cut.
+ anchor = truncation.get("boundary_anchor")
+ if isinstance(anchor, str) and anchor:
+ for index, message in enumerate(_branch_non_system(branch_messages)):
+ if _anchor_text(message) == anchor[:_ANCHOR_TEXT_CHARS]:
+ recorded = min(recorded, index)
+ break
+ boundaries.append(recorded)
+ return min(boundaries) if boundaries else 0
+ except Exception:
+ return 0
+ return 0
+
+
+def _prefix_user_text(message: dict, prefix: str) -> dict:
+ """Copy of ``message`` with ``prefix`` in front of its text. Never mutates."""
+ content = message.get("content")
+ if isinstance(content, str) or content is None:
+ return {**message, "content": prefix + (content or "")}
+ if isinstance(content, list):
+ parts = list(content)
+ for index, part in enumerate(parts):
+ if isinstance(part, dict) and part.get("type") in ("text", "input_text"):
+ parts[index] = {**part, "text": prefix + str(part.get("text") or "")}
+ return {**message, "content": parts}
+ return {**message, "content": [{"type": "text", "text": prefix}] + parts}
+ return message
+
+
+def _recall_top_k(budget_tokens: int) -> int:
+ """How many archived chunks actually fit in the room a fit obtained.
+
+ The reserve is what the fit AIMS to hold back, not what it gets: protected messages
+ (system, latest turn, anchored recalls) can stop the trim reaching its target while
+ still passing the prompt budget. Injecting a full reserve on top then overflows the
+ window -- reproduced at ctx 8000: fit accepted at 6900, recall took it to 8948. So
+ size the recall from the room actually left.
+ """
+ try:
+ from core.rag import config as rag_config
+ chunk = max(1, int(rag_config.CHUNK_TOKENS))
+ cap = max(0, int(rag_config.CONVERSATION_ARCHIVE_TOP_K))
+ except Exception:
+ return 0
+ fits = int(budget_tokens) // chunk
+ if fits <= 0 and int(budget_tokens) > 0:
+ # One attempt whenever there is ANY room. `CHUNK_TOKENS` is a ceiling, not the
+ # size of a turn: most archived turns are far smaller, so flooring to zero
+ # disabled recall on exactly the tight windows that need it. The exact recount
+ # below is what actually decides, and it rejects a chunk that does not fit.
+ fits = 1
+ return max(0, min(cap, fits))
+
+
+def _archive_and_recall(
+ conversation: list[dict],
+ before: list[dict],
+ *,
+ thread_id: Optional[str],
+ style: str,
+ recall_done: bool,
+ recall_budget_tokens: int = 0,
+ count_tokens: Optional[Callable[[list[dict]], int]] = None,
+ branch_messages: Optional[list[dict]] = None,
+) -> dict:
+ """Keep the turns this fit evicted, then pull the relevant ones back.
+
+ Returns ``{"conversation", "events", "counts", "recalled"}``. Never raises: every
+ failure degrades to the plain fitted messages. Recall fires at most once per request,
+ or the tool loop's per-iteration refit would stack a recall block onto each pass.
+ """
+ result = {
+ "conversation": conversation,
+ "events": [],
+ "counts": {},
+ "recalled": False,
+ "anchored": [],
+ }
+ if not thread_id:
+ return result
+ try:
+ from core.inference.tools import build_conversation_recall
+ from core.rag import conversation_archive
+
+ if not conversation_archive.enabled():
+ return result
+
+ gone = evicted_messages(before, conversation)
+ archived = conversation_archive.archive_turns(thread_id, gone) if gone else 0
+ counts = {"archived_messages": archived}
+
+ if recall_done:
+ result["counts"] = counts
+ return result
+
+ top_k = _recall_top_k(recall_budget_tokens)
+ if top_k <= 0:
+ # No room obtained. Archiving still happened, so the turns stay searchable
+ # and the next fit can recall them.
+ result["counts"] = counts
+ return result
+
+ # An EXACT recount decides affordability: the chunk arithmetic above is doubly an
+ # estimate, since CHUNK_TOKENS is an embedding-token limit rather than the chat
+ # template's cost and neither it nor the budget covers the wrapper text.
+ # When the recount says no, ask for FEWER turns rather than giving up: with the
+ # shipped defaults a full top-K of long turns lands just over the reserve once
+ # wrapped, and dropping it would disable recall on exactly the long conversations
+ # this exists for. Halving is bounded (4 -> 2 -> 1), one small query per attempt.
+ attempts = []
+ attempt_k = top_k
+ while True:
+ attempts.append(attempt_k)
+ if attempt_k <= 1:
+ break
+ attempt_k = max(1, attempt_k // 2)
+
+ for index, k in enumerate(attempts):
+ recall = build_conversation_recall(
+ conversation,
+ thread_id,
+ style = style,
+ top_k = k,
+ branch_messages = branch_messages,
+ )
+ if not recall:
+ result["counts"] = counts
+ return result
+
+ candidate = _inject_recall(conversation, recall, style)
+ if candidate is None:
+ result["counts"] = counts
+ return result
+
+ grew = None
+ if count_tokens is not None and recall_budget_tokens > 0:
+ try:
+ grew = count_tokens(candidate["conversation"]) - count_tokens(conversation)
+ except Exception:
+ grew = None
+ if grew is not None and grew > recall_budget_tokens:
+ logger.info(
+ "conversation_recall.over_budget grew=%s budget=%s top_k=%s",
+ grew,
+ recall_budget_tokens,
+ k,
+ )
+ if index + 1 < len(attempts):
+ continue
+ logger.info(
+ "conversation_recall.dropped_over_budget budget=%s", recall_budget_tokens
+ )
+ result["counts"] = counts
+ return result
+
+ result["conversation"] = candidate["conversation"]
+ result["events"] = candidate["events"]
+ result["anchored"] = candidate["anchored"]
+ break
+
+ counts["recalled_chunks"] = int(recall.get("sources") or 0)
+ result["counts"] = counts
+ result["recalled"] = True
+ except Exception as exc:
+ logger.warning("Could not archive or recall compacted turns: %s", exc)
+ return result
+
+
+def _inject_recall(conversation: list[dict], recall: dict, style: str) -> Optional[dict]:
+ """The conversation with ``recall`` added, or None if there was nowhere to put it.
+
+ ``anchored`` is only what this injection added: the two synthetic tool messages, or
+ the rewritten user message inline. The caller protects those from a later refit, and
+ anything else would pin a real turn the fit is entitled to evict.
+ """
+ if style == "inline":
+ prefix = recall.get("prefix") or ""
+ updated = list(conversation)
+ for index in range(len(updated) - 1, -1, -1):
+ if updated[index].get("role") == "user":
+ updated[index] = _prefix_user_text(updated[index], prefix)
+ break
+ else:
+ return None
+ return {"conversation": updated, "events": [], "anchored": [updated[index]]}
+ added = list(recall["messages"])
+ return {
+ "conversation": list(conversation) + added,
+ "events": list(recall["events"]),
+ "anchored": added,
+ }
+
+
# A transport error can arrive before the child is reapable; a request path cannot
# afford the 5s the background MTP reload spends on the same race.
_RESPAWN_REAP_GRACE_S = 1.0
@@ -1349,7 +1798,7 @@ def _gguf_snapshot_files(snapshot: Path) -> list[str]:
return [
p.relative_to(snapshot).as_posix()
for p in snapshot.rglob("*")
- if p.is_file() and p.name.lower().endswith(".gguf") and not is_appledouble_metadata(p)
+ if p.is_file() and p.name.lower().endswith(".gguf")
]
@@ -1686,29 +2135,7 @@ def _companion_snapshot_sibling(
return str(candidate) if _drafter_split_is_complete(candidate) else None
-def _pick_dspark(candidates: list[str]) -> Optional[str]:
- """The DSpark drafter a listing offers, or None. Module level for the same reason
- ``_pick_mmproj`` is: both are handed a live repo listing as well as a snapshot."""
- from hub.utils.gguf import drop_shadowed_appledouble_names
- from utils.models.model_config import dspark_preference_key
-
- # Every GGUF under dspark/ qualifies, so a sidecar ranks equal to its sibling and sorts first.
- files = sorted(
- (
- name
- for name in drop_shadowed_appledouble_names(list(candidates))
- if _is_dspark_drafter_path(name)
- ),
- key = dspark_preference_key,
- )
- return files[0] if files else None
-
-
def _pick_mmproj(candidates: list[str]) -> Optional[str]:
- from hub.utils.gguf import drop_shadowed_appledouble_names
-
- # "._mmproj-F16.gguf" satisfies the F16 preference and sorts ahead of the real adapter.
- candidates = drop_shadowed_appledouble_names(list(candidates))
mmproj_files = sorted(
f for f in candidates if f.lower().endswith(".gguf") and "mmproj" in Path(f).name.lower()
)
@@ -1917,13 +2344,10 @@ def _gguf_files_for_variant(files: Iterable[str], variant: str) -> list[str]:
Prefer exact quant-label matches over loose substring matches so a request
for ``stories260K`` does not resolve to ``stories260K-be.gguf``.
"""
- from hub.utils.gguf import drop_shadowed_appledouble_names
-
variant_key = variant.strip().lower()
- # A repo listing has no bytes to read; a local one arrives already filtered on its headers.
main_files = [
f
- for f in drop_shadowed_appledouble_names(list(files))
+ for f in files
if f.lower().endswith(".gguf")
and not _is_companion_gguf_path(f)
# The endian predicate reads a quant TOKEN -- it decides whether the quant came from the
@@ -8954,11 +9378,9 @@ class LlamaCppBackend:
from huggingface_hub import get_paths_info, list_repo_files
files = list_repo_files(hf_repo, token = hf_token)
- from hub.utils.gguf import drop_shadowed_appledouble_names
-
gguf_files = [
f
- for f in drop_shadowed_appledouble_names(list(files))
+ for f in files
if f.lower().endswith(".gguf")
and not _is_companion_gguf_path(f)
and not _is_big_endian_gguf_path(f)
@@ -10687,6 +11109,14 @@ class LlamaCppBackend:
if caps_probe is None:
caps_probe = self.probe_server_capabilities
+ def _pick_dspark(candidates: list[str]) -> Optional[str]:
+ from utils.models.model_config import dspark_preference_key
+ files = sorted(
+ (name for name in candidates if _is_dspark_drafter_path(name)),
+ key = dspark_preference_key,
+ )
+ return files[0] if files else None
+
cached = _companion_snapshot_sibling(near_path, _pick_dspark) if near_path else None
if not cached and _hf_env_offline():
cached = self._cached_repo_dspark_drafter(
@@ -11998,30 +12428,6 @@ class LlamaCppBackend:
"settings and reload."
)
- # llama.cpp prints the four bytes it found with %c, so a binary header arrives as
- # unprintable characters; the generic fallback then blamed the user's memory (#8566).
- if "invalid magic characters" in lowered:
- # Not necessarily the main model: the projector and drafter report this too.
- base = os.path.basename(gguf_path) if gguf_path else ""
- named = f", loading {base}" if base else ""
- # A "._" model path proves the volume keeps xattrs in companions, whichever file
- # llama-server actually opened, and dot_clean is the remedy for the volume.
- remedy = (
- 'This volume has no native extended attributes, so macOS keeps them in "._" '
- 'companions: run "dot_clean -m" on the folder to remove them, or keep models '
- "on an APFS disk."
- if base.startswith("._")
- else "Re-download the model, or pick a different file."
- )
- return LlamaCppBackend._with_startup_diagnostics(
- f"llama-server opened a file that is not a GGUF{named}: it does not start with "
- "the GGUF magic. It may be that file or a companion loaded with it, such as a "
- f"vision projector or a drafter, which llama-server does not always name. {remedy}",
- output,
- log_path,
- secrets,
- )
-
# Detect Ollama source up front so the arch branch can keep the
# Ollama hint instead of the generic "unsupported arch" message.
gguf = gguf_path or ""
@@ -21398,6 +21804,7 @@ class LlamaCppBackend:
promote_reasoning_only: bool = True,
perf_callback: Optional[Callable[[dict], None]] = None,
context_overflow: Optional[str] = None,
+ thread_id: Optional[str] = None,
_allow_respawn_retry: bool = True,
) -> Generator[Union[str, dict], None, None]:
"""
@@ -21464,6 +21871,7 @@ class LlamaCppBackend:
and not messages_have_media(openai_messages)
):
try:
+ _before_fit = openai_messages
openai_messages, truncation = fit_rolling_context(
openai_messages,
context_length = self._effective_context_length,
@@ -21477,18 +21885,59 @@ class LlamaCppBackend:
continue_final_message = continue_final_message,
should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
),
+ reserve_tokens = _conversation_recall_reserve(thread_id),
+ sticky_dropped = _sticky_compaction_boundary(thread_id, _before_fit),
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
)
+ if truncation and truncation["fits"]:
+ # 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(
+ openai_messages,
+ _before_fit,
+ branch_messages = _before_fit,
+ thread_id = thread_id,
+ style = "inline",
+ 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),
+ ),
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ fitted, None, self.markup_profile
+ ),
+ None,
+ None,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ continue_final_message = continue_final_message,
+ ),
+ )
+ openai_messages = _recalled["conversation"]
+ truncation = {**truncation, **_recalled["counts"]}
+ if truncation and truncation.get("fits"):
+ truncation = {
+ **truncation,
+ "boundary_messages": _branch_boundary(openai_messages, _before_fit),
+ "boundary_anchor": _branch_boundary_anchor(openai_messages, _before_fit),
+ }
payload["messages"] = neutralize_control_markup_in_messages(
openai_messages, None, self.markup_profile
)
- # Reuse the exact fitted request after a respawn. Re-running this
- # preflight would emit the same truncation event a second time.
+ # Reuse the fitted request on respawn; re-running the preflight would
+ # emit the same truncation event twice.
retry_messages = openai_messages
retry_image_b64 = None
retry_max_tokens = payload["max_tokens"]
retry_context_overflow = None
retry_preflight_context_length = self._effective_context_length
- if truncation and truncation["fits"]:
+ # `fits` False too: it carries the diagnosis the client needs to explain
+ # WHY. Otherwise the user only sees llama-server's error, which reports
+ # the whole conversation's size and advises shortening it even when the
+ # single message just sent is the part that does not fit.
+ if truncation:
yield {"type": "context_truncated", **truncation}
except Exception as exc:
logger.warning("Could not preflight the rolling context window: %s", exc)
@@ -21628,8 +22077,8 @@ class LlamaCppBackend:
retry_preflight_context_length is not None
and retry_preflight_context_length != self._effective_context_length
):
- # Refit the already-compacted prompt against a replacement server's
- # actual window. Any event now reports only additional evictions.
+ # Refit the compacted prompt against the replacement server's window;
+ # any event now reports only additional evictions.
retry_context_overflow = context_overflow
if max_tokens is None:
retry_max_tokens = None
@@ -21653,6 +22102,11 @@ class LlamaCppBackend:
promote_reasoning_only = promote_reasoning_only,
perf_callback = perf_callback,
context_overflow = retry_context_overflow,
+ # The retry refits for the replacement window and can evict more than
+ # the first attempt did. Without the thread those extra turns are
+ # archived nowhere and no reserve or boundary applies, on the one path
+ # that deliberately compacts again.
+ thread_id = thread_id,
_allow_respawn_retry = False,
)
return
@@ -21712,7 +22166,11 @@ class LlamaCppBackend:
{"type": "content", "text": "token"} -- streamed content tokens (cumulative)
{"type": "reasoning", "text": "token"} -- streamed reasoning tokens (cumulative)
"""
- from core.inference.tool_stream_exec import accepts_output_callback, stream_tool_execution
+ from core.inference.tool_stream_exec import (
+ accepts_kwarg,
+ accepts_output_callback,
+ stream_tool_execution,
+ )
from core.inference.tools import (
build_rag_autoinject,
execute_tool,
@@ -21740,6 +22198,40 @@ class LlamaCppBackend:
conversation = list(messages)
_rolling_anchor_ids: set[int] = set()
+ # The loop refits on every iteration; recall must fire once per request, or each
+ # pass stacks another block of recalled turns onto the prompt.
+ _conversation_recall_done = False
+ # The sticky boundary describes the ORIGINAL transcript, so apply it at most once
+ # per request. Each later refit runs on what the previous fit returned, so
+ # re-applying the count evicts another boundary-sized block of live history, and
+ # the summed events persist the inflated total into the next request.
+ _sticky_boundary_applied = False
+ # Exact templated prompt tokens minus the estimator's view of the same messages,
+ # measured once by the preflight. The estimator cannot see the tool catalogue or
+ # the template framing, thousands of tokens with a large (MCP) catalogue: enough
+ # for a conversation search to be told there is room it does not have. Carrying
+ # the difference makes the estimate exact where it was measured.
+ _prompt_token_offset: Optional[int] = None
+ # The branch this request is on, kept aside before anything is evicted from or
+ # injected into `conversation`. The archive is keyed by thread and the stored rows
+ # are the whole DAG (Retry keeps the replaced response as a sibling), so recall
+ # has to be told which branch is live, and the client's messages are the answer.
+ _request_branch: list[dict] = list(messages)
+ # ...and everything this request adds to it. A long agent run can evict its own
+ # earlier tool exchange, which is archived; filtered against the messages the
+ # client sent, that document looks like an abandoned branch and is refused, so the
+ # model cannot get back a tool result it still needs to answer. Accumulated rather
+ # than read off `conversation`, which has already lost what earlier fits evicted.
+ _live_branch: list[dict] = list(messages)
+ _live_branch_ids: set[int] = {id(message) for message in messages}
+
+ def _extend_live_branch(current: list[dict]) -> list[dict]:
+ for message in current:
+ if id(message) not in _live_branch_ids:
+ _live_branch_ids.add(id(message))
+ _live_branch.append(message)
+ return _live_branch
+
for message in reversed(conversation):
if message.get("role") == "user":
_rolling_anchor_ids.add(id(message))
@@ -21994,6 +22486,7 @@ class LlamaCppBackend:
):
_preflight_context_length = self._effective_context_length
try:
+ _before_fit = conversation
conversation, truncation = fit_rolling_context(
conversation,
context_length = self._effective_context_length,
@@ -22012,8 +22505,75 @@ class LlamaCppBackend:
should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
),
protected_message_ids = _rolling_anchor_ids,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
+ reserve_tokens = _conversation_recall_reserve(thread_id),
+ sticky_dropped = (
+ 0
+ if _sticky_boundary_applied
+ else _sticky_compaction_boundary(thread_id, _request_branch)
+ ),
)
+ # Accounted for in this request now, whatever the fit decided.
+ _sticky_boundary_applied = True
+ 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.
+ _prompt_token_offset = int(
+ truncation.get("prompt_tokens_after") or 0
+ ) - estimate_messages_tokens(conversation)
if truncation and truncation["fits"]:
+ _recalled = _archive_and_recall(
+ conversation,
+ _before_fit,
+ branch_messages = _extend_live_branch(_before_fit),
+ thread_id = thread_id,
+ # Tool style forges an assistant tool_call plus a tool result
+ # for search_conversation, safe only when the request
+ # advertises it. On the FIRST compaction the archive did not
+ # exist at tool-selection time, so it is absent, and a tool
+ # role with no catalogue entry breaks strict templates.
+ style = (
+ "tool" if "search_conversation" in _enabled_tool_names else "inline"
+ ),
+ 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),
+ ),
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ fitted, _markup_cache, self.markup_profile
+ ),
+ None,
+ safe_tools,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ ),
+ )
+ conversation = _recalled["conversation"]
+ truncation = {**truncation, **_recalled["counts"]}
+ if _recalled["recalled"]:
+ _conversation_recall_done = True
+ # Anchor exactly what the injection added, so a later refit
+ # cannot evict what we just paid to bring back. NOT the last
+ # two messages: inline recall appends nothing and rewrites the
+ # latest user turn in place, so that slice also pinned a whole
+ # eviction unit the fit was entitled to drop.
+ for _message in _recalled["anchored"]:
+ _rolling_anchor_ids.add(id(_message))
+ for _ev in _recalled["events"]:
+ yield _ev
+ if truncation and truncation.get("fits"):
+ truncation = {
+ **truncation,
+ "boundary_messages": _branch_boundary(conversation, _request_branch),
+ "boundary_anchor": _branch_boundary_anchor(
+ conversation, _request_branch
+ ),
+ }
+ # `fits` False too: it carries the does-not-fit diagnosis.
+ if truncation:
yield {"type": "context_truncated", **truncation}
_preflight_succeeded = True
except Exception as exc:
@@ -22064,6 +22624,7 @@ class LlamaCppBackend:
def _refit_iteration_after_respawn() -> None:
nonlocal conversation
+ _before_respawn_fit = conversation
if (
_preflight_context_length is None
or not self._effective_context_length
@@ -22094,11 +22655,33 @@ class LlamaCppBackend:
should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
),
protected_message_ids = _rolling_anchor_ids,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
)
+ 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.
+ truncation.update(
+ _archive_and_recall(
+ conversation,
+ _before_respawn_fit,
+ thread_id = thread_id,
+ style = "inline",
+ recall_done = True,
+ branch_messages = _extend_live_branch(conversation),
+ )["counts"]
+ )
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
+ )
_respawn_truncations.append(truncation)
except Exception as exc:
logger.warning("Could not refit rolling context after respawn: %s", exc)
@@ -23121,7 +23704,7 @@ class LlamaCppBackend:
_effective_timeout = None if tool_call_timeout >= 9999 else tool_call_timeout
# RAG: cap paraphrased KB re-searches that slip past the dup guard.
if (
- decision.tool_name == "search_knowledge_base"
+ decision.tool_name in RAG_SEARCH_TOOLS
and _kb_search_count >= RAG_MAX_SEARCHES_PER_TURN
):
result = RAG_SEARCH_CAP_NUDGE
@@ -23140,6 +23723,107 @@ class LlamaCppBackend:
rag_scope = rag_scope,
disable_sandbox = bypass_permissions,
)
+ # Same branch the forced recall is filtered against, so a
+ # model-initiated search cannot reach a sibling response the
+ # forced recall correctly refused.
+ if accepts_kwarg(execute_tool, "conversation_branch"):
+ kwargs["conversation_branch"] = _extend_live_branch(conversation)
+ # And the room actually left: the model picks its own top_k and
+ # the result lands in the current tool exchange, which rolling
+ # truncation protects, so a top_k the window cannot hold ends
+ # the turn in an unrecoverable context-length error.
+ if self._effective_context_length and accepts_kwarg(
+ execute_tool, "conversation_budget_tokens"
+ ):
+ # Priced against the catalogue too: the messages alone
+ # leave the tools array out, and a big catalogue can put
+ # the request near its budget while this still reports
+ # room for several 500-token chunks.
+ # `fit_rolling_context` returns None when it dropped
+ # nothing, so a prompt that simply FITS leaves
+ # `_prompt_token_offset` unset -- after a context-length
+ # increase, or on a shorter branch. The character estimate
+ # that stood in for it there leaves out the template's own
+ # framing, so it can report room that is not there, the
+ # recall appends a passage too large for the real window,
+ # and the next iteration cannot evict it again because the
+ # current tool exchange is protected.
+ #
+ # So price it exactly instead, here: this runs when the
+ # model actually reaches for a retrieval tool on a request
+ # that did not truncate, not on every turn. A failure falls
+ # back to the estimate, which is what this did before.
+ #
+ # Recomputed on EVERY search, not cached for the request.
+ # The count is absolute, and the loop appends the assistant
+ # call and the tool result of every intervening tool to
+ # `conversation`, so a cached figure understates the prompt
+ # by exactly those exchanges and hands the search room that
+ # is already spent. The offset on the other leg is a
+ # framing correction rather than a total, so it stays valid
+ # as the conversation grows.
+ # Unconditionally, not only when the fit dropped nothing.
+ # Gated on `_prompt_token_offset is None`, a request that
+ # HAD compacted priced every later search as a character
+ # estimate plus an offset measured before the loop's own
+ # tool exchanges existed, so a dense ASCII result appended
+ # after that fit -- code, minified JSON, command output --
+ # was undercounted and the recall spent room that was
+ # already gone. The exact count covers the same ground as
+ # the offset leg, since it prices the conversation WITH
+ # the tool catalogue, so the offset stays only as the
+ # fallback for a tokenizer call that raises.
+ _exact_prompt_tokens: Optional[int] = None
+ try:
+ _exact_prompt_tokens = self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ conversation, _markup_cache, self.markup_profile
+ ),
+ None,
+ safe_tools,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ )
+ except Exception:
+ logger.debug(
+ "recall budget: exact prompt count failed",
+ exc_info = True,
+ )
+ # Dense on the fallback leg only: `_prompt_token_offset`
+ # already carries the fit's exact tokenizer count, so it
+ # needs no correction, while the estimate that stands in
+ # for it undercounts CJK and emoji by about half.
+ _spent = (
+ _exact_prompt_tokens
+ if _exact_prompt_tokens is not None
+ else estimate_messages_tokens_dense(conversation)
+ + (
+ _prompt_token_offset
+ if _prompt_token_offset is not None
+ else estimate_messages_tokens_dense(safe_tools or [])
+ )
+ )
+ if accepts_kwarg(execute_tool, "conversation_token_counter"):
+ # The admission check estimates a result's size by
+ # characters, which is optimistic for ASCII that
+ # tokenises densely: code, minified JSON, hashes and
+ # command output all run nearer two or three
+ # characters per token than four. This path has a
+ # tokenizer, so hand it over and let the check spend
+ # the budget as exactly as it computes it.
+ kwargs["conversation_token_counter"] = (
+ lambda text: self.count_chat_tokens(
+ [{"role": "tool", "content": text}],
+ None,
+ None,
+ strict = False,
+ )
+ )
+ kwargs["conversation_budget_tokens"] = max(
+ 0,
+ prompt_budget(self._effective_context_length, max_tokens)
+ - _spent,
+ )
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
return execute_tool(
@@ -23154,7 +23838,7 @@ class LlamaCppBackend:
tool_call_id = decision.tool_call_id,
cancel_event = cancel_event,
)
- if decision.tool_name == "search_knowledge_base":
+ if decision.tool_name in RAG_SEARCH_TOOLS:
_kb_search_count += 1
completion = tool_controller.record_result(decision, result)
resolved_provisional_tool_call_ids.add(decision.tool_call_id)
@@ -23307,6 +23991,7 @@ class LlamaCppBackend:
):
_final_preflight_context_length = self._effective_context_length
try:
+ _before_final_fit = conversation
conversation, truncation = fit_rolling_context(
conversation,
context_length = self._effective_context_length,
@@ -23320,8 +24005,60 @@ class LlamaCppBackend:
should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
),
protected_message_ids = _rolling_anchor_ids,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
+ reserve_tokens = _conversation_recall_reserve(thread_id),
+ sticky_dropped = (
+ 0
+ if _sticky_boundary_applied
+ else _sticky_compaction_boundary(thread_id, _request_branch)
+ ),
)
+ _sticky_boundary_applied = True
if truncation and truncation["fits"]:
+ _recalled = _archive_and_recall(
+ conversation,
+ _before_final_fit,
+ branch_messages = _extend_live_branch(_before_final_fit),
+ thread_id = thread_id,
+ # Inline, not tool: this final-answer request is counted and sent
+ # with no tools array, so a forged tool role has no catalogue to
+ # match and breaks strict templates.
+ style = "inline",
+ 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),
+ ),
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ fitted, None, self.markup_profile
+ ),
+ None,
+ None,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ ),
+ )
+ conversation = _recalled["conversation"]
+ truncation = {**truncation, **_recalled["counts"]}
+ if _recalled["recalled"]:
+ _conversation_recall_done = True
+ for _message in _recalled["anchored"]:
+ _rolling_anchor_ids.add(id(_message))
+ for _ev in _recalled["events"]:
+ yield _ev
+ if truncation and truncation.get("fits"):
+ truncation = {
+ **truncation,
+ "boundary_messages": _branch_boundary(conversation, _request_branch),
+ "boundary_anchor": _branch_boundary_anchor(conversation, _request_branch),
+ }
+ # `fits` False too: it carries the diagnosis the client needs to explain
+ # WHY. Otherwise the user only sees llama-server's error, which reports
+ # the whole conversation's size and advises shortening it even when the
+ # single message just sent is the part that does not fit.
+ if truncation:
yield {"type": "context_truncated", **truncation}
_final_preflight_succeeded = True
except Exception as exc:
@@ -23356,6 +24093,7 @@ class LlamaCppBackend:
def _refit_final_after_respawn() -> None:
nonlocal conversation
+ _before_respawn_fit = conversation
if (
_final_preflight_context_length is None
or not self._effective_context_length
@@ -23381,11 +24119,30 @@ class LlamaCppBackend:
should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
),
protected_message_ids = _rolling_anchor_ids,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
)
+ if truncation and truncation["fits"]:
+ # Archive only, for the same reason as the iteration refit above.
+ truncation.update(
+ _archive_and_recall(
+ conversation,
+ _before_respawn_fit,
+ thread_id = thread_id,
+ style = "inline",
+ recall_done = True,
+ branch_messages = _extend_live_branch(conversation),
+ )["counts"]
+ )
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
+ )
_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/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index db558ced681..4429d2afbd1 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -1878,6 +1878,9 @@ class InferenceOrchestrator:
permission_mode = permission_mode,
reasoning_prefilled = reasoning_prefilled,
continue_final_message = continue_final_message,
+ # So a conversation search can be sized against what this model can hold.
+ context_length = _model_info.get("context_length"),
+ max_tokens = max_new_tokens,
)
def generate_with_adapter_control(
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 3a764b0e0f3..f5fd0b1c6e2 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -33,6 +33,7 @@ from core.inference.tool_call_parser import (
NUDGE_TOOL_CALLS_STATUS,
RAG_MAX_SEARCHES_PER_TURN,
RAG_SEARCH_CAP_NUDGE,
+ RAG_SEARCH_TOOLS,
StreamingMarkupStripper,
TOOL_XML_SIGNALS,
is_reprompt_repeat,
@@ -432,22 +433,26 @@ def _tool_event_provenance(**flags: object) -> dict[str, object]:
return tool_event_provenance(**flags)
-def _accepts_output_callback(func: Callable[..., str]) -> bool:
- """Whether an injectable ``execute_tool`` supports ``output_callback``.
+def _accepts_kwarg(func: Callable[..., str], name: str) -> bool:
+ """Whether an injectable ``execute_tool`` supports the keyword ``name``.
The loop's ``execute_tool`` is a parameter (tests inject fakes), so forward
- the live-output kwarg only when the callable declares it or takes ``**kwargs``.
+ an optional kwarg only when the callable declares it or takes ``**kwargs``.
"""
try:
sig = inspect.signature(func)
except (TypeError, ValueError):
return False
params = sig.parameters
- if "output_callback" in params:
+ if name in params:
return True
return any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
+def _accepts_output_callback(func: Callable[..., str]) -> bool:
+ return _accepts_kwarg(func, "output_callback")
+
+
def _call_single_turn(single_turn, conversation: list, active_tools: list[dict]):
"""Call a single-turn generator with active tool schemas when supported."""
try:
@@ -479,6 +484,8 @@ def run_safetensors_tool_loop(
continue_final_message: bool = False,
markup = None,
renderable_tools = None,
+ context_length: Optional[int] = None,
+ max_tokens: Optional[int] = None,
) -> Generator[dict, None, None]:
"""Drive an agentic tool loop on top of a cumulative-text generator.
@@ -503,6 +510,11 @@ def run_safetensors_tool_loop(
* ``{"type": "tool_end", "tool_name", "tool_call_id", "result"}``
"""
conversation = list(messages)
+ # The branch this request is on, before the loop appends anything. A GGUF-compacted
+ # thread keeps its archive across a switch to safetensors, so search_conversation is
+ # advertised here too and needs the same filtering: the stored rows are the whole
+ # DAG, and Retry leaves the replaced response in them.
+ request_branch = list(messages)
# Mirrors the GGUF loop: "full" and bypass_permissions are the same switch;
# unset defaults to "auto", unknown falls back to the stricter "ask"; "off"
@@ -1277,7 +1289,7 @@ def run_safetensors_tool_loop(
eff_timeout = None if tool_call_timeout >= 9999 else tool_call_timeout
# RAG: cap paraphrased KB re-searches that slip past the dup guard.
if (
- decision.tool_name == "search_knowledge_base"
+ decision.tool_name in RAG_SEARCH_TOOLS
and kb_search_count >= RAG_MAX_SEARCHES_PER_TURN
):
result = RAG_SEARCH_CAP_NUDGE
@@ -1295,6 +1307,31 @@ def run_safetensors_tool_loop(
rag_scope = rag_scope,
disable_sandbox = bypass_permissions,
)
+ if _accepts_kwarg(execute_tool, "conversation_branch"):
+ kwargs["conversation_branch"] = request_branch
+ # And the room the model has left, as the GGUF loop does: without a
+ # budget the tool's clamp is skipped and a model-chosen top_k of 8
+ # appends roughly 4K tokens to an already full prompt.
+ if context_length and _accepts_kwarg(
+ execute_tool, "conversation_budget_tokens"
+ ):
+ from core.inference.context_window import (
+ estimate_messages_tokens_dense,
+ prompt_budget,
+ )
+
+ # Dense, unlike the eviction estimator: four characters per token
+ # undercounts CJK and emoji by about half, and this path has no
+ # rolling fit to recover if the tool exchange it sizes then puts
+ # 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 []),
+ )
if _accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)
@@ -1309,7 +1346,7 @@ def run_safetensors_tool_loop(
except Exception as exc:
logger.exception("Tool %s raised: %s", decision.tool_name, exc)
result = f"Error: tool raised an exception: {exc}"
- if decision.tool_name == "search_knowledge_base":
+ if decision.tool_name in RAG_SEARCH_TOOLS:
kb_search_count += 1
completion = tool_controller.record_result(decision, result)
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index a43e3347f5a..488d7346d34 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -72,6 +72,7 @@ from core.inference.tool_loop_controller import (
)
from core.inference.tool_stream_exec import (
TOOL_HEARTBEAT_INTERVAL_S,
+ accepts_kwarg,
accepts_output_callback,
stream_tool_execution,
)
@@ -729,6 +730,8 @@ async def stream_with_studio_tools(
) -> AsyncIterator[str]:
"""Stream a provider, execute requested Studio tools, continue to a final answer."""
conversation = [dict(message) for message in run.messages]
+ # Kept before the loop appends anything: this is the branch the request is on.
+ request_branch = list(run.messages)
remaining = policy.max_calls
unlimited = remaining >= 9999
session_id = run.session_id
@@ -1220,6 +1223,24 @@ async def stream_with_studio_tools(
"rag_scope": rag_scope,
"disable_sandbox": bypass_permissions,
}
+ # Provider loops share the local catalogue selector, so
+ # search_conversation is advertised here too once a thread has an archive
+ # and needs the same branch: the stored rows are the whole DAG, and Retry
+ # leaves the replaced response in them.
+ if accepts_kwarg(execute_tool, "conversation_branch"):
+ kwargs["conversation_branch"] = request_branch
+ # And a budget, so the tool's clamp is not skipped. Studio cannot measure
+ # an external model's window, and a custom OpenAI-compatible endpoint can
+ # be a small local server, so a model-chosen 8 chunks is roughly 4K tokens
+ # replayed on every later call. Unmeasurable means one recall's worth.
+ if accepts_kwarg(execute_tool, "conversation_budget_tokens"):
+ try:
+ from core.rag import config as rag_config
+ kwargs["conversation_budget_tokens"] = max(
+ 1, int(rag_config.CHUNK_TOKENS)
+ ) * max(1, int(rag_config.CONVERSATION_ARCHIVE_TOP_K))
+ except Exception:
+ pass
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = output_callback
return execute_tool(call.tool_name, call.arguments, **kwargs)
diff --git a/studio/backend/core/inference/tool_call_parser.py b/studio/backend/core/inference/tool_call_parser.py
index cf2f2d5b250..a00b1e1891f 100644
--- a/studio/backend/core/inference/tool_call_parser.py
+++ b/studio/backend/core/inference/tool_call_parser.py
@@ -158,6 +158,10 @@ BUDGET_EXHAUSTED_NUDGE = (
# The exact-args dup guard misses paraphrased re-searches, so also cap KB searches per turn.
RAG_MAX_SEARCHES_PER_TURN = 3
+# Both retrieval tools share that cap. Their top-K passages land in the current
+# exchange, which the rolling window protects and cannot evict, so an uncapped search
+# only ends the turn in a context-length error. Here so both tool loops agree on it.
+RAG_SEARCH_TOOLS = frozenset({"search_knowledge_base", "search_conversation"})
RAG_SEARCH_CAP_NUDGE = (
"You have already searched the knowledge base several times this turn. "
"Do not search again. Answer the question using the passages already "
diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.py
index 041f7cb5a55..58cd560d48c 100644
--- a/studio/backend/core/inference/tool_stream_exec.py
+++ b/studio/backend/core/inference/tool_stream_exec.py
@@ -32,22 +32,26 @@ from loggers import get_logger
logger = get_logger(__name__)
-def accepts_output_callback(func: Callable[..., str]) -> bool:
- """Whether an injectable ``execute_tool`` supports ``output_callback``.
+def accepts_kwarg(func: Callable[..., str], name: str) -> bool:
+ """Whether an injectable ``execute_tool`` supports the keyword ``name``.
``execute_tool`` is replaceable (tests inject fakes / the pre-PR signature),
- so forward the kwarg only when the callable declares it or takes ``**kwargs``
+ so forward a kwarg only when the callable declares it or takes ``**kwargs``
(passing it unconditionally would ``TypeError`` on an old signature).
"""
try:
params = inspect.signature(func).parameters
except (TypeError, ValueError):
return False
- if "output_callback" in params:
+ if name in params:
return True
return any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
+def accepts_output_callback(func: Callable[..., str]) -> bool:
+ return accepts_kwarg(func, "output_callback")
+
+
# Cadence of heartbeat events while a tool blocks with no output. Well under
# common proxy idle caps (Cloudflare ~100 s, nginx default 60 s).
TOOL_HEARTBEAT_INTERVAL_S = 10.0
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 2ed5bc96933..0f9f6234d5f 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -4530,7 +4530,9 @@ def _render_html_reaches_network(arguments: dict) -> bool:
# Tools that are read-only regardless of their arguments, so auto mode never has
# to pause them and their safety needs no argument scan. render_html is handled
# separately above because a networked canvas does need approval.
-_ALWAYS_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base"})
+# search_conversation only reads this chat's own past turns, so auto mode would otherwise
+# prompt for approval on every call.
+_ALWAYS_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base", "search_conversation"})
def is_always_safe_tool(name: str) -> bool:
@@ -9772,6 +9774,33 @@ SEARCH_KNOWLEDGE_BASE_TOOL = {
},
}
+SEARCH_CONVERSATION_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "search_conversation",
+ "description": (
+ "Search earlier turns of THIS conversation that were removed from your "
+ "context when it grew too long. Use it whenever the user refers to something "
+ "discussed earlier that you cannot see, instead of saying you have no record "
+ "of it."
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Natural-language search query.",
+ },
+ "top_k": {
+ "type": "integer",
+ "description": "Max earlier turns to return.",
+ },
+ },
+ "required": ["query"],
+ },
+ },
+}
+
ALL_TOOLS = [
WEB_SEARCH_TOOL,
PYTHON_TOOL,
@@ -9779,6 +9808,7 @@ ALL_TOOLS = [
EDIT_FILE_TOOL,
RENDER_HTML_TOOL,
SEARCH_KNOWLEDGE_BASE_TOOL,
+ SEARCH_CONVERSATION_TOOL,
]
@@ -9974,6 +10004,9 @@ def execute_tool(
disable_sandbox: bool = False,
output_callback = None,
website_policy: dict | None = None,
+ conversation_branch: list[dict] | None = None,
+ conversation_budget_tokens: int | None = None,
+ conversation_token_counter = None,
) -> str:
"""Execute a tool by name with the given arguments; returns a string.
@@ -10001,6 +10034,21 @@ def execute_tool(
effective_timeout,
cancel_event,
)
+ if name == "search_conversation":
+ # Scoped by thread id alone: the archive is this chat's own evicted turns, so it
+ # works with or without a document rag_scope.
+ return _search_knowledge_base_with_budget(
+ arguments,
+ {
+ "thread_id": thread_id,
+ "branch_messages": conversation_branch,
+ "budget_tokens": conversation_budget_tokens,
+ "token_counter": conversation_token_counter,
+ },
+ effective_timeout,
+ cancel_event,
+ search_fn = _search_conversation,
+ )
if name == "render_html":
return _render_html_result(arguments)
if name.startswith(MCP_TOOL_PREFIX):
@@ -10140,12 +10188,159 @@ def _search_knowledge_base(arguments: dict, rag_scope: dict | None) -> str:
return text
+# Ceiling for a model-supplied top_k. Small on purpose: this returns whole archived turns
+# into a protected exchange the rolling window cannot trim.
+_MAX_CONVERSATION_SEARCH_TOP_K = 8
+
+
+def _search_conversation(arguments: dict, rag_scope: dict | None) -> str:
+ """Search this thread's archived turns. ``rag_scope`` carries only the thread id here;
+ the model supplies ``query``/``top_k``."""
+ scope = rag_scope or {}
+ thread_id = scope.get("thread_id")
+ query = (arguments or {}).get("query", "")
+ if not query or not str(query).strip():
+ return "Error: query is empty."
+ if not thread_id:
+ return "There is no earlier conversation to search."
+ try:
+ from core.rag import conversation_archive
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Conversation archive unavailable: %s", exc)
+ return "Searching earlier conversation is unavailable on this server."
+ if not conversation_archive.enabled():
+ return "Searching earlier conversation is unavailable on this server."
+
+ # Clamped, not trusted: top_k comes from the model, and a negative value reaches a
+ # Python slice as out[:-1], returning nearly the whole candidate pool as a ~30k-token
+ # tool result that the protected current exchange cannot evict.
+ requested = _opt_int((arguments or {}).get("top_k"))
+ # None, not the ceiling: an omitted top_k must fall through to the configured recall
+ # default. Defaulting to the maximum returned eight chunks into that same protected
+ # exchange, enough to fail the next pass on a 4K chat.
+ top_k = (
+ None if requested is None else max(1, min(_MAX_CONVERSATION_SEARCH_TOP_K, int(requested)))
+ )
+ # Then against the room actually left: the fixed cap bounds what the model may ask
+ # for, not what fits. Eight chunks is roughly 4,000 tokens once wrapped, so on a 4K
+ # chat overshooting here is a context-length error no later preflight can recover.
+ budget = scope.get("budget_tokens")
+ if budget is not None:
+ default_k = 1
+ try:
+ from core.rag import config as rag_config
+ affordable = max(0, int(budget)) // max(1, int(rag_config.CHUNK_TOKENS))
+ default_k = max(1, int(rag_config.CONVERSATION_ARCHIVE_TOP_K))
+ except Exception:
+ affordable = 0
+ if affordable <= 0:
+ return "There is no room left in this context to search earlier conversation."
+ # An omitted top_k still means the configured default; room is a cap on it, not a
+ # target. Taking the room itself asked a 128K chat for 200 passages, past both the
+ # default and the ceiling the model's own value is held to.
+ top_k = (
+ min(default_k, _MAX_CONVERSATION_SEARCH_TOP_K, affordable)
+ if top_k is None
+ else max(1, min(top_k, affordable))
+ )
+
+ # The branch this request is on, so a response replaced by Retry cannot be searched
+ # back out of the archive. Absent callers fall back to the whole stored thread.
+ def _recall(k):
+ return conversation_archive.recall(
+ str(thread_id),
+ str(query),
+ top_k = k,
+ branch_messages = scope.get("branch_messages"),
+ )
+
+ found = _recall(top_k)
+ if not found:
+ return "No earlier turns of this conversation matched that query."
+
+ # Then against what the result actually costs. CHUNK_TOKENS is what the chunker AIMS
+ # at, not what a chunk weighs: chunks overlap, the chunker's tokenizer is not the
+ # model's, and the rendered block adds markup, source metadata and the tool framing
+ # around it. Measured on a 500-token budget: one chunk came back as 1,256 estimated
+ # tokens. So the count is halved until the rendered result fits, the same backoff the
+ # forced recall uses, and a single chunk that still does not fit is refused rather
+ # than appended to an exchange the window is not allowed to evict.
+ if budget is not None:
+ counter = scope.get("token_counter")
+ attempt = max(1, int(top_k or 1))
+ while True:
+ rendered = _rendered_conversation_search(found)
+ if _conversation_search_cost(rendered, counter) <= int(budget):
+ return rendered
+ if attempt <= 1:
+ return "There is no room left in this context to search earlier conversation."
+ attempt = max(1, attempt // 2)
+ found = _recall(attempt)
+ if not found:
+ return "No earlier turns of this conversation matched that query."
+ return _rendered_conversation_search(found)
+
+
+# What a `tool` message costs beyond its own text: the role, the call id and whatever the
+# template wraps them in. Small, fixed, and left out entirely before, which is the wrong
+# direction on a check whose whole job is to refuse a result that will not fit.
+_TOOL_MESSAGE_FRAMING_TOKENS = 8
+
+
+def _conversation_search_cost(text: str, counter = None) -> int:
+ """What admitting this result really costs, exactly when the caller has a tokenizer.
+
+ The estimate below is pessimistic for CJK and emoji but still optimistic for ASCII
+ that tokenises densely -- source code, minified JSON, hashes, command output all run
+ nearer two or three characters per token than four -- so a result could be admitted at
+ well under its real cost and then land in the current tool exchange, which the window
+ is not allowed to evict. A tokenizer-backed caller passes its own counter, and the
+ GGUF path is one, so the check that already computes the budget exactly can now spend
+ it exactly too.
+ """
+ if counter is not None:
+ try:
+ return int(counter(text)) + _TOOL_MESSAGE_FRAMING_TOKENS
+ except Exception:
+ logger.debug("conversation search: exact result count failed", exc_info = True)
+ return _conversation_search_tokens(text) + _TOOL_MESSAGE_FRAMING_TOKENS
+
+
+def _conversation_search_tokens(text: str) -> int:
+ """A deliberately pessimistic size for a search result, in tokens.
+
+ The shared estimator charges four characters per token, which is about right for
+ English and badly wrong for text that tokenises densely: CJK and emoji run closer to
+ one token per character, so a result could be accepted at a quarter of its real cost
+ and then land in the current tool exchange, which the window cannot evict. No exact
+ counter is reachable from here, the provider loop having no tokenizer at all, so
+ non-ASCII characters are charged one token each and the rest at the usual rate.
+ """
+ dense = sum(1 for char in text if ord(char) > 127)
+ return max(1, dense + (len(text) - dense) // 4)
+
+
+def _rendered_conversation_search(found) -> str:
+ """The tool result exactly as the model would receive it."""
+ text, sources = found
+ if sources:
+ import json as _json
+ return text + RAG_SOURCES_SENTINEL + _json.dumps(sources, ensure_ascii = False)
+ return text
+
+
def _search_knowledge_base_with_budget(
arguments: dict,
rag_scope: dict | None,
timeout: int | None,
cancel_event = None,
+ search_fn = None,
) -> str:
+ """Admission-controlled RAG search.
+
+ ``search_fn`` swaps in a different search over the same capacity-of-one slot, so
+ archive lookups queue behind document lookups instead of racing for the embedder."""
+ search_fn = search_fn or _search_knowledge_base
if cancel_event is not None and cancel_event.is_set():
return "Error: knowledge base search cancelled."
deadline = time.monotonic() + timeout if timeout is not None else None
@@ -10179,7 +10374,7 @@ def _search_knowledge_base_with_budget(
if timeout is None and cancel_event is None:
try:
- return _search_knowledge_base(arguments, rag_scope)
+ return search_fn(arguments, rag_scope)
finally:
release_slot()
@@ -10187,7 +10382,7 @@ def _search_knowledge_base_with_budget(
def search() -> None:
try:
- result.put((True, _search_knowledge_base(arguments, rag_scope)))
+ result.put((True, search_fn(arguments, rag_scope)))
except BaseException as exc:
result.put((False, exc))
finally:
@@ -10330,6 +10525,146 @@ def _last_user_text(conversation: list[dict]) -> str:
return ""
+def build_synthetic_search_exchange(
+ *,
+ tool_name: str,
+ call_prefix: str,
+ status_label: str,
+ query: str,
+ text: str,
+ sources: list[dict],
+) -> dict:
+ """Render a retrieval the loop never asked for as a normal tool exchange.
+
+ Returns ``{"events": [...], "messages": [...]}``: the messages are what the model
+ reads, the events what the UI draws, so a forced retrieval shows up as an ordinary
+ tool card with working citations instead of appearing from nowhere.
+ """
+ import json as _json
+ import uuid as _uuid
+
+ call_id = call_prefix + _uuid.uuid4().hex[:12]
+ args = {"query": query}
+ full_result = text + RAG_SOURCES_SENTINEL + _json.dumps(sources, ensure_ascii = False)
+ events = [
+ {"type": "status", "text": f"{status_label}: {query[:60]}"},
+ {
+ "type": "tool_start",
+ "tool_name": tool_name,
+ "tool_call_id": call_id,
+ "arguments": args,
+ },
+ {
+ "type": "tool_end",
+ "tool_name": tool_name,
+ "tool_call_id": call_id,
+ "result": full_result,
+ },
+ {"type": "status", "text": ""},
+ ]
+ messages = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": tool_name,
+ "arguments": _json.dumps(args, ensure_ascii = False),
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "name": tool_name,
+ "tool_call_id": call_id,
+ "content": text,
+ },
+ ]
+ return {"events": events, "messages": messages}
+
+
+_RECALL_BLOCK = (
+ "<recalled_conversation>\n"
+ "This conversation was compacted and earlier turns were removed from your context. "
+ "These are the most relevant earlier turns, retrieved verbatim from this chat.\n"
+ "{text}\n"
+ "</recalled_conversation>\n\n"
+)
+
+
+def build_conversation_recall(
+ conversation: list[dict],
+ thread_id: str | None,
+ *,
+ style: str = "tool",
+ top_k: int | None = None,
+ branch_messages: list[dict] | None = None,
+) -> dict | None:
+ """Retrieve the archived turns most relevant to the latest user message.
+
+ Deliberately NOT gated on ``rag_scope``: compaction happens whether or not document
+ RAG is on, and these turns are the conversation's own, not uploaded files.
+
+ Forcing this one retrieval is the whole feature. Given only a search tool, a 35B on
+ MRCR v2 declined on 56% of rows, scoring 0.099 when it skipped against 0.461 when it
+ searched; forcing the lookup on the evicting turn took tool-only 0.258 to 0.604, and
+ the model then called the tool on 0% of rows, so it costs nothing on the common path.
+
+ ``style="tool"`` renders a tool exchange, for the tool loop which already carries a
+ tools array. ``style="inline"`` prefixes the latest user message instead, for the
+ plain path: forging tool_calls without a tools array breaks strict templates.
+ """
+ if not thread_id:
+ return None
+ try:
+ from core.rag import conversation_archive
+ except Exception:
+ return None
+ if not conversation_archive.enabled():
+ return None
+
+ # The BRANCH's latest user turn, not the loop conversation's: a later tool-loop
+ # iteration can end with an internal user-role re-prompt (the plan-without-action
+ # nudge), and searching for that controller instruction defeats the forced retrieval.
+ # branch_messages is what the client sent, so its last user turn is the real request.
+ query = _last_user_text(branch_messages or conversation) or _last_user_text(conversation)
+ if not query:
+ return None
+ try:
+ found = conversation_archive.recall(
+ thread_id, query, top_k = top_k, branch_messages = branch_messages
+ )
+ except Exception:
+ logger.warning("Conversation recall failed", exc_info = True)
+ return None
+ if not found:
+ return None
+ text, sources = found
+
+ if style == "inline":
+ return {
+ "events": [],
+ "messages": [],
+ "prefix": _RECALL_BLOCK.format(text = text),
+ "sources": len(sources),
+ }
+ built = build_synthetic_search_exchange(
+ tool_name = "search_conversation",
+ call_prefix = "conv_recall_",
+ status_label = "Recalling earlier conversation",
+ query = query,
+ text = text,
+ sources = sources,
+ )
+ built["sources"] = len(sources)
+ logger.info("Conversation recall: %d earlier passage(s) for %r", len(sources), query[:80])
+ return built
+
+
def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
"""Pre-retrieve the latest user turn; if a hit clears the cosine floor return
``{"events": [...], "messages": [...]}`` to splice into the loop, else ``None``.
@@ -10431,52 +10766,16 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
if text is None:
return None
- import json as _json
- import uuid as _uuid
-
- call_id = "rag_auto_" + _uuid.uuid4().hex[:12]
- args = {"query": query}
- full_result = text + RAG_SOURCES_SENTINEL + _json.dumps(sources, ensure_ascii = False)
- events = [
- {"type": "status", "text": f"Searching documents: {query[:60]}"},
- {
- "type": "tool_start",
- "tool_name": "search_knowledge_base",
- "tool_call_id": call_id,
- "arguments": args,
- },
- {
- "type": "tool_end",
- "tool_name": "search_knowledge_base",
- "tool_call_id": call_id,
- "result": full_result,
- },
- {"type": "status", "text": ""},
- ]
- messages = [
- {
- "role": "assistant",
- "content": "",
- "tool_calls": [
- {
- "id": call_id,
- "type": "function",
- "function": {
- "name": "search_knowledge_base",
- "arguments": _json.dumps(args, ensure_ascii = False),
- },
- }
- ],
- },
- {
- "role": "tool",
- "name": "search_knowledge_base",
- "tool_call_id": call_id,
- "content": text,
- },
- ]
+ built = build_synthetic_search_exchange(
+ tool_name = "search_knowledge_base",
+ call_prefix = "rag_auto_",
+ status_label = "Searching documents",
+ query = query,
+ text = text,
+ sources = sources,
+ )
logger.info("RAG auto-inject: %d passage(s) for %r", len(sources), query[:80])
- return {"events": events, "messages": messages}
+ return built
_MAX_PAGE_CHARS = 16000 # cap fetched page text (after HTML-to-MD conversion)
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index cd713c1c047..56769e4936c 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -24,6 +24,24 @@ RRF_K = int(os.environ.get("RAG_RRF_K", "60"))
THREAD_WHOLE_DOC = os.environ.get("RAG_THREAD_WHOLE_DOC", "1") == "1"
WHOLE_DOC_MAX_TOKENS = int(os.environ.get("RAG_WHOLE_DOC_MAX_TOKENS", "6000"))
+# Conversation archive: turns evicted by the rolling context window go to a per-thread
+# searchable scope and the relevant ones are recalled on the turn that evicted them. Off,
+# evicted turns are simply dropped again, and the recall reserve is not taken. Only applies
+# once the window evicts, which is itself opt-in per request via
+# context_overflow="truncate_oldest".
+#
+# It does NOT turn the rolling window back into what it was before: the compaction headroom
+# and the sticky boundary belong to the window, not to the archive, and have their own knob
+# (ROLLING_COMPACTION_HEADROOM_RATIO). Gating them here instead would make a host without
+# sqlite-vec silently compact differently.
+CONVERSATION_ARCHIVE = os.environ.get("RAG_CONVERSATION_ARCHIVE", "1") == "1"
+CONVERSATION_ARCHIVE_TOP_K = int(os.environ.get("RAG_CONVERSATION_ARCHIVE_TOP_K", "4"))
+# Room held back during the fit for the turns recalled straight after it. Sized to
+# CONVERSATION_ARCHIVE_TOP_K * CHUNK_TOKENS with slack for the wrapper text.
+CONVERSATION_RECALL_RESERVE_TOKENS = int(
+ os.environ.get("RAG_CONVERSATION_RECALL_RESERVE_TOKENS", "2048")
+)
+
UPLOAD_EXTS = {".pdf", ".txt", ".md", ".markdown", ".docx", ".html", ".htm"}
# Reject uploads larger than this, so one pathological file can't drive unbounded parse
# + vision work at ingest. 0 disables the cap. Default 200 MB.
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.py
new file mode 100644
index 00000000000..7ade85fad3a
--- /dev/null
+++ b/studio/backend/core/rag/conversation_archive.py
@@ -0,0 +1,1190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep the turns the rolling context window evicts, and hand them back on request.
+
+Each evicted turn is indexed into a per-thread RAG scope, reusing the store, chunker,
+embedder and hybrid retrieval that back attached documents. The stored transcript is
+never touched; this is only a search index over turns the projection cannot carry.
+
+Two properties are load-bearing and easy to break:
+
+* The archive is CUMULATIVE. Nothing is cleared or re-scoped per compaction, so the fifth
+ compaction can still find what the first evicted. On MRCR v2 over 11 compaction events,
+ cumulative scored 0.450 against 0.058 for latest-compaction-only.
+* Nothing here may break a chat. Every entry point no-ops on failure, because the
+ alternative to a degraded archive is a working conversation, not an error.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import json
+import re
+from typing import Optional
+
+from storage import rag_db
+
+from . import config, embeddings, retrieval, store, tool
+from .chunking import chunk_pages
+from .parsers import Page
+
+logger = logging.getLogger(__name__)
+
+# Instructions, not conversation. An archived system prompt could come back quoted as an
+# "earlier turn" and read as user-authored text.
+_SKIP_ROLES = frozenset({"system", "developer"})
+
+# Tool call ids this feature and the RAG auto-inject generate. Their results are retrieved
+# passages, so archiving them would feed retrieved text back into its own index.
+_INJECTED_CALL_PREFIXES = ("rag_auto_", "conv_recall_")
+
+# What render_turn appends where it cut something short. Named because the branch check
+# has to recognise it: a probe carrying it can only be a PREFIX of the live text.
+_TRUNCATION_MARKER = " ..."
+_MAX_TOOL_RESULT_CHARS = 4000
+# Tool arguments are usually short; the cap only stops a pathological blob dominating.
+_MAX_TOOL_ARGS_CHARS = 1000
+# Over-fetch multiple ahead of the live-branch filter. Filtering after a k-sized fetch
+# lets stale turns from an abandoned branch fill the result and starve live matches just
+# below, so recall returns nothing while the answer is in the archive.
+_BRANCH_FILTER_OVERFETCH = 4
+# One over-fetch is not always enough: rewinding a long compacted continuation leaves an
+# abandoned branch big enough to fill any fixed candidate window, so widen and re-ask.
+# Bounded because this is a chat request, not a crawl.
+_BRANCH_FILTER_MAX_CANDIDATES = 256
+
+
+def _text_of(content, *, include_tool_calls: bool = False) -> str:
+ """Flatten OpenAI message content to plain text, dropping non-text parts.
+
+ ``include_tool_calls`` also flattens assistant-ui's persisted ``tool-call`` parts,
+ whose call lives in structured ``toolName``/``args``/``result`` fields. The branch
+ check needs them, or a transcript can never contain the lines ``render_turn`` wrote
+ and every archived tool turn looks rolled back.
+ """
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts = []
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ if part.get("type") in ("text", "input_text") or "text" in part:
+ parts.append(str(part.get("text") or ""))
+ elif include_tool_calls and part.get("type") == "tool-call":
+ for value in (part.get("toolName"), part.get("args"), part.get("result")):
+ if value in (None, "", {}, []):
+ continue
+ parts.append(value if isinstance(value, str) else json.dumps(value))
+ return "\n".join(p for p in parts if p)
+ return "" if content is None else str(content)
+
+
+def _probe_text(message: dict) -> str:
+ """One message flattened in the ORDER ``render_turn`` writes it.
+
+ The branch check matches in order, so both must agree on it. Bucketing the whole
+ message as call, text, result only holds while the text came BEFORE the call. A
+ persisted row whose tool call is followed by the model's final answer -- the ordinary
+ agent turn -- renders as call, result, answer, and the buckets put the answer in the
+ middle: `_scan_probes` advanced its cursor past the answer to find the result and then
+ could not find the answer again, so an unchanged evicted tool exchange was classified
+ off-branch and no query could return it. Measured end to end: recall came back with
+ the user's question alone and the document holding the answer was filtered out.
+
+ So the buckets are flushed the way the replay serializer flushes its pending calls,
+ when text arrives after a call. Text before a call still rides ahead of it, which is
+ the shape it is written in.
+ """
+ chunks: list[str] = []
+ calls: list[str] = []
+ texts: list[str] = []
+ results: list[str] = []
+
+ def flush() -> None:
+ chunks.extend(part for part in calls + texts + results if part)
+ calls.clear()
+ texts.clear()
+ results.clear()
+
+ def rendered(value) -> list[str]:
+ """A structured value as the strings a wire-format copy of it could look like.
+
+ The store keeps tool arguments as an object; the archived copy is the model's raw
+ string, with its own spacing. This is a haystack, so offering both is free.
+ """
+ if isinstance(value, str):
+ return [value]
+ try:
+ spaced = json.dumps(value, ensure_ascii = False)
+ compact = json.dumps(value, ensure_ascii = False, separators = (",", ":"))
+ except Exception:
+ return [str(value)]
+ return [spaced] if spaced == compact else [spaced, compact]
+
+ content = message.get("content")
+ if isinstance(content, list):
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ if part.get("type") == "tool-call":
+ for value in (part.get("toolName"), part.get("args")):
+ if value not in (None, "", {}, []):
+ calls.extend(rendered(value))
+ result = part.get("result")
+ if result not in (None, "", {}, []):
+ results.extend(rendered(result))
+ elif part.get("type") in ("text", "input_text") or "text" in part:
+ if calls:
+ flush()
+ texts.append(str(part.get("text") or ""))
+ else:
+ texts.append(_text_of(content))
+ for call in message.get("tool_calls") or []:
+ function = (call or {}).get("function") or {}
+ for value in (function.get("name"), function.get("arguments")):
+ if value:
+ calls.append(str(value))
+ flush()
+ return "\n".join(chunks)
+
+
+def _is_injected(message: dict) -> bool:
+ call_id = str(message.get("tool_call_id") or "")
+ if call_id.startswith(_INJECTED_CALL_PREFIXES):
+ return True
+ for call in message.get("tool_calls") or []:
+ if str((call or {}).get("id") or "").startswith(_INJECTED_CALL_PREFIXES):
+ return True
+ return False
+
+
+def render_turn(group: list[dict]) -> str:
+ """Render one evicted turn group as the text that gets indexed and quoted back.
+
+ Both sides go in one document on purpose, so retrieval returns the question with its
+ answer rather than a floating fragment.
+ """
+ lines: list[str] = []
+ for message in group:
+ role = str(message.get("role") or "")
+ if role in _SKIP_ROLES:
+ continue
+ text = _text_of(message.get("content")).strip()
+ calls = message.get("tool_calls") or []
+ if calls:
+ # The arguments, bounded, not just the name: the searchable substance is the
+ # command or query that ran, and "assistant called terminal" cannot answer
+ # "what did you run earlier?". Assistant text on the same message likewise.
+ for call in calls:
+ function = (call or {}).get("function") or {}
+ name = str(function.get("name") or "tool")
+ arguments = str(function.get("arguments") or "").strip()
+ if len(arguments) > _MAX_TOOL_ARGS_CHARS:
+ arguments = arguments[:_MAX_TOOL_ARGS_CHARS] + _TRUNCATION_MARKER
+ lines.append(
+ f"assistant called {name}: {arguments}"
+ if arguments
+ else f"assistant called {name}"
+ )
+ if text:
+ lines.append(f"{role or 'assistant'}: {text}")
+ continue
+ if not text:
+ continue
+ if role == "tool":
+ # Tool results are huge and the least useful thing to quote back verbatim:
+ # keep enough to be searchable without bloating the index.
+ if len(text) > _MAX_TOOL_RESULT_CHARS:
+ text = text[:_MAX_TOOL_RESULT_CHARS] + _TRUNCATION_MARKER
+ lines.append(f"tool result: {text}")
+ else:
+ lines.append(f"{role or 'message'}: {text}")
+ return "\n".join(lines).strip()
+
+
+def _archivable(group: list[dict]) -> list[dict]:
+ """The part of an evicted turn worth archiving, or an empty list.
+
+ Our own injections come out, the rest stays. Rejecting the whole group threw away real
+ answers: ``group_turns`` keeps a tool call, its result and the following reply in ONE
+ group, so an injection on that turn took the model's answer down with it, leaving the
+ question archived and the answer not -- on compaction turns, which are the point here.
+ """
+ if any(str(message.get("role") or "") in _SKIP_ROLES for message in group):
+ return []
+ kept = [message for message in group if not _is_injected(message)]
+ return _without_retrieval(kept)
+
+
+def _retrieval_names() -> frozenset:
+ """The tool names whose results are retrieved passages, not conversation."""
+ try:
+ from core.inference.tool_call_parser import RAG_SEARCH_TOOLS
+ return frozenset(RAG_SEARCH_TOOLS)
+ except Exception: # noqa: BLE001 -- fall back to the name this module owns
+ return frozenset({"search_conversation", "search_knowledge_base"})
+
+
+def _without_retrieval(group: list[dict]) -> list[dict]:
+ """The group with retrieval calls and their results removed.
+
+ `_is_injected` recognises the ids this feature and the RAG auto-inject generate, but a
+ search the MODEL asked for gets an ordinary `call_N` id from the parser, so both the
+ call and its retrieved passage were archived as new conversation. Measured: a second
+ search then indexed the first one's output inside its own, one nesting level per
+ distinct search, each copy competing for the four recall slots.
+
+ Removed by NAME, and only the retrieval parts: an assistant message can carry a
+ retrieval call alongside an ordinary one, and the reply that follows a search is real
+ conversation that must still be archived.
+ """
+ names = _retrieval_names()
+ dropped_ids = set()
+ out = []
+ for message in group:
+ calls = message.get("tool_calls") or []
+ if calls:
+ keep_calls = []
+ for call in calls:
+ function = (call or {}).get("function") or {}
+ if str(function.get("name") or "") in names:
+ dropped_ids.add(str((call or {}).get("id") or ""))
+ else:
+ keep_calls.append(call)
+ if len(keep_calls) != len(calls):
+ if not keep_calls and not _text_of(message.get("content")).strip():
+ # Nothing left of it but the search.
+ continue
+ message = {**message, "tool_calls": keep_calls}
+ if str(message.get("role") or "") == "tool":
+ if str(message.get("tool_call_id") or "") in dropped_ids:
+ continue
+ out.append(message)
+ return out
+
+
+def enabled() -> bool:
+ """Whether the archive can actually run here.
+
+ ``rag_available()`` and not ``RAG_AVAILABLE``: the flag only records that
+ ``import sqlite_vec`` worked, while the vec0 native library is a separate file a venv
+ can be missing (the common macOS case). Trusting it there is worse than no feature at
+ all: the fit still reserves room, then write and recall both fail, so the user pays
+ extra eviction for content that never arrives.
+ """
+ return bool(config.CONVERSATION_ARCHIVE) and bool(rag_db.rag_available())
+
+
+def can_archive(thread_id: Optional[str]) -> bool:
+ """Whether this thread's evicted turns can be archived at all.
+
+ A temporary (incognito) chat is never written to studio.db, yet the frontend still
+ sends its thread_id and the request carries no incognito flag, so saved messages are
+ the only signal. Archiving one would persist exactly what the user asked not to keep,
+ into a scope with no thread row that no deletion flow could reach. An API client that
+ sends a thread_id without persisting anything is excluded for the same reason.
+
+ Also gates the fit's recall reserve: a thread that cannot be archived cannot be
+ recalled, so reserving there would evict history for content that cannot arrive.
+ """
+ if not thread_id or not enabled():
+ return False
+ try:
+ from storage import studio_db
+ return bool(studio_db.chat_thread_has_messages(thread_id))
+ except Exception:
+ return False
+
+
+def archive_turns(thread_id: str, evicted: list[dict]) -> int:
+ """Index the evicted turns for ``thread_id``. Returns how many were newly written.
+
+ Idempotent by content hash: the same turns are evicted again on every later request
+ in the session, so re-archiving has to be free. After the first write each repeat
+ costs one indexed SELECT and writes nothing.
+ """
+ if not thread_id or not evicted or not enabled():
+ return 0
+ # Incognito and API-only threads are excluded; see can_archive. By the time a chat is
+ # long enough to compact, its earlier turns are always persisted.
+ if not can_archive(thread_id):
+ logger.debug("conversation_archive.skipped_unpersisted_thread thread_id=%s", thread_id)
+ return 0
+
+ # The evictor's own grouper, so an archived unit is exactly the unit the window drops.
+ # Imported lazily because the inference layer imports this module.
+ from core.inference.context_window import group_turns
+
+ # Each entry is the archivable messages AND the span of the turn they came from. The
+ # two differ whenever `_archivable` drops something: an assistant batch that called
+ # `search_conversation` alongside an ordinary tool archives three messages while the
+ # live transcript still holds four, and `archive_messages` bounds the branch check's
+ # run. Bounded by the shorter figure, a perfectly valid ordinary-tool exchange and its
+ # answer were rejected as off-branch and could never be recalled.
+ groups = [
+ (archivable, len(group))
+ for group, archivable in ((group, _archivable(group)) for group in group_turns(evicted))
+ if archivable
+ ]
+ if not groups:
+ return 0
+
+ model = config.effective_embedding_model()
+ scope = store.conversation_archive_scope(thread_id)
+ written = 0
+ conn = None
+ try:
+ count = embeddings.token_counter(model)
+ conn = rag_db.get_connection()
+ # What the query side will ask for. Only a prediction until the encode reports
+ # what it actually used, so the authoritative check happens under the write lock.
+ expected_identity = embeddings.embedding_identity(model)
+
+ # Chunk everything first, then embed it in ONE pass. Per group, a first
+ # compaction of a long chat ran dozens of one-item embedding jobs back to back
+ # before the reply could start, and both backends serialise them.
+ pending = []
+ for group, span in groups:
+ text = render_turn(group)
+ if not text:
+ continue
+ digest = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
+ if _archived_under(conn, scope, digest, expected_identity):
+ _widen_span(conn, scope, digest, span)
+ continue
+ chunks = chunk_pages(
+ [Page(text = text, page_number = None, char_count = len(text))],
+ max_tokens = config.CHUNK_TOKENS,
+ overlap = config.CHUNK_OVERLAP,
+ count = count,
+ )
+ if chunks:
+ pending.append((group, span, digest, chunks))
+ if not pending:
+ return 0
+
+ # Identity from the encode that produced these vectors: a concurrent embedder
+ # swap would otherwise label them with a space they were never in.
+ vectors, identity = embeddings.encode_with_identity(
+ [chunk.text for entry in pending for chunk in entry[3]],
+ model_name = model,
+ normalize = True,
+ )
+ offset = 0
+ for group, span, digest, chunks in pending:
+ group_vectors = vectors[offset : offset + len(chunks)]
+ offset += len(chunks)
+ roles = " + ".join(
+ dict.fromkeys(str(message.get("role") or "message") for message in group)
+ )
+ # commit=False, then commit once the chunks are in: committing the document
+ # first leaves an empty row marked "completed" if the chunk write fails, and
+ # `document_by_hash` skips that turn forever after without retrying.
+ # Re-checked here under a write lock, not only before the embedding pass: two
+ # generations compacting one thread both clear that first check, and
+ # `(scope, sha256)` is a plain index, so both insert and the duplicate takes
+ # two of the few recall slots. Reproduced with two concurrent archive passes.
+ _write_lock = False
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ _write_lock = True
+ except Exception:
+ # Already in a transaction: the insert is still atomic with the re-check.
+ logger.debug("conversation_archive.no_write_lock", exc_info = True)
+ stale = _stale_document(conn, scope, digest, identity)
+ if stale is _ARCHIVED:
+ # Widened here too, not only on the pre-check. Both turns can arrive in
+ # ONE compaction: the pre-check clears both before either is written, the
+ # shorter is written first, and the longer then meets this re-check, so
+ # leaving without touching the span left the window at the shorter figure
+ # and the longer occurrence unsearchable. Two concurrent passes reach the
+ # same place. Rolled back first, since this is the duplicate path and the
+ # widen carries its own commit.
+ if _write_lock:
+ conn.rollback()
+ _widen_span(conn, scope, digest, span)
+ continue
+ if stale is not None:
+ # Same turn, vectors from an embedder the query side no longer asks for.
+ # Skipping it would leave the turn invisible to dense search forever, so
+ # the copy is replaced rather than deduplicated, as ingestion does.
+ store.delete_document(conn, stale, commit = False)
+ document_id = store.create_document(
+ conn,
+ scope = scope,
+ thread_id = thread_id,
+ filename = f"earlier turn ({roles})",
+ sha256 = digest,
+ status = "completed",
+ embedding_model = identity,
+ # The turn's real size in the TRANSCRIPT, so the branch check can bound
+ # its run exactly. Counting role labels only approximates it, since a
+ # pasted transcript writes lines that look exactly like the renderer's
+ # own, and counting the archived messages undercounts whenever
+ # `_archivable` dropped one.
+ archive_messages = span,
+ commit = False,
+ )
+ try:
+ store.add_chunks(conn, scope, document_id, chunks, group_vectors)
+ except Exception:
+ conn.rollback()
+ raise
+ conn.commit()
+ written += 1
+ if _INGEST_FAILED:
+ globals()["_INGEST_FAILED"] = False
+ except Exception:
+ # A chat that cannot archive still beats one that raises. Whatever was written
+ # before the failure stays searchable.
+ globals()["_INGEST_FAILED"] = True
+ logger.warning("conversation_archive.ingest_failed thread_id=%s", thread_id, exc_info = True)
+ finally:
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
+ # Cancellation is cooperative, and chunking plus embedding is the slowest stretch of
+ # this function. A delete landing in that window sweeps the archive scope BEFORE this
+ # commit puts rows back, stranding deleted content in a scope no later delete reaches.
+ # Re-checking after the commit converges either way: the delete route drops thread
+ # rows first and sweeps archives last, so an earlier sweep is caught here and a later
+ # one removes these rows itself.
+ if written and not can_archive(thread_id):
+ logger.info("conversation_archive.thread_deleted_mid_ingest thread_id=%s", thread_id)
+ delete_for_thread(thread_id)
+ return 0
+ return written
+
+
+# Set when an archive write fails, cleared by the next one that succeeds. Process-wide on
+# purpose: what fails here is the embedder or the store, not one thread.
+_INGEST_FAILED = False
+
+
+def degraded() -> bool:
+ """Whether the last archive attempt failed outright.
+
+ The window reserves recall room before any of this runs and ``archive_turns``
+ swallows its failures, so a machine whose embedder cannot start would pay the reserve
+ on every compaction for nothing. The caller checks this and stops reserving.
+ """
+ return _INGEST_FAILED
+
+
+# Returned by ``_stale_document`` for a turn that is already archived under vectors the
+# query side still accepts.
+_ARCHIVED = "archived"
+
+
+def _stale_document(conn, scope: str, digest: str, identity: str):
+ """The document id to replace, ``_ARCHIVED`` to skip, or None to write a new one.
+
+ Hash alone is not enough. Dense search only reads documents whose recorded embedder
+ matches the query's, so a turn archived under the previous model stays hashed-and-
+ skipped while being invisible to every paraphrased search. Ingestion re-indexes in
+ that case; so does this.
+ """
+ existing = store.document_by_hash(conn, scope, digest)
+ if existing is None:
+ return None
+ document = store.get_document(conn, existing)
+ recorded = (document or {}).get("embedding_model")
+ if config.embedding_identity_matches(recorded, identity):
+ return _ARCHIVED
+ return existing
+
+
+def _archived_under(conn, scope: str, digest: str, identity: str) -> bool:
+ """Cheap pre-check before the chunking and embedding pass."""
+ return _stale_document(conn, scope, digest, identity) is _ARCHIVED
+
+
+def _widen_span(conn, scope: str, digest: str, span: int) -> None:
+ """Grow a stored turn's window when the same text reappears over a LONGER span.
+
+ The digest is the rendered text, so two turns that read the same are one document,
+ but their transcript spans can differ: `_archivable` strips a retrieval call and its
+ result, so a three-message exchange and a four-message batch containing the same
+ exchange render identically. Archived in that order, the second is skipped and keeps
+ the first turn's span of three, and `_document_matches_one_run` then bounds its
+ four-message live run by three and rejects it as off-branch, so no query returns it.
+
+ Only ever UPWARDS. The window is a maximum, so a larger one still matches the shorter
+ turn, while narrowing it would break whichever turn was archived first.
+ """
+ try:
+ conn.execute(
+ "UPDATE documents SET archive_messages = ? "
+ "WHERE scope = ? AND sha256 = ? "
+ "AND (archive_messages IS NULL OR archive_messages < ?)",
+ (int(span), scope, digest, int(span)),
+ )
+ conn.commit()
+ except Exception:
+ logger.debug("conversation_archive.widen_span_failed", exc_info = True)
+
+
+def has_archive(thread_id: str) -> bool:
+ """Whether anything has ever been archived for this thread."""
+ if not thread_id or not enabled():
+ return False
+ conn = None
+ try:
+ conn = rag_db.get_connection()
+ row = conn.execute(
+ "SELECT 1 FROM documents WHERE scope=? LIMIT 1",
+ (store.conversation_archive_scope(thread_id),),
+ ).fetchone()
+ return row is not None
+ except Exception:
+ return False
+ finally:
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
+
+def _normalise(text: str) -> str:
+ """Probe text for comparison: trimmed at both ends, otherwise exactly as written.
+
+ Case IS the edit. Lowercasing left a turn corrected only in capitalisation matching
+ its archived copy, so `_document_matches_one_run` kept the pre-edit document live and
+ a recall could answer with it: measured, `Foo` after it was corrected to `foo`, still
+ validated. The two sides here are a stored render and the live text of the same
+ messages, so there is no spelling difference to be tolerant of, and nothing else
+ retires the stale copy -- the edit changes the digest, so it is written as a new
+ document and the branch filter is the only thing that could have dropped the old one.
+
+ `strip()` and not `rstrip()`, even though trimming each probe also discards leading
+ indentation. Keeping leading whitespace looks tighter and is worse: `render_turn`
+ strips the whole message, so a live turn beginning with a space or a newline then
+ starts its run at a non-zero offset and `_document_matches_one_run` retires it.
+ Measured, ` hello there` and a pasted block opening on a newline both went from
+ live to retired, which is a silent loss of recall on exactly the pasted code that
+ tends to matter.
+
+ Indentation-only edits are therefore still tolerated, in both directions: probes are
+ matched per line and as substrings, so leading whitespace never decides. Closing that
+ needs the probe splitter to carry offsets, which is a bigger change than this bug
+ warrants. Lexical search does its own tokenising and never reads this.
+ """
+ return (text or "").strip()
+
+
+def _live_transcript(thread_id: str) -> Optional[list[str]]:
+ """The thread's saved messages, one normalised string each, or None if it has none.
+
+ Keeps recall on the branch the user is on. Editing a message rewinds the thread, but
+ the archive is append-only and still holds the abandoned continuation's turns, so
+ without this a recall can pull back a turn that never happened on this branch.
+ Verified: after rewinding past a turn, querying its text still returned it.
+
+ None means the thread has no saved transcript (an API client passing a thread_id
+ without persisting), and the caller then does not filter: absence of evidence.
+ """
+ try:
+ from storage import studio_db
+ messages = studio_db.list_chat_messages(thread_id)
+ except Exception:
+ return None
+ if not messages:
+ return None
+ texts = [_normalise(_probe_text(message)) for message in messages]
+ return [text for text in texts if text] or None
+
+
+def branch_message_texts(
+ messages: Optional[list[dict]], roles: Optional[tuple[str, ...]] = None
+) -> Optional[list[str]]:
+ """The ACTIVE branch, one normalised string PER MESSAGE, from the request's own messages.
+
+ Per message rather than one blob, so the check stays inside the turn it is checking.
+ Flattened, a probe can be satisfied by any later message repeating the words: an
+ archived "Should I deploy? / No" whose answer was edited to "Yes" still matched
+ because an unrelated later turn said "No". Reproduced before the split.
+
+ Preferred over ``_live_transcript`` wherever available: the stored rows are the whole
+ message DAG, and retry/regenerate keep the replaced response as a sibling, so a
+ thread-wide blob can validate a turn that is not on this branch. The client sends
+ exactly one branch per request, and it is the same projection ``render_turn``
+ archived from, so the probe compares like with like.
+
+ ``roles`` narrows it to messages of those roles. The rolling window compares stored
+ ASSISTANT rows, and against every role a short abandoned reply ("Done") matches a live
+ user message that merely contains it ("not done yet").
+ """
+ if roles:
+ messages = [
+ message for message in (messages or []) if str(message.get("role") or "") in roles
+ ]
+ if not messages:
+ return None
+ texts = [_normalise(_probe_text(message)) for message in messages]
+ return [text for text in texts if text] or None
+
+
+def message_text(content) -> str:
+ """One stored message's content, normalised the way the branch check normalises it.
+
+ Exposed so the rolling window compares stored messages on exactly these terms rather
+ than inventing a second notion of "same text".
+ """
+ return _normalise(_probe_text({"content": content}))
+
+
+def content_on_branch(content, transcript: Optional[list[str]]) -> bool:
+ """Whether one stored message's text appears on the branch ``transcript`` describes.
+
+ Shared with the rolling window, which has recall's problem: the stored rows are the
+ whole DAG, so "the newest assistant turn" can belong to a sibling branch. Empty text
+ counts as on-branch, since nothing to compare is not evidence of another branch.
+ """
+ if not transcript:
+ return True
+ text = _normalise(_probe_text({"content": content}))
+ return not text or any(text in message for message in transcript)
+
+
+_ROLE_PREFIX = re.compile(
+ r"^(?:user|assistant|system|developer|tool result|message):\s*", re.IGNORECASE
+)
+# render_turn labels a tool call "assistant called <name>: <args>". The label is ours,
+# not the stored message's, so it comes off before the probe like any role prefix, or
+# every archived tool line misses and the turn looks rolled back. The name goes with it
+# when arguments follow; with none, the bare name is what the transcript has.
+_TOOL_CALL_PREFIX = re.compile(r"^assistant called (?:[^:\n]+:\s*)?", re.IGNORECASE)
+# The same label with the NAME captured, for the probe that has to keep it. Stripping the
+# label whole discarded which tool was called, so a retry that kept the arguments and
+# changed the tool (`terminal` to `python`) left the archived pre-edit turn matching.
+# `_probe_text` renders a live call as "<name> <arguments>", so the name is there to be
+# found; only our own "assistant called " wrapper and the colon are not.
+_TOOL_CALL_NAME = re.compile(r"^assistant called ([^:\n]+):\s*", re.IGNORECASE)
+# What may sit between two probes of the same message: nothing, or a label the probe had
+# stripped. A pasted transcript carries its own "user:" lines, so the gap is real there
+# and the turn is unedited. Any other text in that gap is content the archive never saw.
+_GAP_IS_LABEL = re.compile(
+ r"^\s*(?:(?:user|assistant|system|developer|tool result|message):"
+ r"|assistant called (?:[^:\n]+:)?)?\s*$",
+ re.IGNORECASE,
+)
+
+
+def _probes_for(text: str) -> list[str]:
+ """The lines of an archived chunk, normalised into things to look for on the branch.
+
+ Substring containment on a normalised prefix rather than a digest match: the archived
+ text came from the inference projection and the saved copy from the message store, so
+ exact equality is too brittle. The role labels ``render_turn`` writes exist only in
+ the archived copy, so they are stripped first, or every probe misses.
+ """
+ probes = []
+ for line in (text or "").splitlines():
+ without_role = _ROLE_PREFIX.sub("", line)
+ named = _TOOL_CALL_NAME.match(without_role.strip())
+ if named:
+ # Its own probe, ahead of the arguments, which is the order `_probe_text`
+ # renders them in. Without it the arguments alone decided, and a call to a
+ # different tool with the same arguments matched.
+ #
+ # Except "tool", which is `render_turn`'s own fallback for a call that
+ # arrived without a name. The live text carries no name there either, so
+ # requiring it would reject every one of those turns.
+ name = _normalise(named.group(1))
+ if name and name != "tool":
+ probes.append(name)
+ stripped = _normalise(_TOOL_CALL_PREFIX.sub("", without_role))
+ # The WHOLE line, except where render_turn cut something short: a prefix probe
+ # cannot see an edit past its cut-off, leaving a rewritten tail eligible.
+ # Keyed off the marker, not a "tool result:" label: a long tool result is ONE
+ # string of many newlines, so only its first line carries the label while the
+ # marker is on its last, and nothing in a real transcript ends in the marker, so
+ # every over-cap tool turn was rejected. Reproduced on a 400-line result.
+ if stripped.endswith(_TRUNCATION_MARKER.strip()):
+ stripped = stripped[: -len(_TRUNCATION_MARKER.strip())].strip()
+ probes.append(stripped)
+ return [probe for probe in probes if probe]
+
+
+def _probe_entries(text: str) -> list[tuple[str, bool]]:
+ """``_probes_for`` with a flag per line: was it cut short, or is it a tool call.
+
+ Both mean the live message may legitimately hold more than the probe: a cut line is a
+ prefix by construction, and a tool call is matched against a haystack that renders its
+ arguments twice, spaced and compact, so only one of the two can ever be covered.
+ """
+ entries = []
+ for line in (text or "").splitlines():
+ without_role = _ROLE_PREFIX.sub("", line)
+ is_call = bool(_TOOL_CALL_PREFIX.match(without_role.strip()))
+ named = _TOOL_CALL_NAME.match(without_role.strip())
+ if named:
+ # See `_probes_for`: the tool's NAME is a probe of its own, or the arguments
+ # alone decide and a retry that swapped the tool still matches. Flagged as a
+ # call so it keeps the haystack comparison the rest of the line gets.
+ # "tool" is `render_turn`'s fallback for a nameless call; see `_probes_for`.
+ name = _normalise(named.group(1))
+ if name and name != "tool":
+ entries.append((name, True))
+ stripped = _normalise(_TOOL_CALL_PREFIX.sub("", without_role))
+ truncated = stripped.endswith(_TRUNCATION_MARKER.strip())
+ if truncated:
+ stripped = stripped[: -len(_TRUNCATION_MARKER.strip())].strip()
+ if stripped:
+ entries.append((stripped, truncated or is_call))
+ elif truncated and entries:
+ # The cut landed exactly on a line boundary, so the marker is a line of its
+ # own and the line before it is the one that was cut short. Dropping the empty
+ # marker dropped the flag with it, the last real probe was read as complete,
+ # and `_document_matches_one_run` retired an unedited over-cap turn: measured
+ # on a 900-line tool result whose 4000-character cut fell on a newline, the
+ # live turn came back off-branch and no query could return it.
+ entries[-1] = (entries[-1][0], True)
+ return entries
+
+
+def _on_live_branch(text: str, transcript: Optional[list[str]]) -> bool:
+ """Whether one archived chunk still exists in the saved thread."""
+ probes = _probes_for(text)
+ if not probes or not transcript:
+ return False
+ # EVERY line, IN ORDER, WITHIN ONE RUN OF ADJACENT MESSAGES. All of a turn, because
+ # it is archived as a unit and editing only the assistant half leaves the user line
+ # matching. In order, because independent membership accepts rearranged lines. In one
+ # bounded run, because a global scan lets any later message supply a missing line,
+ # which is how "Should I deploy? / No" survived its answer becoming "Yes".
+ # The window is the probe count; m messages render at least m lines, so a real turn
+ # always fits.
+ window = len(probes)
+ return any(
+ _probes_match_from(probes, transcript, start, window) for start in range(len(transcript))
+ )
+
+
+def _scan_probes(
+ entries: list[tuple[str, bool]], messages: list[str], start: int, last: int
+) -> Optional[tuple[int, int, int, bool, int]]:
+ """Where the probes finish: message index, end offset, opening offset, tail-is-partial,
+ and the message index the run OPENED on.
+
+ An index rather than a bool so one document's chunks scan as a single pass, each
+ continuing where the last stopped, which stops two chunks of a turn matching two
+ places. The cursor within that message is NOT carried over: chunks overlap by
+ ``CHUNK_OVERLAP``, so the next one legitimately repeats the previous tail.
+
+ The opening index is reported because that repeated tail can begin in an EARLIER
+ message than the one the previous chunk finished in -- a short line such as an
+ assistant tool call just before a long tool result is carried into the next chunk
+ whole. Resuming at the finishing message could then never match it, and an unedited
+ document was retired as off-branch, which makes that turn unsearchable.
+ """
+ index = start
+ cursor = 0
+ opened_at = None
+ opened_index = None
+ partial = False
+ fresh = False
+ for probe, partial_ok in entries:
+ while index < last:
+ found = messages[index].find(probe, cursor)
+ if found >= 0:
+ # A message the run stepped INTO has to be accounted for from its first
+ # character: an edit that prepends to it ("no" becoming "correction: no")
+ # otherwise leaves every probe matching. A tool call is exempt, and the
+ # exemption then covers the rest of that message: the store keeps a call
+ # as a structured part, so the live text carries the tool name and BOTH
+ # spellings of its arguments while the archived copy has one line of one
+ # of them. Nothing there can line up character for character.
+ if fresh and found != 0 and not partial_ok:
+ return None
+ # And text inserted BETWEEN two probes of the same message. The two checks
+ # around this one cover an edit that prepends to a message the run stepped
+ # into and one that appends to a message it is leaving; a correction
+ # dropped between two archived lines matched both of them with the new
+ # line sitting unexamined in the gap, so the pre-edit turn stayed
+ # recallable. Measured on "A\nB" becoming "A\ncorrection\nB".
+ #
+ # A gap is only allowed where it is a label `render_turn` wrote and the
+ # probe therefore had stripped: a pasted transcript legitimately carries
+ # its own "user:" lines. Anything else is content the archive never saw.
+ if (
+ not fresh
+ and cursor
+ and not (partial or partial_ok)
+ and not _GAP_IS_LABEL.match(messages[index][cursor:found])
+ ):
+ return None
+ if opened_at is None:
+ # Same exemption at the front of the run as inside it.
+ opened_at = 0 if partial_ok else found
+ opened_index = index
+ cursor = found + len(probe)
+ # The exemption belongs to the CALL, not to the rest of the message. It
+ # exists because a stored tool call cannot line up character for character
+ # with the live text (the store keeps arguments as an object and offers
+ # both JSON spellings), so the cursor after one is not exact. Once an
+ # ordinary text probe has matched, the cursor IS exact again and the gap
+ # and trailing-content checks can be enforced. Left sticky, an assistant
+ # turn carrying both a call and text stayed matched after a correction was
+ # appended to that text, so the pre-edit turn was still recallable.
+ partial = partial_ok
+ fresh = False
+ break
+ # And leaving one it had entered: whatever is left over is text an edit added.
+ if cursor and not partial and cursor < len(messages[index]):
+ return None
+ index += 1
+ cursor = 0
+ partial = False
+ fresh = True
+ else:
+ return None
+ return (
+ index,
+ cursor,
+ (opened_at or 0),
+ partial,
+ (opened_index if opened_index is not None else start),
+ )
+
+
+def _probes_match_from(probes: list[str], messages: list[str], start: int, window: int) -> bool:
+ """Whether ``probes`` appear in order within ``messages[start:start + window]``."""
+ return (
+ _scan_probes(
+ [(probe, True) for probe in probes],
+ messages,
+ start,
+ min(len(messages), start + window),
+ )
+ is not None
+ )
+
+
+def _rendered_message_count(rows) -> int:
+ """How many messages the archived turn was rendered from.
+
+ ``render_turn`` labels every message it writes, so labelled lines count messages. That
+ bounds the run this document may occupy, far tighter than a line count: a two-message
+ turn can be a hundred lines, and a hundred-message window finds its tail anywhere.
+
+ Overlapping chunks can double-count a label, which only widens the window: the safe
+ direction, since too narrow retires turns that are still live.
+ """
+ total = 0
+ for row in rows:
+ for line in (row["text"] or "").splitlines():
+ stripped = line.strip()
+ if _ROLE_PREFIX.match(stripped) or _TOOL_CALL_PREFIX.match(stripped):
+ total += 1
+ return total
+
+
+def _document_on_live_branch(conn, document_id: str, transcript: list[str], cache: dict) -> bool:
+ """Whether EVERY chunk of an archived turn is still on the branch.
+
+ Per chunk is not enough: a turn over CHUNK_TOKENS spans several chunks, so editing the
+ second half of a long answer leaves the untouched earlier chunks eligible on their
+ own. The archived unit is the turn, so an edit to any part retires the whole copy.
+
+ Cached per call: candidates from one turn share a document, and this is the filter's
+ only query.
+ """
+ if document_id in cache:
+ return cache[document_id]
+ try:
+ rows = conn.execute(
+ "SELECT text FROM chunks WHERE document_id = ? ORDER BY chunk_index ASC",
+ (document_id,),
+ ).fetchall()
+ # NULL for archives predating the column, which fall back to counting labels.
+ row = conn.execute(
+ "SELECT archive_messages FROM documents WHERE id = ?", (document_id,)
+ ).fetchone()
+ message_count = row["archive_messages"] if row else None
+ except Exception:
+ # Never fail a recall on the strictness pass: fall back to what the candidate
+ # chunk itself said.
+ cache[document_id] = True
+ return True
+ cache[document_id] = _document_matches_one_run(rows, transcript, message_count)
+ return cache[document_id]
+
+
+def _document_matches_one_run(
+ rows,
+ transcript: Optional[list[str]],
+ message_count: Optional[int] = None,
+) -> bool:
+ """Every chunk of the turn, found within ONE run of adjacent messages.
+
+ Chunk by chunk independently is not enough: they are consecutive slices of one turn,
+ so letting each pick its own place reassembles a turn from parts that never sat
+ together (head on the current answer, tail on a later message repeating what the edit
+ removed). Reproduced before the run was shared. The run is bounded by at least the
+ number of messages the turn was rendered from, so a live turn always fits.
+ """
+ if not rows or not transcript:
+ return False
+ probe_lists = [_probe_entries(row["text"]) for row in rows]
+ if any(not probes for probes in probe_lists):
+ return False
+ # The messages the turn was rendered from, not the lines it produced: bounding by
+ # lines let a long answer's tail be satisfied far outside the turn. Recorded at
+ # archive time; the label count is an approximate fallback for older documents, since
+ # a pasted transcript contains lines that look like the renderer's own.
+ window = (
+ int(message_count)
+ if message_count
+ else (_rendered_message_count(rows) or sum(len(probes) for probes in probe_lists))
+ )
+
+ def _one_run_from(start: int) -> bool:
+ last = min(len(transcript), start + window)
+ position = start
+ cursor = 0
+ opened_at = None
+ partial_tail = False
+ # How far back the NEXT chunk may restart. A chunk's leading overlap is the
+ # previous chunk's tail, and `CHUNK_OVERLAP` can carry a whole short message with
+ # it -- an assistant tool call sitting just before a long tool result. Resuming
+ # strictly at the message the previous chunk FINISHED in then cannot match that
+ # overlap, and an unedited document was retired as off-branch, which makes the
+ # turn unsearchable: reproduced on a 4-message turn for 7 of 89 question lengths.
+ # Never earlier than where the previous chunk itself opened, since the overlap
+ # cannot predate it, and the forward position is always tried FIRST, so this only
+ # ever rescues a scan that used to fail outright.
+ floor = start
+ for probes in probe_lists:
+ found = None
+ for candidate in range(position, floor - 1, -1):
+ found = _scan_probes(probes, transcript, candidate, last)
+ if found is not None:
+ break
+ if found is None:
+ return False
+ position, cursor, chunk_opened_at, partial_tail, floor = found
+ # Where the whole run opened, which is the first chunk's answer: an edit that
+ # prepends to the turn's FIRST message shows up here and nowhere else.
+ if opened_at is None:
+ opened_at = chunk_opened_at
+ # And the turn has to cover the messages it claims, end to end. An edit that
+ # keeps the old text and adds to it leaves every probe matching, whichever side it
+ # adds on and whichever message it touches: "No" becoming "No, correction: yes" or
+ # "Correction: no", or the question itself growing a clause. Either way the
+ # pre-edit copy stayed eligible and could be recalled as the answer.
+ if opened_at:
+ return False
+ return partial_tail or cursor >= len(transcript[position])
+
+ return any(_one_run_from(start) for start in range(len(transcript)))
+
+
+def _candidates(conn, scope: str, query: str, model, fetch: int, thread_id: str) -> list:
+ """Up to ``fetch`` archive chunks for ``query``: lexical first, hybrid for the rest."""
+ hits = retrieval.retrieve_hybrid(conn, scope, query, k = fetch, model_name = model, mode = "lexical")
+ if len(hits) < fetch:
+ try:
+ seen = {hit.chunk_id for hit in hits}
+ for hit in retrieval.retrieve_hybrid(
+ conn, scope, query, k = fetch, model_name = model, mode = "hybrid"
+ ):
+ if hit.chunk_id not in seen:
+ hits.append(hit)
+ seen.add(hit.chunk_id)
+ if len(hits) >= fetch:
+ break
+ except Exception:
+ # Dense retrieval raises rather than degrading when no embedder can start.
+ # The lexical hits stand on their own, so this top-up may fail.
+ logger.warning(
+ "conversation_archive.dense_unavailable thread_id=%s", thread_id, exc_info = True
+ )
+ return hits
+
+
+def recall(
+ thread_id: str,
+ query: str,
+ *,
+ top_k: Optional[int] = None,
+ branch_messages: Optional[list[dict]] = None,
+) -> Optional[tuple[str, list[dict]]]:
+ """Most relevant archived turns for ``query``, rendered like any other RAG hit.
+
+ LEXICAL FIRST, then hybrid for the rest of the budget. Recalling your own conversation
+ is mostly exact match (a name, a number, a code pasted twenty turns ago), which lives
+ or dies on rare tokens. Measured on a 30-turn walkthrough with identical boilerplate
+ per turn: the needle chunk ranked 3rd lexically at any k, was never returned by dense
+ retrieval at all, and RRF fusion pushed it to 16th behind 30 useless dense hits.
+ Hybrid alone lost the answer. Dense still earns its place for paraphrased recall, so
+ it fills whatever the lexical pass leaves.
+
+ No relevance floor, unlike ``tool.search_for_autoinject``: its 0.70 cosine gate keeps
+ off-topic documents out, but here the passages ARE this conversation and the
+ alternative to a weak match is no memory at all. It also keeps lexical-only hits,
+ since ``filter_min_score`` only gates hits carrying a dense score.
+ """
+ query = (query or "").strip()
+ if not thread_id or not query or not enabled():
+ return None
+
+ scope = store.conversation_archive_scope(thread_id)
+ limit = top_k or config.CONVERSATION_ARCHIVE_TOP_K
+ conn = None
+ try:
+ conn = rag_db.get_connection()
+ model = config.effective_embedding_model()
+ # The request's own branch first: the stored rows are the whole DAG. Falling back
+ # to them still beats not filtering when the caller has no branch to offer.
+ transcript = branch_message_texts(branch_messages) or _live_transcript(thread_id)
+ fetch = limit * _BRANCH_FILTER_OVERFETCH
+ rows: dict = {}
+ hits: list = []
+ live_documents: dict = {}
+ while True:
+ candidates = _candidates(conn, scope, query, model, fetch, thread_id)
+ if not candidates:
+ return None
+ rows = store.chunks_by_id(conn, [hit.chunk_id for hit in candidates])
+ if not transcript:
+ hits = candidates[:limit]
+ break
+ hits = [
+ hit
+ for hit in candidates
+ if hit.chunk_id in rows
+ and _document_on_live_branch(
+ conn, rows[hit.chunk_id]["document_id"], transcript, live_documents
+ )
+ ]
+ if len(hits) != len(candidates):
+ logger.info(
+ "conversation_archive.branch_filtered thread_id=%s kept=%d of %d",
+ thread_id,
+ len(hits),
+ len(candidates),
+ )
+ # Enough live hits, or nothing more to widen into: an abandoned branch can
+ # outrank the live one, but it cannot outrank it forever.
+ if (
+ len(hits) >= limit
+ or len(candidates) < fetch
+ or fetch >= _BRANCH_FILTER_MAX_CANDIDATES
+ ):
+ hits = hits[:limit]
+ break
+ fetch = min(_BRANCH_FILTER_MAX_CANDIDATES, fetch * _BRANCH_FILTER_OVERFETCH)
+ if not hits:
+ return None
+ text, sources = tool._format(rows, hits)
+ return (text, sources) if sources else None
+ except Exception:
+ logger.warning("conversation_archive.recall_failed thread_id=%s", thread_id, exc_info = True)
+ return None
+ finally:
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
+
+def _scope_select(scope: str, created_before: Optional[str]) -> tuple:
+ """The scope's document ids, optionally cut at ``created_before``. See `delete_for_thread`."""
+ if not created_before:
+ return ("SELECT id FROM documents WHERE scope=?", (scope,))
+ return (
+ "SELECT id FROM documents WHERE scope=? AND created_at<?",
+ (scope, created_before),
+ )
+
+
+def _delete_scope_without_vec(
+ scope: str,
+ thread_id: str,
+ *,
+ created_before: Optional[str] = None,
+) -> int:
+ """Delete a scope's text-bearing rows over a connection with no sqlite-vec.
+
+ Deletion must not depend on the optional native extension. Archives are only WRITTEN
+ while vec0 loads, but it can stop loading afterwards (a venv change, common on macOS),
+ and a delete that silently does nothing leaves a deleted conversation on disk ready to
+ answer again once vec0 returns.
+
+ The chunks_vec rows are unreachable from here and left behind. They carry vectors, not
+ text, and every read path resolves through ``chunks`` joined to ``documents``, both
+ gone, so nothing can retrieve an orphan.
+ """
+ conn = None
+ removed = 0
+ try:
+ conn = rag_db.get_metadata_connection()
+ documents = [
+ row["id"] for row in conn.execute(*_scope_select(scope, created_before)).fetchall()
+ ]
+ for document_id in documents:
+ conn.execute(
+ "DELETE FROM chunks_fts WHERE chunk_id IN "
+ "(SELECT id FROM chunks WHERE document_id=?)",
+ (document_id,),
+ )
+ conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
+ conn.execute("DELETE FROM documents WHERE id=?", (document_id,))
+ removed += 1
+ conn.commit()
+ except Exception:
+ logger.warning(
+ "conversation_archive.delete_without_vec_failed thread_id=%s", thread_id, exc_info = True
+ )
+ finally:
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+ return removed
+
+
+def delete_for_thread(thread_id: str, *, created_before: Optional[str] = None) -> int:
+ """Drop a thread's archive. Called when the thread itself is deleted.
+
+ ``created_before`` bounds the delete to documents archived before an ISO-8601 UTC
+ instant, which is how a thread id that came BACK is handled. Skipping the scope
+ wholesale spared the recreated chat's memory but also kept the deleted
+ conversation's, under a live id with nothing left to sweep it: the endpoint reported
+ success while the turns the user asked to delete stayed recallable in the new chat.
+ Cutting at the moment the delete was accepted takes exactly the old conversation and
+ leaves whatever the recreated thread has archived since.
+ """
+ if not thread_id:
+ return 0
+ scope = store.conversation_archive_scope(thread_id)
+ conn = None
+ removed = 0
+ try:
+ try:
+ conn = rag_db.get_connection()
+ except Exception:
+ # No vec0 here. Delete what can be deleted rather than nothing at all.
+ return _delete_scope_without_vec(scope, thread_id, created_before = created_before)
+ for row in conn.execute(*_scope_select(scope, created_before)).fetchall():
+ store.delete_document(conn, row["id"])
+ removed += 1
+ except Exception:
+ logger.warning("conversation_archive.delete_failed thread_id=%s", thread_id, exc_info = True)
+ finally:
+ if conn is not None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+ return removed
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index 60cc5f389ba..76b341762a1 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -35,6 +35,20 @@ def project_scope(project_id: str) -> str:
return f"project_{project_id}"
+CONVERSATION_ARCHIVE_PREFIX = "convarchive_"
+
+
+def conversation_archive_scope(thread_id: str) -> str:
+ """Scope holding the turns a thread's rolling context window has evicted.
+
+ Deliberately NOT ``thread_scope``: with ``config.THREAD_WHOLE_DOC`` on, that scope is
+ rendered in full into every request, so archiving turns there would re-inject the
+ history and undo the compaction. A separate scope also keeps the archive out of the
+ attachments UI and the citation panel.
+ """
+ return f"{CONVERSATION_ARCHIVE_PREFIX}{thread_id}"
+
+
def _scopes(scope) -> list[str]:
"""Search helpers accept one scope or several (e.g. project + thread)."""
return [scope] if isinstance(scope, str) else list(scope)
@@ -130,13 +144,14 @@ def create_document(
embedding_model: str | None = None,
linked_folder_id: str | None = None,
linked_relative_path: str | None = None,
+ archive_messages: int | None = None,
commit: bool = True,
) -> str:
document_id = document_id or str(uuid.uuid4())
conn.execute(
"INSERT INTO documents(id, scope, kb_id, thread_id, project_id, filename, sha256, "
"status, stored_path, created_at, embedding_model, linked_folder_id, "
- "linked_relative_path) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
+ "linked_relative_path, archive_messages) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
document_id,
scope,
@@ -151,6 +166,7 @@ def create_document(
embedding_model,
linked_folder_id,
linked_relative_path,
+ archive_messages,
),
)
if commit:
@@ -197,12 +213,17 @@ def list_documents(conn: sqlite3.Connection, scope: str) -> list[dict]:
def list_all_documents(conn: sqlite3.Connection) -> list[dict]:
- """Every uploaded document across all scopes (KBs, threads, projects)."""
+ """Every uploaded document across all scopes (KBs, threads, projects).
+
+ Archived conversation turns are excluded: nobody uploaded them, so listing them would
+ show a chat's own history back as files the user never added.
+ """
rows = conn.execute(
"SELECT id, scope, kb_id, thread_id, project_id, filename, sha256, status, error, "
"num_chunks, stored_path, created_at, linked_folder_id "
"FROM documents d WHERE NOT EXISTS "
"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ "AND d.scope NOT LIKE 'convarchive#_%' ESCAPE '#' "
"ORDER BY created_at DESC"
).fetchall()
return [dict(r) for r in rows]
diff --git a/studio/backend/core/rag/tool.py b/studio/backend/core/rag/tool.py
index b05f8dd3a35..4cc4b876701 100644
--- a/studio/backend/core/rag/tool.py
+++ b/studio/backend/core/rag/tool.py
@@ -18,6 +18,7 @@ from storage import rag_db
from . import config, retrieval
from .store import (
all_chunks_for_scope,
+ conversation_archive_scope,
kb_scope,
project_scope,
scope_token_estimate,
@@ -53,9 +54,16 @@ def _resolve_scope(
scope_kb_id: str | None,
scope_thread_id: str | None,
scope_project_id: str | None = None,
+ scope_conversation_id: str | None = None,
) -> str | list[str] | None:
"""KB (an explicit pick) is exclusive; project and thread scopes combine so a
- project chat also retrieves from its own attached documents."""
+ project chat also retrieves from its own attached documents.
+
+ The conversation archive is exclusive too, and takes precedence: it is a different
+ corpus (this chat's evicted turns), so sharing a top-K would have old turns and
+ document passages crowd each other out."""
+ if scope_conversation_id:
+ return conversation_archive_scope(scope_conversation_id)
if scope_kb_id:
return kb_scope(scope_kb_id)
scopes = []
@@ -126,6 +134,7 @@ def search_knowledge_base_with_sources(
scope_kb_id: str | None = None,
scope_thread_id: str | None = None,
scope_project_id: str | None = None,
+ scope_conversation_id: str | None = None,
top_k: int | None = None,
min_score: float = 0.0,
model_name: str | None = None,
@@ -135,7 +144,7 @@ def search_knowledge_base_with_sources(
rendered ``<chunk>`` block's ``id``."""
if not query or not query.strip():
return "Error: query is empty.", []
- scope = _resolve_scope(scope_kb_id, scope_thread_id, scope_project_id)
+ scope = _resolve_scope(scope_kb_id, scope_thread_id, scope_project_id, scope_conversation_id)
if scope is None:
return "No documents are attached to this chat.", []
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 86ce24b140b..a92ed45fd6c 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -707,6 +707,8 @@ async def delete_threads(
):
from starlette.concurrency import run_in_threadpool
+ # Before the rows go, so a thread id that comes back in the gap is cut here.
+ cutoff = _archive_cutoff()
deleted_research_run_ids = await run_in_threadpool(delete_chat_threads, payload.ids)
_cancel_research_runs(request, deleted_research_run_ids)
_cancel_active_generations(payload.ids)
@@ -715,9 +717,43 @@ async def delete_threads(
# In a worker: right after an upgrade this also runs the legacy move, and a
# cross-filesystem copy on the event loop stops every other request.
removed, kept = await _remove_sandboxes(payload.ids, payload.delete_files)
+ # Archived turns are keyed by thread id and unreferenced once the thread is gone, so
+ # drop them rather than leaking a scope per deleted chat.
+ await run_in_threadpool(_remove_conversation_archives, payload.ids, cutoff = cutoff)
return {"status": "deleted", "sandboxes_removed": removed, "sandboxes_kept": kept}
+def _archive_cutoff() -> str:
+ """The instant a delete was accepted, as an ISO-8601 UTC string. See below."""
+ from datetime import datetime, timezone
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _remove_conversation_archives(thread_ids, *, cutoff: "str | None" = None) -> None:
+ """Drop each deleted thread's archived turns. Never raises."""
+ try:
+ from core.rag import conversation_archive
+ except Exception:
+ return
+ for thread_id in thread_ids or []:
+ # As next to the sandbox removal: the rows went first and the sandbox pass ran in
+ # between, so another tab can have recreated this id and already be archiving
+ # turns under it. That chat is alive, and its memory is not this delete's to take
+ # -- but the conversation the user DID delete is, and skipping the scope kept it
+ # too, recallable under the live id with nothing left to sweep it. So cut at the
+ # instant the delete was accepted instead of skipping: everything archived before
+ # it belongs to the deleted conversation, everything after to the new one.
+ recreated = get_chat_thread(str(thread_id)) is not None
+ if recreated and not cutoff:
+ continue
+ try:
+ conversation_archive.delete_for_thread(
+ str(thread_id), created_before = cutoff if recreated else None
+ )
+ except Exception:
+ logger.warning("Could not remove the conversation archive for %s", thread_id)
+
+
async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[str]]":
"""Drop each thread's sandbox off the event loop. Never raises.
@@ -1008,6 +1044,7 @@ async def delete_project(
# Rows first, files last: a member chat can still be running a tool in the
# workspace, and its cwd disappearing mid-call either kills the call or
# leaves what it writes next in a directory no project owns.
+ cutoff = _archive_cutoff()
try:
project = await run_in_threadpool(
lambda: delete_chat_project(project_id, delete_files = False)
@@ -1041,6 +1078,8 @@ async def delete_project(
# By run id: the rows are gone by now, so there is nothing left to look up.
_cancel_research_runs(request, list(project.get("activeResearchRunIds") or []))
_cancel_active_generations(member_ids)
+ # The project's chats go with it, so their archives have to as well.
+ await run_in_threadpool(_remove_conversation_archives, member_ids, cutoff = cutoff)
if project.get("sandboxPath"):
from core.inference.tools import (
finish_workspace_delete_when_idle,
@@ -1298,6 +1337,7 @@ async def clear_history(
):
from starlette.concurrency import run_in_threadpool
+ cutoff = _archive_cutoff()
# Admission is already closed in the frontend. Include its pending and legacy ids in the
# transaction's fence so a delayed POST cannot recreate a chat after this returns.
thread_ids = (
@@ -1330,6 +1370,11 @@ async def clear_history(
_cancel_active_generations(late)
# By id: the rows went with the threads, so nothing can look them up now.
_cancel_research_runs(request, cleared_runs)
+ # Same archive cleanup as DELETE /threads. Without it "Clear all chats" leaves every
+ # conversation searchable in rag.db, and a reused thread id reads the old archive.
+ await run_in_threadpool(
+ _remove_conversation_archives, list(dict.fromkeys(thread_ids + cleared)), cutoff = cutoff
+ )
# "Clear all chats" is the common bulk delete, so it has to clean up the
# same folders DELETE /threads does; otherwise every sandbox is stranded.
# delete_files matches DELETE /threads: off by default, since the files are
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 64bb96151a0..5c5bfaa307c 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -682,9 +682,9 @@ def _accumulate_context_truncation(current: Optional[dict], event: dict) -> dict
if current is None:
return incoming
combined = {**current, **incoming}
- combined["dropped_messages"] = int(current.get("dropped_messages") or 0) + int(
- incoming.get("dropped_messages") or 0
- )
+ for counter in ("dropped_messages", "archived_messages", "recalled_chunks"):
+ if counter in current or counter in incoming:
+ combined[counter] = int(current.get(counter) or 0) + int(incoming.get(counter) or 0)
if current.get("prompt_tokens_before") is not None:
combined["prompt_tokens_before"] = current["prompt_tokens_before"]
return combined
@@ -3426,6 +3426,17 @@ _RAG_GROUNDING_NUDGE = (
)
+def _thread_has_conversation_archive(thread_id) -> bool:
+ """Whether the rolling window has archived anything for this thread yet."""
+ if not thread_id:
+ return False
+ try:
+ from core.rag import conversation_archive
+ return conversation_archive.has_archive(str(thread_id))
+ except Exception:
+ return False
+
+
async def _select_request_tools(
payload: ChatCompletionRequest, *, tools_on: bool, mcp_allowed: bool
) -> list[dict]:
@@ -3455,6 +3466,20 @@ async def _select_request_tools(
# Drop the RAG tool without a scope: nothing to search over.
if not payload.rag_scope:
tools = [t for t in tools if t["function"]["name"] != "search_knowledge_base"]
+ # Same rule for the conversation archive: offered only once this thread has had turns
+ # evicted, so a short chat never sees the extra schema. On the first compaction the
+ # tool is still absent (the archive is written mid-request) and the forced recall
+ # covers that turn. getattr, because this helper also serves the token-count request
+ # model, which carries no thread_id.
+ # Follows the ARCHIVE, not the caller's allowlist: Studio always sends an explicit
+ # enabled_tools array and has no reason to name an internal tool it shows no pill for,
+ # so the filter above removed search_conversation and neither it nor the compaction
+ # nudge gated on it ever reached a Studio chat. It is read-only and always-safe, so it
+ # is added on that condition rather than requested.
+ has_archive = _thread_has_conversation_archive(getattr(payload, "thread_id", None))
+ tools = [t for t in tools if t["function"]["name"] != "search_conversation"]
+ if has_archive and tools_on:
+ tools = tools + [t for t in ALL_TOOLS if t["function"]["name"] == "search_conversation"]
# Built-ins only, so this runs before the MCP append: an MCP tool's
# description is the server's to write, and Full access says nothing about
# how that server runs.
@@ -3465,6 +3490,28 @@ async def _select_request_tools(
return tools
+_COMPACTED_SESSION_NUDGE = (
+ "This conversation is long, so older turns have been removed from your context. "
+ "The relevant ones are retrieved and shown to you automatically when that happens. "
+ "If the user refers to something you cannot see, call search_conversation before "
+ "answering. Never tell the user you have no record of an earlier turn, and never "
+ "assume the conversation began where your visible context begins."
+)
+
+
+def _apply_compaction_nudge(nudge: str, tools: list[dict]) -> str:
+ """Append the compacted-session nudge when the conversation-archive tool is active.
+
+ Gated on the tool rather than separate state, so it appears exactly when there is an
+ archive to search and stays a no-op for chats that never compacted."""
+ tool_names = {(t.get("function") or {}).get("name") for t in (tools or [])}
+ if "search_conversation" not in tool_names:
+ return nudge
+ if not nudge:
+ return _COMPACTED_SESSION_NUDGE
+ return nudge + " " + _COMPACTED_SESSION_NUDGE
+
+
def _apply_rag_nudge(nudge: str, tools: list[dict], *, rag_scope) -> str:
"""Append the RAG grounding nudge to ``nudge`` when the knowledge-base tool
is active (search_knowledge_base present and a retrieval scope is set). The
@@ -14219,6 +14266,7 @@ async def openai_chat_completions(
# Nudge the model to ground in attached documents instead of memory.
_nudge = _apply_rag_nudge(_nudge, tools_to_use, rag_scope = payload.rag_scope)
+ _nudge = _apply_compaction_nudge(_nudge, tools_to_use)
if _nudge:
# Append nudge to system prompt (preserve user's prompt)
@@ -14982,6 +15030,7 @@ async def openai_chat_completions(
seed = _seed,
perf_callback = _gguf_perf_callback,
context_overflow = _rolling_context_policy(payload),
+ thread_id = payload.thread_id,
)
_gguf_sentinel = object()
@@ -15483,8 +15532,8 @@ async def openai_chat_completions(
or int(_choice_context_truncation.get("dropped_messages") or 0)
>= int(_context_truncation.get("dropped_messages") or 0)
):
- # Choices share the original prompt. Keep the shortest
- # choice's cumulative fit instead of summing choices.
+ # Choices share one prompt: report the choice that dropped
+ # the most, rather than summing across choices.
_context_truncation = _choice_context_truncation
reasoning_text, visible_text = _extract_responses_reasoning(
@@ -15778,6 +15827,7 @@ async def openai_chat_completions(
# RAG nudge, mirroring the GGUF path.
_sf_nudge = _apply_rag_nudge(_sf_nudge, _sf_tools_to_use, rag_scope = payload.rag_scope)
+ _sf_nudge = _apply_compaction_nudge(_sf_nudge, _sf_tools_to_use)
_sf_system_prompt = system_prompt
if _sf_nudge:
@@ -19650,7 +19700,9 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {
# this channel has no way to present, so an omitted permission_mode ("ask") only
# asks then. render_html is excluded because a networked canvas prompts in auto,
# and this channel invokes the loop without confirm; auto/ask reject, off/full run.
-_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset({"web_search", "search_knowledge_base"})
+_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset(
+ {"web_search", "search_knowledge_base", "search_conversation"}
+)
def _anthropic_selects_server_tools(
diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.py
index f82ea9c0973..0e055c22f41 100644
--- a/studio/backend/storage/rag_db.py
+++ b/studio/backend/storage/rag_db.py
@@ -255,6 +255,10 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
conn.execute("ALTER TABLE documents ADD COLUMN linked_folder_id TEXT")
if "linked_relative_path" not in cols:
conn.execute("ALTER TABLE documents ADD COLUMN linked_relative_path TEXT")
+ # How many messages an archived turn was rendered from. NULL for everything else and
+ # for older archives, which fall back to counting role labels in the rendered text.
+ if "archive_messages" not in cols:
+ conn.execute("ALTER TABLE documents ADD COLUMN archive_messages INTEGER")
# After the ALTER that adds the column on an older database. Partial, so it holds only
# folder-owned rows and is empty with nothing linked, which keeps the lexical fast-path
# gate an index probe rather than a scan of documents.
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index ef707a79917..d90d175e7c3 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3355,6 +3355,22 @@ def count_forks_for_message(thread_id: str, message_id: str) -> int:
conn.close()
+def chat_thread_has_messages(thread_id: str) -> bool:
+ """Whether this thread has any saved message. Existence only, no rows hydrated.
+
+ A temporary (incognito) chat is never written here, so this is what tells a thread
+ whose turns can be archived from one whose turns must not be.
+ """
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ "SELECT 1 FROM chat_messages WHERE thread_id = ? LIMIT 1", (thread_id,)
+ ).fetchone()
+ return row is not None
+ finally:
+ conn.close()
+
+
def fork_counts_for_thread(thread_id: str) -> dict[str, int]:
"""Fork counts for every message of one thread, keyed by message id."""
conn = get_connection()
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index e9a764da6e7..adb5322ec60 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -2132,6 +2132,19 @@ class TestAnthropicMessagesToolRouting:
_drive(anthropic_messages(payload, request = None, current_subject = "t"))
assert backend.calls[0][0] == "tools"
+ # Reading this conversation's own archive is as read-only as the other two, and
+ # is_potentially_unsafe_tool_call says so, so selecting it must not trip the gate.
+ # Adding the schema to ALL_TOOLS without adding the name here made the Anthropic
+ # selector pick it and the pre-switch guard reject the whole request with the
+ # terminal/python message, on auto and on the omitted default alike.
+ for extra in ({"permission_mode": "auto"}, {}):
+ backend = _mock_backend(monkeypatch)
+ payload = _basic_payload(
+ enable_tools = True, enabled_tools = ["search_conversation"], **extra
+ )
+ _drive(anthropic_messages(payload, request = None, current_subject = "t"))
+ assert backend.calls[0][0] == "tools"
+
# But auto or an omitted mode that would run a local tool (terminal/python,
# via a bare Anthropic tool type or enabled_tools) is rejected, since that
# tool could need the gate this channel lacks.
diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.py
index e1569496a76..1239b1830d4 100644
--- a/studio/backend/tests/test_context_overflow_truncation.py
+++ b/studio/backend/tests/test_context_overflow_truncation.py
@@ -37,7 +37,13 @@ from routes.inference import (
_truncate_middle_messages,
_truncate_oldest_messages,
)
-from core.inference.context_window import fit_rolling_context, messages_have_media
+from core.inference import context_window
+from core.inference.context_window import (
+ evicted_messages,
+ fit_rolling_context,
+ group_turns,
+ messages_have_media,
+)
from models.inference import ChatCompletion
import routes.inference as routes_mod
@@ -234,9 +240,8 @@ def test_rolling_media_detection_covers_image_and_audio_parts():
assert messages_have_media(
[{"role": "user", "content": [{"type": "input_audio", "input_audio": {}}]}]
)
- # llama.cpp's own part type, written by `_inject_video_part` into the very list this
- # fit is handed. Missed, a video prompt ran the preflight that video tokens are not
- # counted by, so it could be certified as fitting when it does not.
+ # llama.cpp's own part type; missing it would send a video prompt through a
+ # preflight that does not count its tokens.
assert messages_have_media(
[{"role": "user", "content": [{"type": "input_video", "input_video": {"data": "AAAA"}}]}]
)
@@ -270,7 +275,18 @@ def test_rolling_truncation_can_drop_assistant_after_instruction(instruction_rol
assert new == [instruction, latest]
-def test_rolling_fit_recounts_until_the_real_template_fits():
+def no_compaction_headroom(monkeypatch):
+ """Pin the compaction headroom to zero.
+
+ For tests about the MINIMUM eviction needed to fit, the headroom is noise: it drops
+ more than necessary, so an exact count would assert the headroom's value rather than
+ the fit's behaviour. Tests about the headroom set it explicitly.
+ """
+ monkeypatch.setattr(context_window, "_COMPACTION_HEADROOM_RATIO", 0.0)
+
+
+def test_rolling_fit_recounts_until_the_real_template_fits(no_compaction_headroom):
messages = [
{"role": "system", "content": "system"},
{"role": "user", "content": "one" * 40},
@@ -314,9 +330,132 @@ def test_rolling_fit_never_clips_an_irreducible_latest_turn():
assert fitted is messages
assert fitted == messages
+ # Unchanged messages, but not a silent None: the fit says WHY it gave up, so the
+ # user hears the single message is the problem rather than the history.
+ assert info is not None and info["fits"] is False
+ assert info["dropped_messages"] == 0
+ assert info["latest_turn_tokens"] > info["context_length"]
+
+
+def _length_counter(candidate):
+ return sum(len(str(message.get("content", ""))) for message in candidate)
+
+
+def test_evicted_messages_returns_dropped_turns_in_original_order(no_compaction_headroom):
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "one" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "two" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "latest"},
+ ]
+
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ gone = evicted_messages(messages, fitted)
+
+ assert info is not None
+ assert len(gone) == info["dropped_messages"]
+ assert gone == [messages[1], messages[2]]
+
+
+def test_evicted_messages_uses_identity_not_equality():
+ """Two byte-identical turns must not collapse into one.
+
+ An equality diff reports BOTH copies as evicted when only the older one was, so
+ downstream acts on a turn the model can still see.
+ """
+ first = {"role": "user", "content": "same question"}
+ second = {"role": "user", "content": "same question"}
+ before = [first, {"role": "assistant", "content": "reply"}, second]
+ after = [second]
+
+ gone = evicted_messages(before, after)
+
+ assert len(gone) == 2
+ assert gone[0] is first
+ assert all(message is not second for message in gone)
+
+
+def test_group_turns_matches_the_unit_truncation_drops():
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "ask"},
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "c1"}]},
+ {"role": "tool", "tool_call_id": "c1", "content": "result"},
+ {"role": "assistant", "content": "answer"},
+ {"role": "user", "content": "latest"},
+ ]
+
+ groups = group_turns(messages)
+
+ assert [[message["role"] for message in group] for group in groups] == [
+ ["system"],
+ ["user"],
+ ["assistant", "tool", "assistant"],
+ ["user"],
+ ]
+
+
+def test_reserve_tokens_does_not_trim_a_prompt_that_already_fits():
+ """The reserve must never be what causes eviction.
+
+ A conversation inside the window comes back untouched even when the reserve would
+ not fit alongside it, or recall would start evicting chats nowhere near the limit.
+ """
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "short"},
+ {"role": "assistant", "content": "short answer"},
+ {"role": "user", "content": "latest"},
+ ]
+
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ reserve_tokens = 380,
+ )
+
+ assert fitted is messages
assert info is None
+def test_reserve_tokens_trims_further_once_trimming_is_needed(no_compaction_headroom):
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "one" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "two" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "latest"},
+ ]
+
+ _, plain = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ _, reserved = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ reserve_tokens = 200,
+ )
+
+ assert plain is not None and reserved is not None
+ assert reserved["dropped_messages"] > plain["dropped_messages"]
+ assert reserved["prompt_tokens_after"] < plain["prompt_tokens_after"]
+
+
def test_rolling_fit_keeps_original_when_protected_messages_still_do_not_fit():
latest = {"role": "user", "content": "latest" * 200}
messages = [
@@ -335,7 +474,114 @@ def test_rolling_fit_keeps_original_when_protected_messages_still_do_not_fit():
assert fitted is messages
assert fitted == messages
- assert info is None
+ assert info is not None and info["fits"] is False
+ # The partial eviction is deliberately NOT applied: the request fails either way,
+ # and dropping turns off a doomed request loses them for nothing.
+ assert info["dropped_messages"] == 0
+ assert info["prompt_tokens_after"] == info["prompt_tokens_before"]
+
+
+def test_an_irreducible_fit_says_WHOSE_turn_does_not_fit():
+ """A tool loop refits with the tool result appended.
+
+ The turn that will not fit is then output the user never wrote and cannot edit, so
+ "shorten this message" has no remedy. The role is what tells the two apart.
+ """
+ user_turn = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "what does this file contain"},
+ {"role": "assistant", "content": "reading it"},
+ {"role": "tool", "tool_call_id": "c1", "content": "output" * 200},
+ ]
+ _, info = fit_rolling_context(
+ user_turn,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ assert info["fits"] is False
+ assert info["latest_turn_role"] == "tool"
+
+ # And an ordinary overflowing user message still says so.
+ _, info = fit_rolling_context(
+ [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "latest" * 200},
+ ],
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ assert info["latest_turn_role"] == "user"
+
+
+def test_an_irreducible_fit_survives_a_template_that_refuses_a_lone_tool_result():
+ """The diagnosis is produced exactly where a tool loop is most likely to be.
+
+ Strict templates refuse to render a tool result on its own, so counting that slice
+ threw out of the fit and the caller fell back to the untrimmed request, telling the
+ client nothing on the one path this diagnosis exists for.
+ """
+
+ def strict_counter(messages):
+ if len(messages) == 1 and messages[0].get("role") == "tool":
+ raise RuntimeError("a tool result must follow an assistant tool call")
+ return _length_counter(messages)
+
+ messages = [
+ {"role": "user", "content": "read it"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"id": "c1", "function": {"name": "python", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "output" * 500},
+ ]
+ _, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = strict_counter,
+ )
+
+ assert info is not None and info["fits"] is False
+ assert info["latest_turn_role"] == "tool"
+ # Estimated rather than counted: an approximation beats no diagnosis at all.
+ assert info["latest_turn_tokens"] > 0
+
+
+def test_an_irreducible_fit_says_whether_the_message_or_the_history_is_at_fault():
+ """The two numbers that make the error actionable.
+
+ llama-server's error reports the WHOLE conversation's size and advises shortening
+ it, which cannot work when the latest turn alone is over the window.
+ """
+ huge_message = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "latest" * 200},
+ ]
+ _, info = fit_rolling_context(
+ huge_message,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ assert info["fits"] is False
+ assert info["latest_turn_tokens"] > info["context_length"]
+
+ # A conversation that fits reports nothing, not a fits:False dict a caller could
+ # mistake for a failure.
+ small = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "hello"},
+ ]
+ _, none_info = fit_rolling_context(
+ small,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+ assert none_info is None
# ---------------------------------------------------------------------------
@@ -596,3 +842,178 @@ def test_reasoning_clip_alone_prevents_middle_eviction():
assert body["max_tokens"] == max(
1024, int(8192 * (1.0 - routes_mod._OVERFLOW_PROMPT_TARGET_FRACTION))
)
+
+
+def test_compaction_headroom_does_not_trim_a_prompt_that_already_fits():
+ """Same rule as the reserve: headroom must never be what causes eviction.
+
+ The headroom makes a compaction take a chunk out in one go; charging it up front
+ would evict from chats that comfortably fit today.
+ """
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "short"},
+ {"role": "assistant", "content": "short answer"},
+ {"role": "user", "content": "latest"},
+ ]
+
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+
+ assert fitted is messages
+ assert info is None
+
+
+def test_compaction_leaves_headroom_below_the_budget():
+ """A compaction lands clear of the budget, not flush against it.
+
+ Trimming to the brim makes the boundary creep every turn: the client re-sends the
+ whole transcript, so an exactly fitted prompt is over again on the next turn.
+ """
+ messages = [{"role": "system", "content": "system"}]
+ for index in range(12):
+ messages.append({"role": "user", "content": f"question {index} " * 20})
+ messages.append({"role": "assistant", "content": f"answer {index} " * 20})
+ messages.append({"role": "user", "content": "latest"})
+
+ _, info = fit_rolling_context(
+ messages,
+ context_length = 800,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ )
+
+ assert info is not None
+ prompt_target = 800 - min(100, 800 // 4)
+ assert info["prompt_tokens_after"] <= prompt_target
+ # The point of the change: comfortably under, not just under.
+ assert info["prompt_tokens_after"] < prompt_target * 0.9
+
+
+def _long_thread(turns: int = 40):
+ """A thread several times its window, in turns big enough to be evicted as units."""
+ messages = [{"role": "system", "content": "system"}]
+ for index in range(turns):
+ messages.append({"role": "user", "content": f"question {index} " * 200})
+ messages.append({"role": "assistant", "content": f"answer {index} " * 200})
+ return messages
+
+
+def _fit_with_appended(
+ base,
+ appended,
+ sticky = 0,
+):
+ messages = list(base)
+ for index in range(appended):
+ messages.append({"role": "user", "content": f"follow up {index} " * 20})
+ messages.append({"role": "assistant", "content": f"reply {index} " * 20})
+ messages.append({"role": "user", "content": "latest"})
+ _, info = fit_rolling_context(
+ messages,
+ context_length = 8000,
+ max_tokens = 512,
+ count_tokens = _length_counter,
+ sticky_dropped = sticky,
+ )
+ return info
+
+
+def test_sticky_boundary_holds_still_while_short_turns_are_appended():
+ """After a compaction, ordinary turns do not push the boundary again.
+
+ The notice depends on this, and it is why the boundary is read back rather than
+ recomputed: the client re-sends the whole transcript, so a recomputed "keep the
+ newest N tokens" slides forward and every reply reports a fresh compaction.
+ """
+ base = _long_thread()
+ first = _fit_with_appended(base, 0)
+ assert first is not None and first["dropped_messages"] > 0
+
+ boundary = first["dropped_messages"]
+ # Not "forever": the appended turns consume the headroom and the next test pins
+ # down that it eventually moves. A handful of turns, against a baseline that moved
+ # on nearly every one.
+ for appended in range(1, 6):
+ info = _fit_with_appended(base, appended, sticky = boundary)
+ assert info is not None
+ assert (
+ info["dropped_messages"] == boundary
+ ), f"the boundary moved after {appended} appended turns"
+
+
+def test_sticky_boundary_moves_again_once_the_headroom_is_used_up():
+ """It holds still, but it does not hold forever: enough new turns re-compact."""
+ base = _long_thread()
+ boundary = _fit_with_appended(base, 0)["dropped_messages"]
+
+ moved = None
+ for appended in range(1, 60):
+ info = _fit_with_appended(base, appended, sticky = boundary)
+ if info["dropped_messages"] > boundary:
+ moved = appended
+ break
+
+ assert moved is not None, "the boundary never moved, so the window would overflow"
+ assert moved > 4, f"the boundary moved again after only {moved} turns"
+
+
+def test_sticky_boundary_never_causes_eviction_on_a_thread_that_fits():
+ """A stale boundary from a longer branch must not evict a conversation that fits.
+
+ After a rollback the saved boundary describes a branch that no longer exists. The
+ fit may reapply it, but never report a compaction on a prompt that already fits.
+ """
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "short"},
+ {"role": "assistant", "content": "short answer"},
+ {"role": "user", "content": "latest"},
+ ]
+
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 4000,
+ max_tokens = 100,
+ count_tokens = _length_counter,
+ sticky_dropped = 40,
+ )
+
+ assert fitted is messages
+ assert info is None
+
+
+def test_the_compaction_headroom_needs_a_boundary_to_be_worth_it():
+ """Cutting deeper than needed buys quiet turns only if the cut is remembered.
+
+ An incognito chat, an API request with no persisted thread, or a request whose turns
+ are not saved gets neither the boundary back nor a recall of what went, so there the
+ headroom is simply less history than plain eviction would have kept, on every
+ overflow, and turning the archive off did not restore the old behaviour.
+ """
+ messages = []
+ for index in range(20):
+ messages.append({"role": "user", "content": f"q{index} " + "u" * 80})
+ messages.append({"role": "assistant", "content": f"a{index} " + "a" * 80})
+ messages.append({"role": "user", "content": "latest"})
+
+ def _fit(keeps_boundary):
+ return fit_rolling_context(
+ list(messages),
+ context_length = 2000,
+ max_tokens = 200,
+ count_tokens = _length_counter,
+ keeps_boundary = keeps_boundary,
+ )
+
+ plain, plain_info = _fit(False)
+ sticky, sticky_info = _fit(True)
+
+ assert plain_info["fits"] and sticky_info["fits"]
+ # The one that can restore its boundary is the one that pays for headroom.
+ assert sticky_info["dropped_messages"] > plain_info["dropped_messages"]
+ assert len(plain) > len(sticky)
diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.py
new file mode 100644
index 00000000000..39ce78affd9
--- /dev/null
+++ b/studio/backend/tests/test_conversation_archive.py
@@ -0,0 +1,1925 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The archive behind rolling-context compaction: what it keeps, and what it must not touch."""
+
+import copy
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from core.rag import conversation_archive, retrieval, store # noqa: E402
+from storage import rag_db # noqa: E402
+
+THREAD = "thread-abc"
+
+
+def _turn(question, answer):
+ return [
+ {"role": "user", "content": question},
+ {"role": "assistant", "content": answer},
+ ]
+
+
+def _save_thread(
+ thread_id,
+ turns,
+ *,
+ append = False,
+):
+ """Persist a transcript the way the chat history route does.
+
+ ``append`` matters: replacing the rows on every archive call would leave only the
+ newest turn saved and the branch filter would reject everything archived earlier.
+ Tests that rewind a thread pass append=False to replace.
+ """
+ from storage import studio_db
+
+ studio_db.upsert_chat_thread(
+ {
+ "id": thread_id,
+ "title": "t",
+ "modelType": "base",
+ "modelId": "local-model",
+ "createdAt": 1,
+ }
+ )
+ existing = len(studio_db.list_chat_messages(thread_id) or []) if append else 0
+ rows = [
+ {
+ "id": f"{thread_id}-{existing + index}",
+ "threadId": thread_id,
+ "role": message["role"],
+ "content": [{"type": "text", "text": message["content"]}],
+ "createdAt": existing + index + 2,
+ }
+ for index, message in enumerate(turns)
+ ]
+ if append:
+ for row in rows:
+ studio_db.upsert_chat_message(row)
+ return
+ # A rewind, through the same prune_missing sync the PUT route uses. Deleting the
+ # thread instead would tombstone its id, and recreating a tombstoned id raises.
+ studio_db.sync_chat_messages(thread_id, rows, prune_missing = True)
+
+
+def _archive(
+ messages,
+ thread_id = THREAD,
+ *,
+ persist = True,
+):
+ """The module opens its own connection to the same temp DB the fixture points at.
+
+ Archiving requires the thread to exist in studio.db, so the default persists a
+ matching transcript: only a persisted thread can be deleted, and an unreachable
+ archive is the temporary-chat leak. ``persist=False`` exercises the refusal.
+ """
+ if persist:
+ _save_thread(thread_id, messages, append = True)
+ return conversation_archive.archive_turns(thread_id, messages)
+
+
+def conn(rag_home, rag_conn, stub_embeddings):
+ return rag_conn
+
+
+def test_evicted_turns_are_archived_under_the_conversation_scope(conn):
+ written = _archive(_turn("what is a duck", "a waterfowl"))
+
+ scope = store.conversation_archive_scope(THREAD)
+ assert written == 1
+ documents = store.list_documents(conn, scope)
+ assert len(documents) == 1
+ assert "earlier turn" in documents[0]["filename"]
+
+
+def test_re_archiving_the_same_turns_writes_nothing(conn):
+ """The same turns are evicted again on every later request, so repeats must be free."""
+ turn = _turn("what is a duck", "a waterfowl")
+ first = _archive(turn)
+ second = _archive(turn)
+
+ scope = store.conversation_archive_scope(THREAD)
+ assert (first, second) == (1, 0)
+ assert len(store.list_documents(conn, scope)) == 1
+
+
+def test_archive_accumulates_across_compaction_epochs(conn):
+ """Compaction N must still find what compaction 1 evicted.
+
+ Latest-compaction-only measured 0.058 against 0.450 cumulative, so this is the
+ property the feature rests on.
+ """
+ _archive(_turn("tell me about pelicans", "they have large bills"))
+ _archive(_turn("tell me about otters", "they use tools"))
+ _archive(_turn("tell me about pangolins", "they have scales"))
+
+ scope = store.conversation_archive_scope(THREAD)
+ assert len(store.list_documents(conn, scope)) == 3
+
+ found = conversation_archive.recall(THREAD, "pelicans")
+
+ assert found is not None
+ text, _sources = found
+ assert "pelicans" in text
+
+
+def test_whole_document_context_never_sees_archived_turns(conn):
+ """The hazard that decided the scope layout.
+
+ Thread-attached documents are injected in full on every request, so an archive in the
+ thread scope would re-inject the evicted history each turn and undo itself.
+ """
+ _archive(_turn("secret archived question", "secret archived answer"))
+
+ thread_scope = store.thread_scope(THREAD)
+ archive_scope = store.conversation_archive_scope(THREAD)
+ assert thread_scope != archive_scope
+ assert store.list_documents(conn, thread_scope) == []
+
+
+def test_archive_skips_instructions_and_its_own_injections(conn):
+ written = _archive(
+ [
+ {"role": "system", "content": "you are a helpful assistant"},
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "conv_recall_1"}]},
+ {"role": "tool", "tool_call_id": "conv_recall_1", "content": "recalled text"},
+ ],
+ )
+
+ assert written == 0
+ assert store.list_documents(conn, store.conversation_archive_scope(THREAD)) == []
+
+
+def test_recall_returns_the_gold_turn(conn):
+ _archive(_turn("how do I bake sourdough", "start a starter"))
+ _archive(_turn("what is the capital of Peru", "Lima"))
+
+ found = conversation_archive.recall(THREAD, "sourdough")
+
+ assert found is not None
+ text, sources = found
+ assert "sourdough" in text
+ assert sources
+
+
+def test_recall_degrades_to_lexical_when_dense_retrieval_raises(monkeypatch, conn):
+ """No embedder must mean weaker recall, never a broken chat."""
+ _archive(_turn("how do I bake sourdough", "start a starter"))
+
+ real_hybrid = retrieval.retrieve_hybrid
+
+ def only_lexical_works(
+ conn_,
+ scope,
+ query,
+ *,
+ k = None,
+ model_name = None,
+ mode = "hybrid",
+ ):
+ if mode != "lexical":
+ raise RuntimeError("no embedding backend available")
+ return real_hybrid(conn_, scope, query, k = k, model_name = model_name, mode = mode)
+
+ monkeypatch.setattr(retrieval, "retrieve_hybrid", only_lexical_works)
+ found = conversation_archive.recall(THREAD, "sourdough")
+
+ assert found is not None
+ assert "sourdough" in found[0]
+
+
+def test_archive_is_a_noop_when_rag_is_unavailable(monkeypatch, conn):
+ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", False)
+
+ assert conversation_archive.archive_turns(THREAD, _turn("q", "a")) == 0
+ assert conversation_archive.recall(THREAD, "q") is None
+ assert conversation_archive.has_archive(THREAD) is False
+
+
+def test_archive_is_a_noop_when_disabled(monkeypatch, conn):
+ monkeypatch.setattr(conversation_archive.config, "CONVERSATION_ARCHIVE", False)
+
+ assert conversation_archive.archive_turns(THREAD, _turn("q", "a")) == 0
+ assert conversation_archive.recall(THREAD, "q") is None
+
+
+def test_archived_turns_are_hidden_from_the_documents_list(conn):
+ _archive(_turn("what is a duck", "a waterfowl"))
+
+ listed = store.list_all_documents(conn)
+
+ assert all(not d["scope"].startswith(store.CONVERSATION_ARCHIVE_PREFIX) for d in listed)
+
+
+def test_the_transcript_is_never_mutated(conn):
+ messages = _turn("what is a duck", "a waterfowl")
+ original = copy.deepcopy(messages)
+
+ _archive(messages)
+ conversation_archive.recall(THREAD, "duck")
+
+ assert messages == original
+
+
+def test_has_archive_reports_whether_anything_was_kept(conn):
+ assert conversation_archive.has_archive(THREAD) is False
+ _archive(_turn("what is a duck", "a waterfowl"))
+ assert conversation_archive.has_archive(THREAD) is True
+
+
+def test_render_turn_keeps_both_sides_together():
+ rendered = conversation_archive.render_turn(_turn("what is a duck", "a waterfowl"))
+
+ assert "user: what is a duck" in rendered
+ assert "assistant: a waterfowl" in rendered
+
+
+def test_render_turn_truncates_a_huge_tool_result():
+ rendered = conversation_archive.render_turn(
+ [{"role": "tool", "tool_call_id": "c1", "content": "x" * 20000}]
+ )
+
+ assert len(rendered) < 20000
+ assert rendered.endswith("...")
+
+
+def test_delete_for_thread_drops_the_archive(conn):
+ _archive(_turn("what is a duck", "a waterfowl"))
+
+ removed = conversation_archive.delete_for_thread(THREAD)
+
+ assert removed == 1
+ assert store.list_documents(conn, store.conversation_archive_scope(THREAD)) == []
+
+
+def test_recall_finds_a_rare_token_buried_in_boilerplate(conn):
+ """Lexical first, because recalling a conversation is mostly exact matching.
+
+ Measured on a 30-turn walkthrough with identical wrapper text per turn: the needle
+ chunk ranked 3rd lexically at any k, was never returned by dense retrieval, and RRF
+ pushed it to 16th. Hybrid alone lost the answer, so this pins the ordering.
+ """
+ for index in range(1, 9):
+ code = " Internal tracking code: VULPINE-9134-QK." if index == 1 else ""
+ _archive(
+ [
+ {
+ "role": "user",
+ "content": f"Here is section {index} of the climate change article."
+ f"{code} Reply with one short sentence naming its main topic.",
+ },
+ {
+ "role": "assistant",
+ "content": f"Section {index} is about climate change impacts.",
+ },
+ ],
+ thread_id = "needle-thread",
+ )
+
+ found = conversation_archive.recall(
+ "needle-thread",
+ "Earlier I gave you section 1 and it carried an internal tracking code. "
+ "What was that exact tracking code?",
+ )
+
+ assert found is not None
+ assert "VULPINE-9134-QK" in found[0]
+
+
+def test_recall_does_not_resurrect_a_turn_the_user_rolled_back_past(conn, monkeypatch):
+ """Editing an earlier message rewinds the thread onto a new branch.
+
+ The archive is append-only and still holds the abandoned continuation, so without a
+ branch check a recall returns a turn that never happened here. Verified live.
+ """
+ kept = [
+ {"role": "user", "content": "section one, code KEEPME-1111"},
+ {"role": "assistant", "content": "noted section one"},
+ ]
+ rolled_back = [
+ {"role": "user", "content": "section two, code GONEAWAY-2222"},
+ {"role": "assistant", "content": "noted section two"},
+ ]
+ _archive(kept, thread_id = "branch-thread")
+ _archive(rolled_back, thread_id = "branch-thread")
+ # The saved thread now holds only the surviving branch.
+ _save_thread("branch-thread", kept)
+
+ survived = conversation_archive.recall("branch-thread", "KEEPME-1111")
+ abandoned = conversation_archive.recall("branch-thread", "GONEAWAY-2222")
+
+ assert survived is not None and "KEEPME-1111" in survived[0]
+ # Recall has no relevance floor, so this query can still return the surviving turn.
+ # What matters is that the rolled-back content itself never comes back.
+ assert abandoned is None or "GONEAWAY-2222" not in abandoned[0]
+ assert "GONEAWAY-2222" not in (survived[0] or "")
+
+
+def test_recall_filters_to_the_ACTIVE_branch_not_the_whole_stored_thread(conn):
+ """Retry keeps the replaced response as a sibling, and siblings are stored rows.
+
+ Editing prunes the abandoned rows, so thread-wide filtering suffices there. Retry
+ keeps both responses on purpose, so the thread-wide blob still contains the one the
+ user replaced, and only the branch the request was sent on separates them.
+ """
+ live = [
+ {"role": "user", "content": "what is the code, code KEEPME-1111"},
+ {"role": "assistant", "content": "the code is KEEPME-1111"},
+ ]
+ retried_away = [
+ {"role": "user", "content": "what is the code, code KEEPME-1111"},
+ {"role": "assistant", "content": "the code is SIBLING-3333"},
+ ]
+ _archive(live, thread_id = "retry-thread")
+ _archive(retried_away, thread_id = "retry-thread")
+ # Both branches remain stored, which is exactly what Retry leaves behind.
+ _save_thread("retry-thread", live)
+ _save_thread("retry-thread", retried_away, append = True)
+
+ # Thread-wide filtering cannot reject the sibling: its text is genuinely in the DAG.
+ thread_wide = conversation_archive.recall("retry-thread", "SIBLING-3333")
+ assert thread_wide is not None and "SIBLING-3333" in thread_wide[0]
+
+ # Told which branch this is, it is rejected while the live answer still comes back.
+ on_branch = conversation_archive.recall("retry-thread", "SIBLING-3333", branch_messages = live)
+ assert on_branch is None or "SIBLING-3333" not in on_branch[0]
+ survived = conversation_archive.recall("retry-thread", "KEEPME-1111", branch_messages = live)
+ assert survived is not None and "KEEPME-1111" in survived[0]
+
+
+def test_the_reply_that_FOLLOWS_a_forced_recall_is_still_archived(conn):
+ """group_turns keeps a tool call, its result and the reply after it in one group.
+
+ Rejecting the whole group over our own injection threw away the model's answer, so a
+ later search found what was asked and never what was said, on compaction turns.
+ """
+ evicted = [
+ {"role": "user", "content": "what was the passphrase"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "conv_recall_1",
+ "function": {"name": "search_conversation", "arguments": '{"query": "pass"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "conv_recall_1", "content": "<chunk>RETRIEVED</chunk>"},
+ {"role": "assistant", "content": "The passphrase you set earlier was SWORDFISH-42."},
+ ]
+ _save_thread("recall-turn-thread", evicted, append = True)
+
+ assert conversation_archive.archive_turns("recall-turn-thread", evicted) == 2
+
+ found = conversation_archive.recall(
+ "recall-turn-thread", "SWORDFISH-42", branch_messages = evicted
+ )
+ assert found is not None
+ assert "SWORDFISH-42" in found[0]
+ # The retrieved passage itself is still kept out, or the archive feeds on itself.
+ assert "RETRIEVED" not in found[0]
+ assert (
+ conversation_archive.recall("recall-turn-thread", "RETRIEVED", branch_messages = evicted)
+ is None
+ or "RETRIEVED"
+ not in conversation_archive.recall(
+ "recall-turn-thread", "RETRIEVED", branch_messages = evicted
+ )[0]
+ )
+
+
+def test_deleting_a_thread_works_without_sqlite_vec(conn, monkeypatch):
+ """An archive is only written while vec0 loads, but it can stop loading afterwards.
+
+ A venv change is enough (common on macOS), and a delete that silently does nothing
+ leaves the turns on disk, ready to answer again once the extension loads.
+ """
+ turns = _turn("what is the passphrase", "the passphrase is VECGONE-2020")
+ _save_thread("vecless-thread", turns, append = True)
+ assert conversation_archive.archive_turns("vecless-thread", turns) == 1
+
+ def no_vec():
+ raise rag_db.RagExtensionUnavailable("vec0 will not load")
+
+ monkeypatch.setattr(rag_db, "get_connection", no_vec)
+ removed = conversation_archive.delete_for_thread("vecless-thread")
+ monkeypatch.undo()
+
+ assert removed == 1
+ # And with the extension back, nothing of that conversation is left to find.
+ assert conversation_archive.has_archive("vecless-thread") is False
+ assert conversation_archive.recall("vecless-thread", "VECGONE-2020") is None
+
+
+def test_a_turns_CHUNKS_must_all_sit_in_the_same_place_on_the_branch(conn):
+ """The chunks of one turn are consecutive slices of one rendering.
+
+ Validating them independently reassembles a turn from parts that never sat together:
+ head on the current answer, tail on a later message repeating what the edit removed.
+ """
+ rows = [
+ {
+ "text": "user: How do I deploy?\nassistant: Run the deploy script from the release branch."
+ },
+ {"text": "assistant: Never deploy on a Friday afternoon."},
+ ]
+ edited_with_a_later_echo = [
+ {"role": "user", "content": "How do I deploy?"},
+ {
+ "role": "assistant",
+ "content": "Run the deploy script from the release branch. Any day is fine.",
+ },
+ {"role": "user", "content": "What was that old rule of thumb?"},
+ {"role": "assistant", "content": "Never deploy on a Friday afternoon."},
+ ]
+ intact = [
+ {"role": "user", "content": "How do I deploy?"},
+ {
+ "role": "assistant",
+ "content": (
+ "Run the deploy script from the release branch.\n"
+ "Never deploy on a Friday afternoon."
+ ),
+ },
+ {"role": "user", "content": "Thanks"},
+ ]
+
+ # Each chunk on its own still matches somewhere: that is exactly the trap.
+ texts = conversation_archive.branch_message_texts(edited_with_a_later_echo)
+ assert all(conversation_archive._on_live_branch(row["text"], texts) for row in rows)
+ # As one document sharing a run, it is correctly rejected.
+ assert conversation_archive._document_matches_one_run(rows, texts) is False
+ # And a turn that really is still there is still accepted.
+ assert (
+ conversation_archive._document_matches_one_run(
+ rows, conversation_archive.branch_message_texts(intact)
+ )
+ is True
+ )
+
+
+def test_a_turns_CHUNKS_cannot_spill_into_the_message_after_the_turn(conn):
+ """The run is bounded by the MESSAGES the turn was rendered from, not by its lines.
+
+ A turn is two or three messages however long it is, so bounding by line count let a
+ long answer's tail be satisfied well outside the turn. Here the edit removes the end
+ of the answer and the next message repeats it, the shape of a short correction.
+ Chunks are shaped as the chunker produces them, so a continuation starts mid-message.
+ """
+ rows = [
+ {
+ "text": "user: how do I deploy\nassistant: Run the deploy script from the release branch."
+ },
+ {"text": "Never deploy on a Friday afternoon."},
+ ]
+ edited = [
+ {"role": "user", "content": "how do I deploy"},
+ {"role": "assistant", "content": "Run the deploy script from the release branch."},
+ {"role": "user", "content": "Never deploy on a Friday afternoon."},
+ ]
+ intact = [
+ {"role": "user", "content": "how do I deploy"},
+ {
+ "role": "assistant",
+ "content": (
+ "Run the deploy script from the release branch.\n"
+ "Never deploy on a Friday afternoon."
+ ),
+ },
+ {"role": "user", "content": "thanks"},
+ ]
+
+ assert (
+ conversation_archive._document_matches_one_run(
+ rows, conversation_archive.branch_message_texts(edited)
+ )
+ is False
+ )
+ # The same two chunks, with the answer still whole, are still accepted.
+ assert (
+ conversation_archive._document_matches_one_run(
+ rows, conversation_archive.branch_message_texts(intact)
+ )
+ is True
+ )
+
+
+def test_a_search_the_MODEL_asked_for_is_not_archived_as_new_history():
+ """`_is_injected` knows this feature's own ids, and the model's searches carry none.
+
+ A model-emitted `search_conversation` gets an ordinary `call_N` id from the parser, so
+ both the call and the passages it retrieved were indexed as fresh conversation. A
+ second search then archived the first one's output inside its own, one nesting level
+ per distinct search, each copy competing for the four recall slots.
+
+ Removed by NAME, and only the retrieval parts: the reply that follows a search is real
+ conversation, and an assistant message can carry an ordinary call beside the search.
+ """
+ from core.rag import conversation_archive as archive
+
+ recalled = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_0",
+ "function": {"name": "search_conversation", "arguments": '{"query":"pass"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_0", "content": "<chunk>RETRIEVEDPASSAGE</chunk>"},
+ {"role": "assistant", "content": "It was ZQXVARA123."},
+ ]
+
+ rendered = archive.render_turn(archive._archivable(recalled))
+ assert "RETRIEVEDPASSAGE" not in rendered
+ assert "ZQXVARA123" in rendered
+
+ # A retrieval call beside an ordinary one loses only the retrieval half.
+ mixed = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "call_0", "function": {"name": "search_conversation", "arguments": "{}"}},
+ {"id": "call_1", "function": {"name": "terminal", "arguments": '{"cmd":"ls"}'}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_0", "content": "<chunk>RETRIEVEDPASSAGE</chunk>"},
+ {"role": "tool", "tool_call_id": "call_1", "content": "total 12"},
+ ]
+
+ mixed_rendered = archive.render_turn(archive._archivable(mixed))
+ assert "RETRIEVEDPASSAGE" not in mixed_rendered
+ assert "terminal" in mixed_rendered
+ assert "total 12" in mixed_rendered
+
+
+def test_swapping_the_tool_retires_the_archived_call():
+ """Which tool ran is part of what the turn says, so it has to be part of the probe.
+
+ The label `render_turn` writes ("assistant called terminal: <args>") was stripped
+ whole, name included, leaving only the arguments to match. A retry that kept the
+ arguments and changed the tool therefore left the archived pre-edit turn eligible, and
+ it could be recalled as though the old call had happened on this branch. `_probe_text`
+ renders a live call as "<name> <arguments>", so the name is there to be required.
+ """
+ from core.rag import conversation_archive as archive
+
+ archived = archive.render_turn(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "function": {"name": "terminal", "arguments": '{"cmd":"ls -la /srv"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "total 12"},
+ ]
+ )
+
+ def _branch(tool):
+ return [
+ archive._normalise(archive._probe_text(message))
+ for message in [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "function": {"name": tool, "arguments": '{"cmd":"ls -la /srv"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "total 12"},
+ ]
+ ]
+
+ assert archive._on_live_branch(archived, _branch("terminal")) is True
+ assert archive._on_live_branch(archived, _branch("python")) is False
+
+
+def test_the_tool_call_exemption_ends_where_the_call_does():
+ """The exemption belongs to the CALL, not to the rest of the message.
+
+ A stored tool call cannot line up character for character with the live text, because
+ the store keeps arguments as an object and offers both JSON spellings, so the cursor
+ after one is not exact and the anchors have to be relaxed. Left set for the remainder
+ of the message, an assistant turn carrying both a call and text stayed matched after a
+ correction was appended to that text, and the pre-edit turn was still recallable.
+ Once an ordinary text probe has matched, the cursor is exact again.
+ """
+ from core.rag import conversation_archive as archive
+
+ probes = [("search_conversation", True), ("old answer", False)]
+
+ def _eligible(message):
+ found = archive._scan_probes(probes, [message], 0, 1)
+ if found is None:
+ return False
+ position, cursor, opened_at, partial, _opened_index = found
+ return not opened_at and (partial or cursor >= len([message][position]))
+
+ assert _eligible('{"tool":"search_conversation"}\nold answer') is True
+ assert _eligible('{"tool":"search_conversation"}\nold answer, correction: new answer') is False
+
+
+def test_a_line_inserted_INTO_an_archived_turn_retires_it():
+ """An edit that adds a line BETWEEN two archived lines is still an edit.
+
+ The two anchors either side of this covered an edit that prepends to a message the run
+ stepped into and one that appends to a message it is leaving. A correction dropped
+ between two archived lines matched both probes with the new line sitting unexamined in
+ the gap, so the pre-edit turn stayed recallable and could be quoted back as current.
+
+ A label `render_turn` wrote is still allowed in that gap, or a pasted chat log carrying
+ its own "user:" lines would retire turns nobody touched.
+ """
+ from core.rag import conversation_archive as archive
+
+ probes = [("A: drain traffic", False), ("B: flip the flag", False)]
+
+ assert archive._scan_probes(probes, ["A: drain traffic\nB: flip the flag"], 0, 1) is not None
+ assert (
+ archive._scan_probes(
+ probes, ["A: drain traffic\ncorrection: hold on\nB: flip the flag"], 0, 1
+ )
+ is None
+ )
+ assert (
+ archive._scan_probes(probes, ["A: drain traffic\nuser: B: flip the flag"], 0, 1) is not None
+ )
+
+
+def test_a_pasted_transcript_cannot_widen_a_turns_run(conn):
+ """Counting role labels counts lines the USER wrote, not just the renderer's.
+
+ A pasted chat log carries lines that look exactly like `render_turn`'s, each widening
+ the run by a message, enough for the message after an edited turn to supply what the
+ edit removed. The turn's real size is recorded when it is archived.
+ """
+ rows = [
+ {"text": "user: look at this log\nassistant: Here is what it says:\nuser: hello there"},
+ {"text": "The fix is to restart the worker."},
+ ]
+ edited = conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "look at this log"},
+ {"role": "assistant", "content": "Here is what it says:\nuser: hello there"},
+ {"role": "user", "content": "The fix is to restart the worker."},
+ ]
+ )
+ intact = conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "look at this log"},
+ {
+ "role": "assistant",
+ "content": (
+ "Here is what it says:\nuser: hello there\nThe fix is to restart the worker."
+ ),
+ },
+ ]
+ )
+
+ # Two messages, whatever the rendered text looks like.
+ assert conversation_archive._document_matches_one_run(rows, edited, 2) is False
+ assert conversation_archive._document_matches_one_run(rows, intact, 2) is True
+
+
+def test_an_archived_turn_records_how_many_messages_it_came_from(conn):
+ """The count has to reach the database, or the bound falls back on every recall."""
+ from core.rag import store
+
+ thread_id = "sized-archive"
+ _save_thread(thread_id, [{"role": "user", "content": "hi"}])
+ written = conversation_archive.archive_turns(
+ thread_id,
+ [
+ {"role": "user", "content": "what is the deploy code"},
+ {"role": "assistant", "content": "the deploy code is 5150"},
+ ],
+ )
+ assert written == 1
+
+ row = conn.execute(
+ "SELECT archive_messages FROM documents WHERE scope = ?",
+ (store.conversation_archive_scope(thread_id),),
+ ).fetchone()
+ assert row["archive_messages"] == 2
+
+
+def test_one_turn_archived_twice_at_once_is_stored_once(conn, monkeypatch):
+ """Two generations compacting the same thread both clear the hash check.
+
+ The embedding pass sits between the check and the insert, and `(scope, sha256)` is a
+ plain index, so both wrote and the duplicate took two of the few recall slots.
+ """
+ import threading
+
+ from core.rag import embeddings, store
+ from storage import studio_db
+
+ thread_id = "concurrent-archive"
+ studio_db.upsert_chat_thread(
+ {
+ "id": thread_id,
+ "title": "t",
+ "modelType": "base",
+ "modelId": "m",
+ "createdAt": 1,
+ }
+ )
+ studio_db.sync_chat_messages(
+ thread_id,
+ [
+ {
+ "id": "m1",
+ "threadId": thread_id,
+ "role": "user",
+ "content": [{"type": "text", "text": "hello"}],
+ "createdAt": 2,
+ }
+ ],
+ )
+
+ barrier = threading.Barrier(2)
+ real_encode = embeddings.encode_with_identity
+
+ def slow_encode(texts, **kwargs):
+ # Both passes are inside the window: neither has inserted yet.
+ barrier.wait(timeout = 10)
+ return real_encode(texts, **kwargs)
+
+ monkeypatch.setattr(embeddings, "encode_with_identity", slow_encode)
+
+ evicted = [
+ {"role": "user", "content": "what is the deploy code"},
+ {"role": "assistant", "content": "the deploy code is 5150"},
+ ]
+ workers = [
+ threading.Thread(
+ target = lambda: conversation_archive.archive_turns(
+ thread_id, [dict(message) for message in evicted]
+ )
+ )
+ for _ in range(2)
+ ]
+ for worker in workers:
+ worker.start()
+ for worker in workers:
+ worker.join()
+
+ rows = conn.execute(
+ "SELECT COUNT(*) AS c FROM documents WHERE scope = ?",
+ (store.conversation_archive_scope(thread_id),),
+ ).fetchone()
+ assert rows["c"] == 1
+
+
+def test_a_LATER_turn_cannot_supply_a_line_the_edit_removed(conn):
+ """The branch check has to stay inside the turn it is checking.
+
+ Against one flattened transcript, any later message repeating the words satisfies a
+ missing line, so a short answer could survive being edited away.
+ """
+ archived = conversation_archive.render_turn(
+ [{"role": "user", "content": "Should I deploy?"}, {"role": "assistant", "content": "No"}]
+ )
+ edited_away = [
+ {"role": "user", "content": "Should I deploy?"},
+ {"role": "assistant", "content": "Yes"},
+ {"role": "user", "content": "Is the staging queue busy?"},
+ {"role": "assistant", "content": "No"},
+ ]
+ still_there = [
+ {"role": "user", "content": "Should I deploy?"},
+ {"role": "assistant", "content": "No"},
+ {"role": "user", "content": "Is the staging queue busy?"},
+ {"role": "assistant", "content": "Yes"},
+ ]
+
+ assert (
+ conversation_archive._on_live_branch(
+ archived, conversation_archive.branch_message_texts(edited_away)
+ )
+ is False
+ )
+ # And the turn that IS still there is still found, or the check is just "no".
+ assert (
+ conversation_archive._on_live_branch(
+ archived, conversation_archive.branch_message_texts(still_there)
+ )
+ is True
+ )
+
+
+def test_a_turn_whose_lines_were_REORDERED_is_no_longer_on_the_branch(conn):
+ """Independent line membership accepts a turn that was merely rearranged.
+
+ Every probe still occurs somewhere, so the pre-edit ordering would be served back.
+ """
+ original = [{"role": "assistant", "content": "REORDER-A first\nREORDER-B second"}]
+ archived = conversation_archive.render_turn(original)
+
+ same = conversation_archive.branch_message_texts(original)
+ swapped = conversation_archive.branch_message_texts(
+ [{"role": "assistant", "content": "REORDER-B second\nREORDER-A first"}]
+ )
+
+ assert conversation_archive._on_live_branch(archived, same) is True
+ assert conversation_archive._on_live_branch(archived, swapped) is False
+
+
+def test_a_tool_turn_with_BOTH_text_and_a_call_stays_on_its_branch(conn):
+ """Ordered matching only works if both sides agree on the order.
+
+ render_turn writes a tool call before any assistant text on the same message and the
+ result after it, so both transcript shapes (`tool_calls`, `tool-call` parts) must lay
+ a turn out the same way.
+ """
+ request_shape = [
+ {"role": "user", "content": "check the log"},
+ {
+ "role": "assistant",
+ "content": "I will read it now",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"cmd":"cat log"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "log contents here"},
+ ]
+ archived = conversation_archive.render_turn(request_shape)
+ stored_shape = [
+ {"role": "user", "content": [{"type": "text", "text": "check the log"}]},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "text", "text": "I will read it now"},
+ {
+ "type": "tool-call",
+ "toolName": "terminal",
+ "args": {"cmd": "cat log"},
+ "result": "log contents here",
+ },
+ ],
+ },
+ ]
+
+ assert conversation_archive._on_live_branch(
+ archived, conversation_archive.branch_message_texts(request_shape)
+ )
+ # The stored shape keeps arguments as an object, so its spacing is not the model's.
+ assert conversation_archive._on_live_branch(
+ archived, conversation_archive.branch_message_texts(stored_shape)
+ )
+
+
+def test_editing_ONE_chunk_of_a_long_turn_retires_the_whole_turn(conn):
+ """A turn longer than CHUNK_TOKENS is stored as several chunks of one document.
+
+ Per-chunk checking retires only the chunks carrying an edit, leaving untouched
+ earlier chunks of the same retired turn eligible. The archived unit is the turn.
+ """
+ # The head spans several chunks, so the FIRST chunk lies entirely inside the part
+ # that is never edited and passes a per-chunk check unchanged.
+ head = "opening CHUNKSPLIT-7373 marker. " + ("unchanged opening sentence. " * 300)
+ turn = [
+ {"role": "user", "content": "explain the deploy process"},
+ {"role": "assistant", "content": head + ("original ending sentence. " * 300)},
+ ]
+ _save_thread("chunk-thread", turn, append = True)
+ assert conversation_archive.archive_turns("chunk-thread", turn) == 1
+ # More than one chunk, or this test is not testing anything.
+ scope = store.conversation_archive_scope("chunk-thread")
+ document_ids = {
+ row["document_id"]
+ for row in conversation_archive.rag_db.get_connection()
+ .execute(
+ "SELECT document_id FROM chunks c JOIN documents d ON d.id = c.document_id "
+ "WHERE d.scope = ?",
+ (scope,),
+ )
+ .fetchall()
+ }
+ chunk_count = (
+ conversation_archive.rag_db.get_connection()
+ .execute(
+ "SELECT COUNT(*) AS n FROM chunks c JOIN documents d ON d.id = c.document_id "
+ "WHERE d.scope = ?",
+ (scope,),
+ )
+ .fetchone()["n"]
+ )
+ assert len(document_ids) == 1 and chunk_count > 1
+
+ # Same turn with its TAIL rewritten; the head holding the marker is untouched.
+ rewritten = [
+ turn[0],
+ {"role": "assistant", "content": head + ("a completely different ending. " * 300)},
+ ]
+ # The first chunk really is still on the branch: this is what per-chunk admitted.
+ first_chunk = (
+ conversation_archive.rag_db.get_connection()
+ .execute(
+ "SELECT c.text FROM chunks c JOIN documents d ON d.id = c.document_id "
+ "WHERE d.scope = ? ORDER BY c.chunk_index ASC LIMIT 1",
+ (scope,),
+ )
+ .fetchone()["text"]
+ )
+ assert conversation_archive._on_live_branch(
+ first_chunk, conversation_archive.branch_message_texts(rewritten)
+ )
+
+ found = conversation_archive.recall(
+ "chunk-thread", "CHUNKSPLIT-7373", branch_messages = rewritten
+ )
+
+ assert found is None
+
+
+def test_a_long_multi_line_tool_result_stays_on_its_branch(conn):
+ """render_turn caps a tool result and marks the cut with a truncation marker.
+
+ That result is ONE string of many newlines, so only its first line carries the "tool
+ result:" label while the marker is on its last, and nothing in a real transcript ends
+ in the marker: every archived tool turn over the cap was rejected as rolled back.
+ """
+ body = "opening line TOOLWALL-6060\n" + ("filler output line\n" * 400) + "trailing line"
+ group = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"cmd": "cat log"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": body},
+ ]
+ text = conversation_archive.render_turn(group)
+ assert text.endswith("...")
+ assert len(text.splitlines()) > 100
+
+ transcript = conversation_archive.branch_message_texts(group)
+
+ assert conversation_archive._on_live_branch(text, transcript) is True
+ # And an edit to the part that WAS archived still retires the copy.
+ edited = conversation_archive.branch_message_texts(
+ [
+ group[0],
+ {**group[1], "content": body.replace("opening line", "rewritten line")},
+ ]
+ )
+ assert conversation_archive._on_live_branch(text, edited) is False
+
+
+def test_recall_widens_past_a_wall_of_abandoned_branch_hits(conn):
+ """One over-fetch is not enough when the abandoned branch is long.
+
+ Rewinding a compacted continuation leaves enough stale turns to fill any fixed
+ candidate window, so a single fetch rejects the whole page and never looks at the
+ live match just below it, reporting nothing while the answer is in the archive.
+ """
+ # The live answer mentions the marker once, in a turn that is mostly other words.
+ live = _turn(
+ "where is the marker",
+ "the marker is WIDEN-5150 and the rest of this answer is about unrelated matters "
+ "such as scheduling, packaging, release notes and the weather in three cities",
+ )
+ # The abandoned branch repeats it, so these outrank the live turn lexically and fill
+ # any fixed candidate window ahead of it.
+ abandoned = [
+ _turn(
+ f"where is the marker attempt {index}",
+ f"WIDEN-5150 WIDEN-5150 WIDEN-5150 attempt {index} discarded",
+ )
+ for index in range(40)
+ ]
+
+ _save_thread("wall-thread", live, append = True)
+ conversation_archive.archive_turns("wall-thread", live)
+ for turn in abandoned:
+ # Stored as siblings, as Retry leaves them: on the thread, not on the branch.
+ _save_thread("wall-thread", turn, append = True)
+ conversation_archive.archive_turns("wall-thread", turn)
+
+ found = conversation_archive.recall("wall-thread", "WIDEN-5150", branch_messages = live)
+
+ assert found is not None
+ assert "the marker is WIDEN-5150" in found[0]
+ assert "discarded" not in found[0]
+
+
+def test_the_branch_transcript_carries_request_shaped_tool_calls(conn):
+ """A tool turn's arguments live in `tool_calls`, not in content, on the wire.
+
+ render_turn indexes them, so a branch blob built from content alone misses every
+ archived tool turn and filters the whole exchange out as rolled back.
+ """
+ branch = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "function": {"name": "terminal", "arguments": '{"cmd": "ls TOOLARG-7777"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOLARG-7777 listed"},
+ ]
+ _archive(branch, thread_id = "tool-branch-thread")
+ _save_thread("tool-branch-thread", [{"role": "user", "content": "unrelated"}])
+
+ found = conversation_archive.recall(
+ "tool-branch-thread", "TOOLARG-7777", branch_messages = branch
+ )
+
+ assert found is not None and "TOOLARG-7777" in found[0]
+
+
+def test_a_thread_that_was_never_persisted_is_never_archived(conn):
+ """The temporary-chat guarantee.
+
+ An incognito chat is never written to studio.db, yet the frontend still sends its
+ thread_id and the request carries no incognito flag. Archiving it would persist the
+ one conversation the user asked not to keep, where no deletion flow could reach it.
+ """
+ written = _archive(
+ [
+ {"role": "user", "content": "temporary section, code EPHEMERAL-4444"},
+ {"role": "assistant", "content": "noted"},
+ ],
+ thread_id = "temporary-thread",
+ persist = False,
+ )
+
+ assert written == 0
+ assert conversation_archive.has_archive("temporary-thread") is False
+ assert conversation_archive.recall("temporary-thread", "EPHEMERAL-4444") is None
+ # Same predicate the fit asks before reserving, so an unarchivable chat never pays
+ # for room to recall into.
+ assert conversation_archive.can_archive("temporary-thread") is False
+
+
+def test_a_thread_deleted_mid_ingest_does_not_leave_its_turns_behind(conn, monkeypatch):
+ """Deleting a chat while it is compacting must not resurrect the archive.
+
+ Cancellation is cooperative and the embedding pass between the liveness check and the
+ commit does not observe it, so a sweep in that window is undone by the commit, into a
+ scope no later delete can reach now the thread is gone.
+ """
+ from storage import studio_db
+
+ turns = _turn("what is the code", "the code is DELETED-9999")
+ _save_thread("doomed-thread", turns, append = True)
+
+ original = conversation_archive.embeddings.encode_with_identity
+
+ def delete_the_thread_mid_ingest(*args, **kwargs):
+ # The interleaving that matters: rows first, sweep last, both before this commit.
+ studio_db.delete_chat_threads(["doomed-thread"])
+ conversation_archive.delete_for_thread("doomed-thread")
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(
+ conversation_archive.embeddings, "encode_with_identity", delete_the_thread_mid_ingest
+ )
+
+ written = conversation_archive.archive_turns("doomed-thread", turns)
+
+ assert written == 0
+ assert conversation_archive.has_archive("doomed-thread") is False
+ assert conversation_archive.recall("doomed-thread", "DELETED-9999") is None
+
+
+def test_recall_is_unfiltered_when_the_thread_has_no_saved_transcript(conn):
+ """A thread archived earlier whose saved rows are gone still answers.
+
+ An empty transcript is absence of evidence, not evidence the turns are gone, so the
+ branch check must not silently disable recall for an existing archive.
+ """
+ _archive(
+ [
+ {"role": "user", "content": "unsaved section, code ORPHAN-3333"},
+ {"role": "assistant", "content": "noted"},
+ ],
+ thread_id = "unsaved-thread",
+ )
+ # Drop the saved rows, leaving the archive behind.
+ from storage import studio_db
+
+ studio_db.delete_chat_threads(["unsaved-thread"])
+
+ found = conversation_archive.recall("unsaved-thread", "ORPHAN-3333")
+
+ assert found is not None
+ assert "ORPHAN-3333" in found[0]
+
+
+def test_editing_only_the_assistant_half_retires_the_archived_turn(conn):
+ """A turn is archived as a unit, so it lives or dies as a unit.
+
+ Matching on the first surviving line kept serving the old answer: the unchanged user
+ line vouched for the whole turn.
+ """
+ original = [
+ {"role": "user", "content": "what is the launch code"},
+ {"role": "assistant", "content": "the launch code is STALEANSWER-9999"},
+ ]
+ _archive(original, thread_id = "edited-thread")
+ # The user keeps their question and rewrites the answer.
+ _save_thread(
+ "edited-thread",
+ [
+ {"role": "user", "content": "what is the launch code"},
+ {"role": "assistant", "content": "the launch code is FRESHANSWER-1111"},
+ ],
+ )
+
+ found = conversation_archive.recall("edited-thread", "STALEANSWER-9999")
+
+ assert found is None or "STALEANSWER-9999" not in found[0]
+
+
+def test_a_failed_chunk_write_leaves_the_turn_retryable(conn, monkeypatch):
+ """An empty 'completed' document would make the turn unarchivable forever.
+
+ `document_by_hash` skips whatever it finds, and the row says completed, so nothing
+ would ever retry it.
+ """
+ turns = _turn("what is a quokka", "a small marsupial")
+
+ def explode(*args, **kwargs):
+ raise RuntimeError("disk full")
+
+ # Restored by re-setting, not monkeypatch.undo(): fixtures share this instance, so
+ # undo() would also revert stub_embeddings and fail the retry for another reason.
+ real_add_chunks = store.add_chunks
+ monkeypatch.setattr(store, "add_chunks", explode)
+ assert _archive(turns, thread_id = "retry-thread") == 0
+ monkeypatch.setattr(store, "add_chunks", real_add_chunks)
+
+ # The retry succeeds, which it cannot do if a completed husk was left behind.
+ assert _archive(turns, thread_id = "retry-thread", persist = False) == 1
+ found = conversation_archive.recall("retry-thread", "quokka")
+ assert found is not None and "quokka" in found[0]
+
+
+def test_archived_tool_turns_keep_what_the_call_actually_did(conn):
+ """ "assistant called terminal" cannot answer "what did you run earlier?"."""
+ rendered = conversation_archive.render_turn(
+ [
+ {
+ "role": "assistant",
+ "content": "running the migration now",
+ "tool_calls": [
+ {
+ "function": {
+ "name": "terminal",
+ "arguments": '{"command": "alembic upgrade head"}',
+ }
+ }
+ ],
+ },
+ {"role": "tool", "content": "ok"},
+ ]
+ )
+
+ assert "terminal" in rendered
+ assert "alembic upgrade head" in rendered
+ assert "running the migration now" in rendered
+
+
+def test_an_archived_tool_turn_survives_the_branch_filter(conn):
+ """The two previous fixes together could make tool turns permanently unrecallable.
+
+ render_turn archives a tool turn as "assistant called X: args" and "tool result: ...",
+ while assistant-ui persists a structured tool-call part the flattener used to drop, so
+ with every archived line required in the transcript no tool turn could match.
+ """
+ from storage import studio_db
+
+ turn = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "function": {
+ "name": "terminal",
+ "arguments": '{"command": "alembic upgrade head"}',
+ }
+ }
+ ],
+ },
+ {"role": "tool", "content": "migration applied cleanly"},
+ ]
+ studio_db.upsert_chat_thread(
+ {
+ "id": "tool-thread",
+ "title": "t",
+ "modelType": "base",
+ "modelId": "local-model",
+ "createdAt": 1,
+ }
+ )
+ # Persisted the way the UI stores it: a structured part, not text.
+ studio_db.upsert_chat_message(
+ {
+ "id": "tool-thread-0",
+ "threadId": "tool-thread",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool-call",
+ "toolCallId": "c1",
+ "toolName": "terminal",
+ "args": {"command": "alembic upgrade head"},
+ "result": "migration applied cleanly",
+ }
+ ],
+ "createdAt": 2,
+ }
+ )
+ conversation_archive.archive_turns("tool-thread", turn)
+
+ found = conversation_archive.recall("tool-thread", "alembic upgrade head")
+
+ assert found is not None
+ assert "alembic" in found[0]
+
+
+def test_an_edit_past_the_probe_cutoff_still_retires_the_turn(conn):
+ """A prefix probe cannot see a change after its cut-off.
+
+ Rewriting a long answer's tail left the archived copy matching on its first 160
+ characters, so the stale text stayed eligible.
+ """
+ head = "the deployment steps are as follows and here is the full detail " * 4
+ original = [
+ {"role": "user", "content": "how do I deploy"},
+ {"role": "assistant", "content": head + "finally run OLDSTEP-7777"},
+ ]
+ _archive(original, thread_id = "tail-edit-thread")
+ # Same opening, different ending.
+ _save_thread(
+ "tail-edit-thread",
+ [
+ {"role": "user", "content": "how do I deploy"},
+ {"role": "assistant", "content": head + "finally run NEWSTEP-8888"},
+ ],
+ )
+
+ found = conversation_archive.recall("tail-edit-thread", "OLDSTEP-7777")
+
+ assert found is None or "OLDSTEP-7777" not in found[0]
+
+
+def test_a_failed_archive_marks_the_feature_degraded(conn, monkeypatch):
+ """And a later success clears it, so one bad moment is not permanent."""
+ from core.rag import embeddings
+
+ thread_id = "degraded-archive"
+ _save_thread(thread_id, [{"role": "user", "content": "hi"}])
+ turn = [
+ {"role": "user", "content": "what is the deploy code"},
+ {"role": "assistant", "content": "the deploy code is 5150"},
+ ]
+
+ assert conversation_archive.degraded() is False
+
+ real = embeddings.encode_with_identity
+
+ def no_embedder(*_args, **_kwargs):
+ raise RuntimeError("no embedding model could be started")
+
+ monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)
+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 0
+ assert conversation_archive.degraded() is True
+
+ monkeypatch.setattr(embeddings, "encode_with_identity", real)
+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 1
+ assert conversation_archive.degraded() is False
+
+
+def test_the_late_archive_cleanup_spares_a_recreated_thread(conn):
+ """DELETE removes the rows, then awaits the sandbox pass, and only then sweeps here.
+
+ Another tab can POST the same id in that window and its generation can archive turns
+ under it before the sweep runs. The sandbox pass re-checks for exactly that; this had
+ not, so the recreated chat silently lost its memory.
+ """
+ from routes import chat_history
+ from storage import studio_db
+
+ thread_id = "recreated-thread"
+ turns = _turn("what is the code", "the code is 5150")
+ _save_thread(thread_id, turns, append = True)
+ assert conversation_archive.archive_turns(thread_id, turns) == 1
+
+ chat_history._remove_conversation_archives([thread_id])
+
+ assert conversation_archive.has_archive(thread_id) is True
+
+ # And a thread that really is gone still has its archive dropped.
+ studio_db.delete_chat_threads([thread_id])
+ chat_history._remove_conversation_archives([thread_id])
+ assert conversation_archive.has_archive(thread_id) is False
+
+
+def test_an_answer_edited_by_appending_to_it_retires_the_archived_copy(conn):
+ """Keeping the old text and adding to it left every probe matching.
+
+ "No" becoming "No, correction: yes" is the ordinary way a person fixes an answer, and
+ the pre-edit copy stayed eligible: a later search could return "No" as the answer with
+ the correction nowhere in it.
+ """
+ rows = [{"text": "user: should I deploy on Friday\nassistant: No"}]
+ edited = conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "should I deploy on Friday"},
+ {"role": "assistant", "content": "No, correction: yes, the freeze lifted"},
+ ]
+ )
+ intact = conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "should I deploy on Friday"},
+ {"role": "assistant", "content": "No"},
+ ]
+ )
+
+ assert conversation_archive._document_matches_one_run(rows, edited, 2) is False
+ assert conversation_archive._document_matches_one_run(rows, intact, 2) is True
+
+
+def test_a_truncated_tool_result_may_still_end_mid_message(conn):
+ """render_turn cuts long tool results, so that probe is a prefix by design.
+
+ Demanding that the turn end where the live message does would retire every turn that
+ carried one.
+ """
+ marker = conversation_archive._TRUNCATION_MARKER
+ rows = [{"text": "user: run it\ntool result: " + "x" * 100 + marker}]
+ live = conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "run it"},
+ {"role": "tool", "content": "x" * 400},
+ ]
+ )
+
+ assert conversation_archive._document_matches_one_run(rows, live, 2) is True
+
+
+def test_an_answer_edited_by_prepending_to_it_retires_the_archived_copy(conn):
+ """The other side of the same edit: the old text is kept as a suffix.
+
+ "No" becoming "Correction: no" leaves the probe matching and ending exactly where the
+ live message does, so an end-only check still called the pre-edit copy live.
+ """
+ rows = [{"text": "user: should I deploy on Friday\nassistant: No"}]
+
+ def _live(answer):
+ return conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": "should I deploy on Friday"},
+ {"role": "assistant", "content": answer},
+ ]
+ )
+
+ assert conversation_archive._document_matches_one_run(rows, _live("Correction: no"), 2) is False
+ assert conversation_archive._document_matches_one_run(rows, _live("No"), 2) is True
+
+
+def test_a_tool_exchange_archived_mid_request_is_recallable(conn):
+ """What the branch filter costs when the branch is the client's messages alone.
+
+ The exchange was created by this request, evicted by a later refit, and archived. The
+ client never sent it, so filtering against those messages calls it an abandoned branch
+ and refuses it, and the model loses a tool result it still needs to answer.
+ """
+ thread_id = "toolrun-thread"
+ request_branch = [{"role": "user", "content": "find the deploy code in the repo"}]
+ _save_thread(thread_id, request_branch, append = True)
+
+ tool_exchange = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "grep", "arguments": '{"q": "deploy"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "config/deploy.yml: token ZQX-5150"},
+ ]
+ assert conversation_archive.archive_turns(thread_id, tool_exchange) == 1
+
+ assert (
+ conversation_archive.recall(thread_id, "ZQX-5150", top_k = 4, branch_messages = request_branch)
+ is None
+ )
+ assert (
+ conversation_archive.recall(
+ thread_id,
+ "ZQX-5150",
+ top_k = 4,
+ branch_messages = request_branch + tool_exchange,
+ )
+ is not None
+ )
+
+
+def test_an_edit_to_any_message_of_a_turn_retires_the_archived_copy(conn):
+ """Anchoring only the final message left the question editable underneath it.
+
+ The turn is checked as a whole, so every message it claims has to be accounted for
+ from its first character to its last, wherever the edit landed.
+ """
+ rows = [{"text": "user: should I deploy on Friday\nassistant: No"}]
+
+ def _live(question, answer = "No"):
+ return conversation_archive.branch_message_texts(
+ [
+ {"role": "user", "content": question},
+ {"role": "assistant", "content": answer},
+ ]
+ )
+
+ match = conversation_archive._document_matches_one_run
+ # The question, either side.
+ assert match(rows, _live("Actually, should I deploy on Friday"), 2) is False
+ assert match(rows, _live("should I deploy on Friday or wait"), 2) is False
+ # The answer, either side.
+ assert match(rows, _live("should I deploy on Friday", "Correction: no"), 2) is False
+ assert match(rows, _live("should I deploy on Friday", "No, correction: yes"), 2) is False
+ # And the turn as it was archived is still live.
+ assert match(rows, _live("should I deploy on Friday"), 2) is True
+
+
+def test_a_tool_call_message_is_exempt_from_the_character_anchors(conn):
+ """The store keeps a call as a structured part, so nothing can line up exactly.
+
+ The live text carries the tool name and BOTH spellings of the arguments, spaced and
+ compact, while the archived copy has one line of one of them. Demanding coverage there
+ would retire every tool turn in the archive.
+ """
+ live = conversation_archive.branch_message_texts(
+ [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool-call",
+ "toolCallId": "c1",
+ "toolName": "terminal",
+ "args": {"command": "alembic upgrade head"},
+ "result": "migration applied cleanly",
+ }
+ ],
+ }
+ ]
+ )
+ rows = [
+ {
+ "text": (
+ 'assistant called terminal: {"command": "alembic upgrade head"}\n'
+ "tool result: migration applied cleanly"
+ )
+ }
+ ]
+
+ assert conversation_archive._document_matches_one_run(rows, live, 1) is True
+
+
+def test_a_turn_is_re_embedded_when_the_embedder_changes(conn, monkeypatch):
+ """Dense search only reads documents whose embedder matches the query's.
+
+ Hashed and skipped, a turn archived under the previous model stayed invisible to every
+ paraphrased search for good, however often the client re-presented it.
+ """
+ from core.rag import embeddings, store
+
+ thread_id = "identity-thread"
+ turn = _turn("what is the deploy code", "the deploy code is 5150")
+ _save_thread(thread_id, turn, append = True)
+
+ identity = {"name": "st:model-a"}
+ real = embeddings.encode_with_identity
+ monkeypatch.setattr(
+ embeddings,
+ "encode_with_identity",
+ lambda texts, **kwargs: (real(texts, **kwargs)[0], identity["name"]),
+ )
+ monkeypatch.setattr(embeddings, "embedding_identity", lambda *_a, **_k: identity["name"])
+
+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 1
+ # Same turn, same hash, under an embedder the query side no longer asks for.
+ identity["name"] = "st:model-b"
+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 1
+
+ rows = conn.execute(
+ "SELECT embedding_model FROM documents WHERE scope = ?",
+ (store.conversation_archive_scope(thread_id),),
+ ).fetchall()
+ # Replaced, not duplicated.
+ assert [row["embedding_model"] for row in rows] == ["st:model-b"]
+
+ # And re-presenting it under the SAME embedder is still a no-op.
+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 0
+
+
+def test_a_first_compaction_embeds_its_turns_in_one_pass(conn, monkeypatch):
+ """Per group, a long chat's first compaction ran dozens of jobs back to back.
+
+ Both backends serialise them, so the reply could not start until the last one landed.
+ """
+ from core.rag import embeddings
+
+ thread_id = "batch-thread"
+ _save_thread(thread_id, _turn("hello", "hi"), append = True)
+
+ calls = []
+ real = embeddings.encode_with_identity
+
+ def counted(texts, **kwargs):
+ calls.append(len(texts))
+ return real(texts, **kwargs)
+
+ monkeypatch.setattr(embeddings, "encode_with_identity", counted)
+
+ evicted = []
+ for index in range(12):
+ evicted.append({"role": "user", "content": f"question number {index} about the deploy"})
+ evicted.append({"role": "assistant", "content": f"answer number {index}, code {index}"})
+
+ assert conversation_archive.archive_turns(thread_id, evicted) == 12
+ assert len(calls) == 1
+ assert calls[0] >= 12
+
+
+def test_the_deleted_conversation_goes_even_when_its_id_comes_back(conn):
+ """Sparing a recreated id spared the DELETED conversation along with it.
+
+ The scope is keyed by thread id alone, so the pre-delete turns stayed under a live id
+ with nothing left to sweep them: the endpoint reported success while the conversation
+ the user asked to delete remained recallable in the new chat. Cutting at the instant
+ the delete was accepted takes the old turns and leaves the new ones.
+ """
+ from datetime import datetime, timezone
+
+ from routes import chat_history
+
+ thread_id = "recreated-with-cutoff"
+ old_turns = _turn("what is the code", "the code is 5150")
+ _save_thread(thread_id, old_turns, append = True)
+ assert conversation_archive.archive_turns(thread_id, old_turns) == 1
+
+ cutoff = datetime.now(timezone.utc).isoformat()
+
+ # The stale tab recreates the id and its generation archives a turn of its own.
+ fresh = _turn("what is the new code", "the new code is 8080")
+ _save_thread(thread_id, old_turns + fresh, append = True)
+ assert conversation_archive.archive_turns(thread_id, fresh) == 1
+
+ chat_history._remove_conversation_archives([thread_id], cutoff = cutoff)
+
+ scope = store.conversation_archive_scope(thread_id)
+ remaining = " ".join(
+ row["text"]
+ for row in conn.execute(
+ "SELECT c.text FROM chunks c JOIN documents d ON d.id=c.document_id WHERE d.scope=?",
+ (scope,),
+ ).fetchall()
+ )
+ assert "5150" not in remaining
+ assert "8080" in remaining
+
+
+def test_an_answer_corrected_only_in_case_retires_the_archived_copy(conn):
+ """Lowercasing the comparison made a case-only correction invisible.
+
+ `Foo` corrected to `foo` is a real edit, and the pre-edit copy stayed eligible: a
+ later search could answer with the spelling the user had just fixed. Same for a block
+ re-indented and nothing else, which is the ordinary way YAML and Python get corrected.
+ """
+ rows = [{"text": "user: set the key\nassistant: Foo"}]
+ corrected = conversation_archive.branch_message_texts(
+ [{"role": "user", "content": "set the key"}, {"role": "assistant", "content": "foo"}]
+ )
+ intact = conversation_archive.branch_message_texts(
+ [{"role": "user", "content": "set the key"}, {"role": "assistant", "content": "Foo"}]
+ )
+
+ assert conversation_archive._document_matches_one_run(rows, corrected, 2) is False
+ assert conversation_archive._document_matches_one_run(rows, intact, 2) is True
+
+
+def test_a_turn_that_opens_on_whitespace_is_still_on_its_branch(conn):
+ """The guard on the tighter comparison, which `rstrip()` would have broken.
+
+ `render_turn` strips the whole message, so keeping a probe's LEADING whitespace makes
+ a live turn beginning with a space or a newline start its run at a non-zero offset and
+ `_document_matches_one_run` retires it. Pasted code is the common shape here, so the
+ loss would land on exactly the turns worth recalling.
+ """
+ for content in (" hello there", "\n def f():\n pass"):
+ turn = [{"role": "user", "content": content}, {"role": "assistant", "content": "ok"}]
+ rendered = conversation_archive.render_turn(turn)
+ text = rendered[1] if isinstance(rendered, tuple) else rendered
+ live = conversation_archive.branch_message_texts(turn)
+
+ assert conversation_archive._document_matches_one_run([{"text": text}], live, 2) is True
+
+
+def test_a_tool_result_cut_exactly_on_a_line_stays_on_its_branch(conn):
+ """`render_turn`'s cut can land on a newline, and the marker is then its own line.
+
+ Stripped, that line is empty and was dropped, taking the truncation flag with it. The
+ last real probe was read as complete, `_document_matches_one_run` demanded the live
+ message end where the probe did, and an unedited over-cap tool result was retired:
+ measured on a 900-line result, no query could return it.
+ """
+ for length, where in ((7, "on a line boundary"), (8, "mid line")):
+ body = "\n".join("y" * length for _ in range(900))
+ turn = [{"role": "user", "content": "run it"}, {"role": "tool", "content": body}]
+ rendered = conversation_archive.render_turn(turn)
+ text = rendered[1] if isinstance(rendered, tuple) else rendered
+ live = conversation_archive.branch_message_texts(turn)
+
+ assert (
+ conversation_archive._document_matches_one_run([{"text": text}], live, 2) is True
+ ), f"cut {where}"
+
+
+def test_a_persisted_tool_call_followed_by_its_answer_stays_on_its_branch(conn):
+ """The ordinary agent turn: call, result, then the model's final answer.
+
+ Bucketing the whole message as call, text, result put the answer in the middle, so
+ `_scan_probes` advanced past it to find the result and could not find it again. The
+ document rendered from the request said call, result, answer, and an unchanged evicted
+ tool exchange was classified off-branch: measured end to end, recall came back with
+ the user's question alone and the document holding the answer was filtered out.
+ """
+ stored = [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool-call",
+ "toolCallId": "c1",
+ "toolName": "terminal",
+ "args": {"command": "cat deploy.yml"},
+ "result": "token ZQX-5150",
+ },
+ {"type": "text", "text": "The deploy token is ZQX-5150."},
+ ],
+ }
+ ]
+ wire = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "function": {"name": "terminal", "arguments": '{"command": "cat deploy.yml"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "token ZQX-5150"},
+ {"role": "assistant", "content": "The deploy token is ZQX-5150."},
+ ]
+ rendered = conversation_archive.render_turn(wire)
+ text = rendered[1] if isinstance(rendered, tuple) else rendered
+
+ assert (
+ conversation_archive._document_matches_one_run(
+ [{"text": text}], conversation_archive.branch_message_texts(stored), 3
+ )
+ is True
+ )
+ # The wire-shaped branch, which every live caller supplies, is unchanged.
+ assert (
+ conversation_archive._document_matches_one_run(
+ [{"text": text}], conversation_archive.branch_message_texts(wire), 3
+ )
+ is True
+ )
+
+
+def test_a_batch_mixing_a_search_with_an_ordinary_tool_keeps_its_transcript_span(conn):
+ """`archive_messages` bounds the branch check, so it has to be the TRANSCRIPT span.
+
+ An assistant batch that called `search_conversation` alongside an ordinary tool has
+ its retrieval call and result stripped before the document is written, so the archived
+ copy is three messages where the live turn is four. Bounded by the shorter figure, the
+ perfectly valid ordinary-tool exchange and the answer that followed were rejected as
+ off-branch and could never be recalled.
+ """
+ group = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "search_conversation", "arguments": '{"q":"x"}'}},
+ {"id": "c2", "function": {"name": "terminal", "arguments": '{"command":"ls"}'}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "earlier turns about the repo"},
+ {"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},
+ {"role": "assistant", "content": "The repo has two files."},
+ ]
+ archivable = conversation_archive._archivable(group)
+ assert len(archivable) == 3 and len(group) == 4
+
+ rendered = conversation_archive.render_turn(archivable)
+ text = rendered[1] if isinstance(rendered, tuple) else rendered
+ live = conversation_archive.branch_message_texts(group)
+
+ assert (
+ conversation_archive._document_matches_one_run([{"text": text}], live, len(group)) is True
+ )
+
+ _archive(group)
+ scope = store.conversation_archive_scope(THREAD)
+ spans = [
+ row["archive_messages"]
+ for row in conn.execute(
+ "SELECT archive_messages FROM documents WHERE scope=?", (scope,)
+ ).fetchall()
+ ]
+ assert spans == [4], spans
+
+
+def test_the_same_text_over_a_longer_span_widens_the_stored_window(conn):
+ """One document, two spans: the window has to fit the LONGER of them.
+
+ The digest is the rendered text, and `_archivable` strips a retrieval call and its
+ result, so a three-message tool exchange and a four-message batch containing that same
+ exchange render identically. Archived shortest first, the second was skipped as a
+ duplicate and inherited a window of three, which `_document_matches_one_run` then used
+ to bound a four-message live run: the turn was rejected as off-branch and no query
+ could return it.
+ """
+ short = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c2", "function": {"name": "terminal", "arguments": '{"command":"ls"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},
+ {"role": "assistant", "content": "The repo has two files."},
+ ]
+ long = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "search_conversation", "arguments": '{"q":"x"}'}},
+ {"id": "c2", "function": {"name": "terminal", "arguments": '{"command":"ls"}'}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "earlier turns about the repo"},
+ {"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},
+ {"role": "assistant", "content": "The repo has two files."},
+ ]
+ assert conversation_archive.render_turn(
+ conversation_archive._archivable(short)
+ ) == conversation_archive.render_turn(conversation_archive._archivable(long))
+
+ _archive(short)
+ _archive(long)
+
+ scope = store.conversation_archive_scope(THREAD)
+ rows = conn.execute(
+ "SELECT archive_messages, sha256 FROM documents WHERE scope=?", (scope,)
+ ).fetchall()
+ assert [row["archive_messages"] for row in rows] == [4], "the window stayed at the shorter span"
+
+ # And the longer turn now validates against its own four-message run.
+ text = conversation_archive.render_turn(conversation_archive._archivable(long))
+ live = conversation_archive.branch_message_texts(long)
+ assert conversation_archive._document_matches_one_run([{"text": text}], live, 3) is False
+ assert conversation_archive._document_matches_one_run([{"text": text}], live, 4) is True
+
+
+def test_a_long_tool_exchange_stays_on_branch_across_a_chunk_boundary():
+ """A chunk's overlap can carry a whole short message into the next chunk.
+
+ `CHUNK_OVERLAP` repeats the previous chunk's tail, and where that tail begins just
+ after a short line -- an assistant tool call sitting in front of a long tool result --
+ the repeat starts in an EARLIER message than the one the previous chunk finished in.
+ Resuming the scan strictly at the finishing message could never match it, so an
+ unedited document was retired as off-branch and that turn became unsearchable. Swept
+ over question lengths, 7 of 89 failed before the fix.
+ """
+ from core.rag import config
+ from core.rag.chunking import chunk_pages
+ from core.rag.parsers import Page
+
+ def _matches(lines: int, count) -> bool:
+ group = [
+ {
+ "role": "user",
+ "content": "\n".join(
+ f"line {i} of the question about the repo" for i in range(lines)
+ ),
+ },
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "grep", "arguments": '{"pattern":"foo"}'}}
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "c1",
+ "content": "\n".join(
+ f"result row {i} with some matching text here" for i in range(200)
+ ),
+ },
+ {"role": "assistant", "content": "That is the whole match list."},
+ ]
+ text = conversation_archive.render_turn(group)
+ chunks = chunk_pages(
+ [Page(text = text, page_number = None, char_count = len(text))],
+ max_tokens = config.CHUNK_TOKENS,
+ overlap = config.CHUNK_OVERLAP,
+ count = count,
+ )
+ assert len(chunks) > 1, "this test needs a turn that really crosses a chunk boundary"
+ return conversation_archive._document_matches_one_run(
+ [{"text": chunk.text} for chunk in chunks],
+ conversation_archive.branch_message_texts(group),
+ len(group),
+ )
+
+ for count in (lambda t: max(1, len(t) // 4), lambda t: max(1, len(t.split()))):
+ missed = [lines for lines in range(1, 90) if not _matches(lines, count)]
+ assert not missed, f"unedited turns retired as off-branch at question lengths {missed}"
+
+
+def test_one_pass_holding_both_spans_widens_the_window_too(conn):
+ """The window has to grow on the LOCKED duplicate path as well.
+
+ Both turns can arrive in one compaction: the pre-check runs before either is written,
+ so it clears both, and the shorter one is written first. The longer one then meets the
+ re-check under the write lock, which rolls back and moves on without touching the
+ span. The stored window stays at three, the four-message occurrence is bounded by it,
+ and the turn is unsearchable -- the same failure as the unlocked path, one lock down.
+ """
+ short = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c2", "function": {"name": "terminal", "arguments": '{"command":"ls"}'}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},
+ {"role": "assistant", "content": "The repo has two files."},
+ ]
+ long = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "function": {"name": "search_conversation", "arguments": '{"q":"x"}'}},
+ {"id": "c2", "function": {"name": "terminal", "arguments": '{"command":"ls"}'}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "earlier turns about the repo"},
+ {"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},
+ {"role": "assistant", "content": "The repo has two files."},
+ ]
+
+ # One call, both turns, shortest first.
+ _archive(short + [{"role": "user", "content": "and again please"}] + long)
+
+ scope = store.conversation_archive_scope(THREAD)
+ spans = [
+ row["archive_messages"]
+ for row in conn.execute(
+ "SELECT archive_messages FROM documents WHERE scope=? AND archive_messages >= 3",
+ (scope,),
+ ).fetchall()
+ ]
+ assert spans == [4], spans
diff --git a/studio/backend/tests/test_conversation_recall_injection.py b/studio/backend/tests/test_conversation_recall_injection.py
new file mode 100644
index 00000000000..5aa60fdec6b
--- /dev/null
+++ b/studio/backend/tests/test_conversation_recall_injection.py
@@ -0,0 +1,1532 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""How recalled turns get back into a compacted request, and what must not ride along."""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from core.inference import llama_cpp # noqa: E402
+from core.inference import tools as tools_mod # noqa: E402
+from core.rag import conversation_archive # noqa: E402
+
+THREAD = "thread-recall"
+
+
+def archived(rag_home, rag_conn, stub_embeddings):
+ turns = [
+ {"role": "user", "content": "write me a limerick about pelicans"},
+ {"role": "assistant", "content": "There once was a bird with a bill"},
+ ]
+ # The thread has to exist in studio.db: only a persisted thread can be deleted, and
+ # an archive nothing can delete is the temporary-chat leak the rule prevents.
+ from storage import studio_db
+
+ studio_db.upsert_chat_thread(
+ {
+ "id": THREAD,
+ "title": "t",
+ "modelType": "base",
+ "modelId": "local-model",
+ "createdAt": 1,
+ }
+ )
+ for index, message in enumerate(turns):
+ studio_db.upsert_chat_message(
+ {
+ "id": f"{THREAD}-{index}",
+ "threadId": THREAD,
+ "role": message["role"],
+ "content": [{"type": "text", "text": message["content"]}],
+ "createdAt": index + 2,
+ }
+ )
+ conversation_archive.archive_turns(THREAD, turns)
+ return rag_conn
+
+
+def _conversation():
+ return [
+ {"role": "system", "content": "you are helpful"},
+ {"role": "user", "content": "what was that pelicans limerick"},
+ ]
+
+
+def test_recall_runs_even_when_document_rag_is_off(archived):
+ """Compaction happens regardless of the user's RAG toggle.
+
+ The recalled turns are the conversation's own, so gating on rag_scope would lose a
+ compacted chat's history whenever documents are off.
+ """
+ built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "tool")
+
+ assert built is not None
+ assert built["sources"] >= 1
+ assert built["messages"][0]["tool_calls"][0]["function"]["name"] == "search_conversation"
+
+
+def test_tool_style_matches_the_rag_autoinject_shape(archived):
+ """The UI renders forced retrieval through the existing tool-card path."""
+ built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "tool")
+
+ assert [event["type"] for event in built["events"]] == [
+ "status",
+ "tool_start",
+ "tool_end",
+ "status",
+ ]
+ assert [message["role"] for message in built["messages"]] == ["assistant", "tool"]
+ call_id = built["messages"][0]["tool_calls"][0]["id"]
+ assert call_id.startswith("conv_recall_")
+ assert built["messages"][1]["tool_call_id"] == call_id
+
+
+def test_inline_style_returns_a_prefix_and_no_forged_tool_messages(archived):
+ """The plain path sends no tools array; a tool role there is a template hazard."""
+ built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "inline")
+
+ assert built["messages"] == []
+ assert built["events"] == []
+ assert "<recalled_conversation>" in built["prefix"]
+
+
+def test_recall_is_none_without_a_thread_id(archived):
+ assert tools_mod.build_conversation_recall(_conversation(), None) is None
+
+
+def test_recall_is_none_when_nothing_matches(archived):
+ built = tools_mod.build_conversation_recall(
+ [{"role": "user", "content": "zzzz unrelated quantum plumbing"}], THREAD
+ )
+
+ assert built is None or built["sources"] >= 0
+
+
+def test_prefix_user_text_does_not_mutate_the_original():
+ message = {"role": "user", "content": "original"}
+
+ updated = llama_cpp._prefix_user_text(message, "PREFIX ")
+
+ assert message["content"] == "original"
+ assert updated["content"] == "PREFIX original"
+
+
+def test_prefix_user_text_handles_content_parts():
+ message = {
+ "role": "user",
+ "content": [{"type": "image_url", "image_url": {}}, {"type": "text", "text": "hello"}],
+ }
+
+ updated = llama_cpp._prefix_user_text(message, "PREFIX ")
+
+ assert updated["content"][1]["text"] == "PREFIX hello"
+ assert message["content"][1]["text"] == "hello"
+
+
+def test_archive_and_recall_reports_counts_only(archived):
+ """The counts merge into the context_truncated SSE payload, which goes to the client.
+
+ Message text must never ride along on that event.
+ """
+ before = _conversation() + [{"role": "user", "content": "evicted turn"}]
+ after = _conversation()
+
+ result = llama_cpp._archive_and_recall(
+ after, before, thread_id = THREAD, style = "tool", recall_done = False
+ )
+
+ assert set(result["counts"]) <= {"archived_messages", "recalled_chunks"}
+ assert all(isinstance(value, int) for value in result["counts"].values())
+
+
+def test_archive_and_recall_skips_recall_once_already_done(archived):
+ before = _conversation() + [{"role": "user", "content": "evicted turn"}]
+ after = _conversation()
+
+ result = llama_cpp._archive_and_recall(
+ after, before, thread_id = THREAD, style = "tool", recall_done = True
+ )
+
+ assert result["recalled"] is False
+ assert result["conversation"] is after
+ assert "recalled_chunks" not in result["counts"]
+
+
+def test_archive_and_recall_is_a_noop_without_a_thread_id(archived):
+ after = _conversation()
+
+ result = llama_cpp._archive_and_recall(
+ after, after, thread_id = None, style = "tool", recall_done = False
+ )
+
+ assert result["conversation"] is after
+ assert result["counts"] == {}
+
+
+def test_recall_reserve_is_zero_without_a_thread():
+ assert llama_cpp._conversation_recall_reserve(None) == 0
+
+
+def test_recall_reserve_is_zero_when_the_archive_is_disabled(monkeypatch):
+ monkeypatch.setattr(conversation_archive.config, "CONVERSATION_ARCHIVE", False)
+
+ assert llama_cpp._conversation_recall_reserve(THREAD) == 0
+
+
+def test_build_rag_autoinject_still_emits_its_original_shape(monkeypatch):
+ """Guards the extraction that gave recall and document auto-inject a shared builder."""
+ from core.rag import tool as rag_tool
+
+ # Patched on core.rag.tool, not on tools_mod: build_rag_autoinject imports it lazily
+ # inside the function body, so rebinding the caller's module has no effect.
+ monkeypatch.setattr(
+ rag_tool,
+ "search_for_autoinject",
+ lambda **kwargs: ("passage text", [{"citationId": 1, "filename": "doc.txt"}]),
+ )
+
+ # kb_id rather than thread_id so this exercises the retrieval branch rather than the
+ # whole-document one, and the toggles ride in the scope instead of a monkeypatch.
+ built = tools_mod.build_rag_autoinject(
+ [{"role": "user", "content": "question"}],
+ {"kb_id": "kb-1", "autoinject": True, "autoinject_min_score": 0.0},
+ )
+
+ assert built is not None
+ assert [event["type"] for event in built["events"]] == [
+ "status",
+ "tool_start",
+ "tool_end",
+ "status",
+ ]
+ assert built["messages"][0]["tool_calls"][0]["function"]["name"] == "search_knowledge_base"
+ assert built["messages"][0]["tool_calls"][0]["id"].startswith("rag_auto_")
+ assert built["messages"][1]["content"] == "passage text"
+
+
+def test_search_conversation_is_always_safe():
+ """Read-only, so auto mode must not prompt on every call."""
+ assert tools_mod.is_always_safe_tool("search_conversation") is True
+
+
+def test_search_conversation_tool_is_registered():
+ names = {tool["function"]["name"] for tool in tools_mod.ALL_TOOLS}
+
+ assert "search_conversation" in names
+
+
+def test_execute_tool_without_a_thread_returns_a_message_not_a_traceback():
+ result = tools_mod.execute_tool(
+ "search_conversation", {"query": "anything"}, thread_id = None, timeout = None
+ )
+
+ assert isinstance(result, str)
+ assert "no earlier conversation" in result.lower()
+
+
+def test_execute_tool_rejects_an_empty_query(archived):
+ result = tools_mod.execute_tool(
+ "search_conversation", {"query": " "}, thread_id = THREAD, timeout = None
+ )
+
+ assert result == "Error: query is empty."
+
+
+def test_execute_tool_finds_an_archived_turn(archived):
+ result = tools_mod.execute_tool(
+ "search_conversation", {"query": "pelicans"}, thread_id = THREAD, timeout = None
+ )
+
+ assert "pelicans" in result
+
+
+def test_compaction_nudge_only_fires_when_the_tool_is_present():
+ import routes.inference as routes_mod
+
+ without = routes_mod._apply_compaction_nudge("base.", [])
+ with_tool = routes_mod._apply_compaction_nudge(
+ "base.", [{"function": {"name": "search_conversation"}}]
+ )
+
+ assert without == "base."
+ assert "search_conversation" in with_tool
+
+
+# ---------------------------------------------------------------------------
+# The sticky compaction boundary
+# ---------------------------------------------------------------------------
+
+
+def _fake_studio_db(monkeypatch, messages):
+ """Stand in for storage.studio_db.list_chat_messages."""
+ import sys
+ import types
+
+ module = types.SimpleNamespace(list_chat_messages = lambda thread_id: messages)
+ package = types.ModuleType("storage")
+ package.studio_db = module
+ monkeypatch.setitem(sys.modules, "storage", package)
+ monkeypatch.setitem(sys.modules, "storage.studio_db", module)
+
+
+def test_sticky_boundary_reads_the_newest_assistant_truncation(monkeypatch):
+ from core.inference import llama_cpp
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 12}}
+ },
+ },
+ {"role": "user", "content": "q2"},
+ {
+ "role": "assistant",
+ "content": "a2",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 18}}
+ },
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 18
+
+
+def test_sticky_boundary_ignores_a_sibling_branchs_assistant_turn(monkeypatch):
+ """Retry keeps the replaced response, and the stored rows are the whole DAG.
+
+ Ordered by creation time, the newest assistant can be the sibling the user switched
+ away from, whose boundary is sized for history this branch does not have.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": "answer on the branch we are on",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 4}}
+ },
+ },
+ {
+ "role": "assistant",
+ "content": "regenerated answer the user switched away from",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 40}}
+ },
+ },
+ ],
+ )
+ branch = [
+ {"role": "user", "content": "q"},
+ {"role": "assistant", "content": "answer on the branch we are on"},
+ {"role": "user", "content": "next"},
+ ]
+
+ # Thread-wide, the newest row wins even though it is on the other branch.
+ assert llama_cpp._sticky_compaction_boundary("t1") == 40
+ # Told which branch the request is on, the branch's own boundary is used.
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4
+
+
+def test_sticky_boundary_takes_the_smaller_of_two_identical_replies(monkeypatch):
+ """Retry on a short reply gives two siblings whose text is the same.
+
+ The branch check is textual, so both look on-branch and the newest row wins, applying
+ a much deeper branch's boundary and evicting live history. Where the text cannot
+ separate them, the smaller boundary is the safe one.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": "Done.",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 4}}
+ },
+ },
+ {
+ "role": "assistant",
+ "content": "Done.",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 60}}
+ },
+ },
+ ],
+ )
+ branch = [
+ {"role": "user", "content": "q"},
+ {"role": "assistant", "content": "Done."},
+ {"role": "user", "content": "next"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4
+
+
+def test_sticky_boundary_still_prefers_the_newest_distinguishable_reply(monkeypatch):
+ """Only replies indistinguishable from the newest are folded in.
+
+ Otherwise the smallest boundary anywhere in a long thread wins every time and the
+ boundary ratchets backwards over the life of the chat.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "an earlier, shallower answer",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 2}}
+ },
+ },
+ {
+ "role": "assistant",
+ "content": "the newest answer",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 30}}
+ },
+ },
+ ],
+ )
+ branch = [
+ {"role": "assistant", "content": "an earlier, shallower answer"},
+ {"role": "assistant", "content": "the newest answer"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 30
+
+
+def test_sticky_boundary_prefers_a_reply_that_matches_the_branch_exactly(monkeypatch):
+ """The branch check is a substring test, and short replies ride in on longer ones.
+
+ "Done" is contained in the live "Not done yet, still running.", so an abandoned
+ sibling looked active and, having no live twin, decided the boundary alone.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {"role": "user", "content": "did it work"},
+ {
+ "role": "assistant",
+ "content": "Not done yet, still running.",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 4}}
+ },
+ },
+ {
+ "role": "assistant",
+ "content": "Done",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 60}}
+ },
+ },
+ ],
+ )
+ branch = [
+ {"role": "user", "content": "did it work"},
+ {"role": "assistant", "content": "Not done yet, still running."},
+ {"role": "user", "content": "keep going"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 4
+
+
+def test_sticky_boundary_still_reads_a_reply_no_branch_message_matches_exactly(monkeypatch):
+ """The exact preference must not become a requirement.
+
+ A stored row is not always byte-identical to what the client re-sends, and demanding
+ equality would silently switch the boundary off for every such thread.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "the answer",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 9}}
+ },
+ },
+ ],
+ )
+ branch = [
+ {"role": "user", "content": "q"},
+ {"role": "assistant", "content": "the answer, with a block the request drops"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 9
+
+
+def test_sticky_boundary_prefers_the_recorded_branch_boundary(monkeypatch):
+ """A turn that refit several times persists a dropped count larger than the branch.
+
+ The counts are summed and include the tool exchanges the turn created, which the next
+ request's transcript lacks. Restore the boundary recorded against its own messages.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {
+ "custom": {
+ "contextTruncation": {
+ "fits": True,
+ "dropped_messages": 12,
+ "boundary_messages": 4,
+ }
+ }
+ },
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 4
+
+
+def _anchored_row(
+ boundary,
+ anchor,
+ content = "a",
+):
+ return {
+ "role": "assistant",
+ "content": content,
+ "metadata": {
+ "custom": {
+ "contextTruncation": {
+ "fits": True,
+ "boundary_messages": boundary,
+ "boundary_anchor": anchor,
+ }
+ }
+ },
+ }
+
+
+def test_sticky_boundary_rebases_after_an_evicted_turn_is_deleted(monkeypatch):
+ """Deleting an already-evicted prompt must not cost a LIVE turn.
+
+ The recorded count is absolute against the transcript it was counted on. Delete two
+ messages in front of the boundary and replaying that count unchanged lands two
+ messages too deep, evicting history the user can still see. The anchor names the
+ message the boundary was meant to land on, so the count is re-derived by position.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(monkeypatch, [_anchored_row(4, "kept first")])
+ # The two turns the boundary used to sit behind are gone; "kept first" is now 3rd.
+ branch = [
+ {"role": "user", "content": "old prompt"},
+ {"role": "assistant", "content": "old reply"},
+ {"role": "user", "content": "kept first"},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2
+
+
+def test_sticky_boundary_anchor_never_deepens_the_cut(monkeypatch):
+ """An anchor that has moved BACK is ignored, never obeyed.
+
+ A repeated text or an edited turn can put the anchor further into the branch than the
+ recorded count. Following it there would evict live history on the strength of a
+ coincidence, so the anchor is allowed to make the boundary shallower and nothing else.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(monkeypatch, [_anchored_row(2, "kept first")])
+ branch = [
+ {"role": "user", "content": "one"},
+ {"role": "assistant", "content": "two"},
+ {"role": "user", "content": "three"},
+ {"role": "assistant", "content": "four"},
+ {"role": "user", "content": "kept first"},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2
+
+
+def test_sticky_boundary_ignores_an_anchor_the_branch_no_longer_has(monkeypatch):
+ """The anchor's own turn can be the one deleted. Fall back to the recorded count."""
+ from core.inference import llama_cpp
+
+ _fake_studio_db(monkeypatch, [_anchored_row(2, "a text this branch does not have")])
+ branch = [
+ {"role": "user", "content": "one"},
+ {"role": "assistant", "content": "two"},
+ {"role": "user", "content": "three"},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2
+
+
+def test_sticky_boundary_anchor_skips_the_system_turn(monkeypatch):
+ """Counted the way `_branch_boundary` counts: system and developer turns do not.
+
+ Studio prefixes every request with a system message, so counting it would put every
+ anchor one place late and quietly deepen every boundary by one.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(monkeypatch, [_anchored_row(4, "kept first")])
+ branch = [
+ {"role": "system", "content": "you are a helpful assistant"},
+ {"role": "user", "content": "old prompt"},
+ {"role": "assistant", "content": "old reply"},
+ {"role": "user", "content": "kept first"},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 2
+
+
+def test_branch_boundary_anchor_names_the_first_kept_message():
+ """The anchor and the count describe the same cut, or the rebase is meaningless."""
+ from core.inference import llama_cpp
+
+ branch = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "evicted prompt"},
+ {"role": "assistant", "content": "evicted reply"},
+ {"role": "user", "content": "kept prompt"},
+ {"role": "assistant", "content": "kept reply"},
+ {"role": "user", "content": "the turn just sent"},
+ ]
+ conversation = [branch[0]] + branch[3:]
+
+ assert llama_cpp._branch_boundary(conversation, branch) == 2
+ assert llama_cpp._branch_boundary_anchor(conversation, branch) == "kept prompt"
+
+
+def test_sticky_boundary_falls_back_for_turns_saved_before_the_boundary_existed(monkeypatch):
+ """Rows written by an earlier build carry only the dropped count."""
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 6}}
+ },
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 6
+
+
+def test_the_recall_reserve_is_dropped_once_archiving_has_failed(monkeypatch):
+ """sqlite-vec present and the thread saved, but the embedder cannot start.
+
+ archive_turns swallows that and recall injects nothing, so the reserved room is pure
+ loss on every compaction, forgetting more history than having the feature off.
+ """
+ from core.inference import llama_cpp
+ from core.rag import conversation_archive as archive
+
+ monkeypatch.setattr(archive, "can_archive", lambda _tid: True)
+ monkeypatch.setattr(archive, "degraded", lambda: False)
+ assert llama_cpp._conversation_recall_reserve("t1") > 0
+
+ monkeypatch.setattr(archive, "degraded", lambda: True)
+ assert llama_cpp._conversation_recall_reserve("t1") == 0
+
+
+def test_sticky_boundary_only_matches_assistant_messages(monkeypatch):
+ """The rows being checked are replies, so the branch has to be read as replies.
+
+ Against every role, an abandoned "Done" rides in on a live user message that merely
+ contains it ("not done yet I think"), and its much larger boundary is applied to a
+ branch that never had that reply.
+ """
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {"role": "user", "content": "did the deploy finish? not done yet I think"},
+ {
+ "role": "assistant",
+ "content": "Done",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": True, "dropped_messages": 60}}
+ },
+ },
+ ],
+ )
+ branch = [{"role": "user", "content": "did the deploy finish? not done yet I think"}]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 0
+
+
+def test_sticky_boundary_reads_the_flattened_metadata_shape(monkeypatch):
+ """The history row flattens `custom` into `metadata`; both shapes are in the wild."""
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {"contextTruncation": {"fits": True, "dropped_messages": 7}},
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 7
+
+
+def test_sticky_boundary_is_zero_without_a_thread_or_history(monkeypatch):
+ from core.inference import llama_cpp
+
+ assert llama_cpp._sticky_compaction_boundary(None) == 0
+ assert llama_cpp._sticky_compaction_boundary("") == 0
+ _fake_studio_db(monkeypatch, [])
+ assert llama_cpp._sticky_compaction_boundary("t1") == 0
+
+
+def test_sticky_boundary_ignores_a_fit_that_did_not_fit(monkeypatch):
+ """`fits: false` means the fit gave up, so it describes no boundary to restore."""
+ from core.inference import llama_cpp
+
+ _fake_studio_db(
+ monkeypatch,
+ [
+ {
+ "role": "assistant",
+ "content": "a",
+ "metadata": {
+ "custom": {"contextTruncation": {"fits": False, "dropped_messages": 40}}
+ },
+ },
+ ],
+ )
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 0
+
+
+def test_sticky_boundary_never_raises_on_a_storage_failure(monkeypatch):
+ """A boundary is an optimisation; losing it must never cost the user a turn."""
+ import sys
+ import types
+
+ from core.inference import llama_cpp
+
+ def explode(thread_id):
+ raise RuntimeError("database is locked")
+
+ module = types.SimpleNamespace(list_chat_messages = explode)
+ package = types.ModuleType("storage")
+ package.studio_db = module
+ monkeypatch.setitem(sys.modules, "storage", package)
+ monkeypatch.setitem(sys.modules, "storage.studio_db", module)
+
+ assert llama_cpp._sticky_compaction_boundary("t1") == 0
+
+
+# ---------------------------------------------------------------------------
+# Sizing the forced recall, and applying the sticky boundary once
+# ---------------------------------------------------------------------------
+
+
+def test_recall_is_sized_by_the_room_the_fit_actually_obtained():
+ """The reserve is what the fit AIMS for, not what it always gets.
+
+ Protected messages can stop the trim reaching its target while still passing the
+ prompt budget. Reproduced at ctx 8000: accepted at 6900, and a full reserve of recall
+ on top took the request to 8948, past the window it had just been made to fit.
+ """
+ from core.inference import llama_cpp
+
+ assert llama_cpp._recall_top_k(0) == 0
+ assert llama_cpp._recall_top_k(-500) == 0
+ # Enough room for some chunks but not the full allowance.
+ assert 0 < llama_cpp._recall_top_k(1024) <= 4
+ # Plenty of room is still capped by the configured top-k.
+ assert llama_cpp._recall_top_k(1_000_000) == 4
+
+
+def test_the_sticky_boundary_is_applied_once_per_request():
+ """The tool loop refits on the conversation the previous fit returned.
+
+ Re-applying the persisted count evicts another boundary-sized block of live history:
+ before the fix a second fit dropped 28 of 30 surviving messages instead of 14.
+ """
+ from core.inference.context_window import fit_rolling_context
+
+ def counter(messages):
+ return sum(max(1, len(m["content"]) // 4) for m in messages)
+
+ conversation = [{"role": "system", "content": "s" * 80}]
+ for index in range(40):
+ conversation.append({"role": "user", "content": f"q{index} " * 200})
+ conversation.append({"role": "assistant", "content": f"a{index} " * 200})
+ conversation.append({"role": "user", "content": "latest"})
+
+ conversation, first = fit_rolling_context(
+ conversation,
+ context_length = 8000,
+ max_tokens = 512,
+ count_tokens = counter,
+ sticky_dropped = 52,
+ )
+ assert first["dropped_messages"] == 52
+ # A tool result lands and pushes the already-fitted conversation back over budget.
+ conversation = conversation + [
+ {"role": "assistant", "content": "calling"},
+ {"role": "tool", "content": "R" * (2600 * 4)},
+ ]
+ _, reapplied = fit_rolling_context(
+ conversation,
+ context_length = 8000,
+ max_tokens = 512,
+ count_tokens = counter,
+ sticky_dropped = 52,
+ )
+ _, once = fit_rolling_context(
+ conversation,
+ context_length = 8000,
+ max_tokens = 512,
+ count_tokens = counter,
+ sticky_dropped = 0,
+ )
+ assert reapplied["dropped_messages"] > once["dropped_messages"]
+ # The second shape: the boundary describes the ORIGINAL transcript, so the first
+ # fit spends it.
+ from pathlib import Path
+
+ source = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"
+ text = source.read_text()
+ assert "_sticky_boundary_applied = True" in text
+ # Whitespace-insensitive: the gate is one expression however the formatter wraps it.
+ assert "0 if _sticky_boundary_applied" in " ".join(text.split())
+
+
+def test_conversation_search_top_k_is_clamped(archived, monkeypatch):
+ """top_k is written by the model. A negative reaches a slice as out[:-1]."""
+ seen = {}
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ seen["top_k"] = top_k
+ seen["branch_messages"] = branch_messages
+ return ("earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ tools_mod._search_conversation({"query": "pelicans", "top_k": -1}, {"thread_id": THREAD})
+ assert seen["top_k"] >= 1
+
+ tools_mod._search_conversation({"query": "pelicans", "top_k": 10_000}, {"thread_id": THREAD})
+ assert seen["top_k"] <= tools_mod._MAX_CONVERSATION_SEARCH_TOP_K
+
+
+def test_conversation_search_top_k_is_clamped_by_the_live_budget(archived, monkeypatch):
+ """The fixed ceiling bounds what the model may ask for, not what the context holds.
+
+ Eight chunks is roughly 4,000 tokens once wrapped, landing in the protected current
+ exchange, so on a small context an unbudgeted search is an unrecoverable error.
+ """
+ from core.rag import config as rag_config
+
+ seen = {}
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ seen["top_k"] = top_k
+ return ("earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ # Room for two chunks, asked for the ceiling.
+ tools_mod._search_conversation(
+ {"query": "pelicans", "top_k": 8},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
+ )
+ assert seen["top_k"] == 2
+
+ # An omitted top_k is budgeted too, rather than falling through to the default.
+ seen.clear()
+ tools_mod._search_conversation(
+ {"query": "pelicans"},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS},
+ )
+ assert seen["top_k"] == 1
+
+ # No room at all: say so instead of returning a result that cannot be sent.
+ seen.clear()
+ answer = tools_mod._search_conversation(
+ {"query": "pelicans", "top_k": 4},
+ {"thread_id": THREAD, "budget_tokens": 10},
+ )
+ assert "no room" in answer.lower()
+ assert not seen
+
+
+def test_an_omitted_top_k_still_means_the_configured_default(archived, monkeypatch):
+ """Room is a cap on the default, not a target.
+
+ Budgeting an omitted top_k by dividing the whole budget asked a 128K chat for 200
+ passages, past the configured default and past the ceiling the model's own value is
+ held to.
+ """
+ from core.rag import config as rag_config
+
+ asked = []
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ asked.append(top_k)
+ return ("an earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ tools_mod._search_conversation(
+ {"query": "pelicans"}, {"thread_id": THREAD, "budget_tokens": 100_000}
+ )
+ assert asked == [
+ min(rag_config.CONVERSATION_ARCHIVE_TOP_K, tools_mod._MAX_CONVERSATION_SEARCH_TOP_K)
+ ]
+
+ # And a budget smaller than the default still caps it.
+ asked.clear()
+ tools_mod._search_conversation(
+ {"query": "pelicans"},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
+ )
+ assert asked == [2]
+
+
+def test_conversation_search_refuses_a_result_the_budget_cannot_hold(archived, monkeypatch):
+ """CHUNK_TOKENS is what the chunker aims at, not what a chunk weighs.
+
+ Chunks overlap, the chunker's tokenizer is not the model's, and the rendered block
+ adds markup, sources and the tool framing. Measured on a 500-token budget: one chunk
+ came back at 1,256 estimated tokens, into an exchange the window cannot evict.
+ """
+ from core.rag import config as rag_config
+
+ asked = []
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ asked.append(top_k)
+ # Roughly what a real chunk renders to, wrapper included.
+ return ("x" * 4 * rag_config.CHUNK_TOKENS * (top_k or 1) * 6, [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ answer = tools_mod._search_conversation(
+ {"query": "pelicans", "top_k": 8},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 4},
+ )
+
+ # Halved down to one, and refused when even that does not fit.
+ assert asked == [4, 2, 1]
+ assert "no room" in answer.lower()
+
+
+def test_conversation_search_returns_what_the_budget_does_hold(archived, monkeypatch):
+ """The backoff must not become a refusal on a result that fits."""
+ from core.rag import config as rag_config
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ return ("an earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ answer = tools_mod._search_conversation(
+ {"query": "pelicans", "top_k": 4},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 4},
+ )
+
+ assert "an earlier turn" in answer
+
+
+def test_the_conversation_tool_survives_studios_explicit_allowlist(monkeypatch):
+ """Studio always sends enabled_tools, and it never names this internal tool.
+
+ While the gate could only REMOVE, the allowlist filter dropped search_conversation
+ first, so neither it nor the compaction nudge ever appeared in a Studio chat.
+ """
+ import asyncio
+ import types
+
+ import routes.inference as routes_mod
+
+ monkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: True)
+
+ payload = types.SimpleNamespace(
+ enabled_tools = ["search_knowledge_base", "web_search"],
+ rag_scope = {"thread_id": THREAD},
+ thread_id = THREAD,
+ bypass_permissions = False,
+ )
+ tools = asyncio.run(routes_mod._select_request_tools(payload, tools_on = True, mcp_allowed = False))
+ names = [tool["function"]["name"] for tool in tools]
+
+ assert "search_conversation" in names
+ assert names.count("search_conversation") == 1
+ # Still absent without an archive: an ordinary short chat never sees the schema.
+ monkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: False)
+ tools = asyncio.run(routes_mod._select_request_tools(payload, tools_on = True, mcp_allowed = False))
+ assert "search_conversation" not in [t["function"]["name"] for t in tools]
+
+
+def test_both_retrieval_tools_share_the_per_turn_search_cap():
+ """Each search appends passages into the protected current exchange.
+
+ The rolling window cannot evict those, so an uncapped tool only ends the turn in a
+ context-length error after paying for the embeddings.
+ """
+ from pathlib import Path
+
+ from core.inference.tool_call_parser import RAG_SEARCH_TOOLS
+
+ assert RAG_SEARCH_TOOLS == {"search_knowledge_base", "search_conversation"}
+ # BOTH loops: the tool is advertised per thread, so a GGUF-compacted chat can call
+ # it under a safetensors model.
+ backend = Path(__file__).resolve().parent.parent / "core/inference"
+ for module in ("llama_cpp.py", "safetensors_agentic.py"):
+ text = (backend / module).read_text()
+ # The cap and the counter must both key on the set, not on one tool name.
+ assert "decision.tool_name in RAG_SEARCH_TOOLS" in text, module
+ assert 'decision.tool_name == "search_knowledge_base"' not in text, module
+
+
+def test_an_omitted_top_k_falls_through_to_the_configured_default(archived, monkeypatch):
+ """Defaulting to the CEILING made an ordinary search return eight archived turns.
+
+ Those land in the protected current exchange, so one search could fail the next pass
+ on a small window.
+ """
+ seen = {}
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ seen["top_k"] = top_k
+ seen["branch_messages"] = branch_messages
+ return ("earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+ tools_mod._search_conversation({"query": "pelicans"}, {"thread_id": THREAD})
+
+ assert seen["top_k"] is None
+
+
+def test_a_thread_that_cannot_be_archived_holds_back_no_reserve(monkeypatch):
+ """The reserve is room for recalled turns, and a temporary chat never has any.
+
+ archive_turns refuses a thread with no saved messages, so nothing can be recalled
+ into that room, while the fit still pays for it in evicted history. On a 4K window
+ that was most of the conversation.
+ """
+ from core.inference import llama_cpp
+ from core.rag import conversation_archive
+
+ monkeypatch.setattr(conversation_archive, "enabled", lambda: True)
+
+ monkeypatch.setattr(conversation_archive, "can_archive", lambda thread_id: False)
+ assert llama_cpp._conversation_recall_reserve("incognito") == 0
+
+ monkeypatch.setattr(conversation_archive, "can_archive", lambda thread_id: True)
+ assert llama_cpp._conversation_recall_reserve("saved") > 0
+ # And no thread at all is still zero.
+ assert llama_cpp._conversation_recall_reserve(None) == 0
+
+
+def test_the_forced_recall_searches_for_the_USERS_question(archived, monkeypatch):
+ """The loop conversation can end with an internal user-role re-prompt.
+
+ The plan-without-action nudge and the deferred no-op both append one, so a later
+ overflow would search for that controller instruction instead of the user's question.
+ """
+ seen = {}
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ seen["query"] = query
+ return ("earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+ branch = [
+ {"role": "user", "content": "what was the VULPINE code from earlier"},
+ {"role": "assistant", "content": "checking"},
+ ]
+ conversation = branch + [
+ {"role": "user", "content": "You said you would use a tool. Do it now or answer."}
+ ]
+
+ tools_mod.build_conversation_recall(
+ conversation, THREAD, style = "inline", branch_messages = branch
+ )
+
+ assert seen["query"] == "what was the VULPINE code from earlier"
+
+
+def test_a_model_initiated_search_is_filtered_to_the_request_branch(archived, monkeypatch):
+ """The forced recall is branch-filtered, so the tool the model can call must be too.
+
+ Otherwise the model asks for what the forced recall refused, and a response replaced
+ by Retry comes back through the other door.
+ """
+ seen = {}
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ seen["branch_messages"] = branch_messages
+ return ("earlier turn", [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+ branch = [{"role": "user", "content": "on this branch"}]
+
+ tools_mod.execute_tool(
+ "search_conversation",
+ {"query": "pelicans"},
+ thread_id = THREAD,
+ conversation_branch = branch,
+ )
+
+ assert seen["branch_messages"] == branch
+
+
+def test_inline_recall_anchors_only_the_turn_it_rewrote(archived, monkeypatch):
+ """Inline recall appends nothing; it rewrites the latest user message in place.
+
+ Anchoring the last two messages therefore also pinned the assistant turn before it,
+ and with it a whole eviction unit the fit was entitled to drop.
+ """
+ from core.inference import llama_cpp
+
+ conversation = [
+ {"role": "user", "content": "an earlier question"},
+ {"role": "assistant", "content": "an earlier answer"},
+ {"role": "user", "content": "what was that limerick"},
+ ]
+ monkeypatch.setattr(
+ tools_mod,
+ "build_conversation_recall",
+ lambda *args, **kwargs: {"prefix": "RECALLED ", "messages": [], "events": [], "sources": 1},
+ )
+
+ out = llama_cpp._archive_and_recall(
+ conversation,
+ conversation,
+ thread_id = THREAD,
+ style = "inline",
+ recall_done = False,
+ # Any non-zero budget: with none, the fit obtained no room and recall is skipped.
+ recall_budget_tokens = 100_000,
+ )
+
+ assert out["recalled"] is True
+ # Exactly one message is anchored, and it is the rewritten latest user turn.
+ assert len(out["anchored"]) == 1
+ assert out["anchored"][0]["content"].startswith("RECALLED ")
+ assert out["anchored"][0] is out["conversation"][-1]
+ # The assistant turn before it stays evictable.
+ assert id(conversation[1]) not in {id(message) for message in out["anchored"]}
+
+
+def test_tool_recall_anchors_the_synthetic_exchange(archived, monkeypatch):
+ """The tool style DOES append two messages, and those are what must survive a refit."""
+ from core.inference import llama_cpp
+
+ conversation = [{"role": "user", "content": "what was that limerick"}]
+ synthetic = [
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "conv_recall_x"}]},
+ {"role": "tool", "tool_call_id": "conv_recall_x", "content": "an earlier turn"},
+ ]
+ monkeypatch.setattr(
+ tools_mod,
+ "build_conversation_recall",
+ lambda *args, **kwargs: {"messages": synthetic, "events": [], "sources": 1},
+ )
+
+ out = llama_cpp._archive_and_recall(
+ conversation,
+ conversation,
+ thread_id = THREAD,
+ style = "tool",
+ recall_done = False,
+ recall_budget_tokens = 100_000,
+ )
+
+ assert [id(message) for message in out["anchored"]] == [id(m) for m in out["conversation"][-2:]]
+
+
+def test_an_over_budget_recall_is_retried_with_fewer_turns(archived, monkeypatch):
+ """Dropping the lot is the wrong answer when three of four chunks would fit.
+
+ A full top-K of long turns lands just over the reserve once the wrappers are priced,
+ which is the common case here, so an all-or-nothing check disables forced retrieval.
+ """
+ from core.inference import llama_cpp
+
+ conversation = [{"role": "user", "content": "what was that pelicans limerick"}]
+ asked = []
+
+ def build(
+ _conversation,
+ _thread_id,
+ *,
+ style,
+ top_k,
+ branch_messages = None,
+ ):
+ asked.append(top_k)
+ # 1400 characters per requested chunk, so only the smallest k fits the budget.
+ return {"prefix": "R" * (1400 * top_k), "messages": [], "events": [], "sources": top_k}
+
+ monkeypatch.setattr(tools_mod, "build_conversation_recall", build)
+ chars = lambda messages: sum(len(m.get("content") or "") for m in messages)
+
+ out = llama_cpp._archive_and_recall(
+ conversation,
+ conversation,
+ thread_id = THREAD,
+ style = "inline",
+ recall_done = False,
+ # Room for four chunks by the estimate, but only one once actually counted.
+ recall_budget_tokens = 2500,
+ count_tokens = chars,
+ )
+
+ assert asked == [4, 2, 1]
+ assert out["recalled"] is True
+ assert out["counts"]["recalled_chunks"] == 1
+ assert chars(out["conversation"]) > chars(conversation)
+
+
+def test_recall_is_dropped_when_the_real_prompt_exceeds_the_budget(archived, monkeypatch):
+ """The chunk arithmetic is an estimate; the tokenizer is not.
+
+ CHUNK_TOKENS is an embedding-token limit, not the chat template's cost, and neither
+ it nor the budget prices the wrappers, so a nominally-fitting recall can overshoot.
+ """
+ from core.inference import llama_cpp
+
+ conversation = [{"role": "user", "content": "what was that pelicans limerick"}]
+ monkeypatch.setattr(
+ tools_mod,
+ "build_conversation_recall",
+ lambda *args, **kwargs: {
+ "prefix": "R" * 4000,
+ "messages": [],
+ "events": [],
+ "sources": 2,
+ },
+ )
+ chars = lambda messages: sum(len(m.get("content") or "") for m in messages)
+
+ # Budget far below what the injection costs: dropped, and the conversation comes
+ # back untouched rather than over the window.
+ tight = llama_cpp._archive_and_recall(
+ conversation,
+ conversation,
+ thread_id = THREAD,
+ style = "inline",
+ recall_done = False,
+ recall_budget_tokens = 10,
+ count_tokens = chars,
+ )
+ assert tight["recalled"] is False
+ assert tight["conversation"] == conversation
+
+ # Room to spare: the same injection is kept.
+ roomy = llama_cpp._archive_and_recall(
+ conversation,
+ conversation,
+ thread_id = THREAD,
+ style = "inline",
+ recall_done = False,
+ recall_budget_tokens = 100_000,
+ count_tokens = chars,
+ )
+ assert roomy["recalled"] is True
+ assert chars(roomy["conversation"]) > chars(conversation)
+
+
+def test_the_branch_boundary_excludes_the_turn_inline_recall_rewrites():
+ """A continued assistant message puts a prefill after the newest user turn.
+
+ Excluding only the branch's last element then leaves that user message in an
+ identity scan, and inline recall rewrites it into a new dict, so it reads as evicted.
+ The inflated boundary is persisted and costs the next request a live message.
+ """
+ from core.inference import llama_cpp
+
+ user_first = {"role": "user", "content": "first"}
+ answer_first = {"role": "assistant", "content": "first answer"}
+ user_latest = {"role": "user", "content": "latest question"}
+ prefill = {"role": "assistant", "content": "partial answer so far"}
+ branch = [user_first, answer_first, user_latest, prefill]
+
+ # The fit evicted the first turn; inline recall then rewrote the newest user message.
+ rewritten = {"role": "user", "content": "recalled turns\nlatest question"}
+
+ assert llama_cpp._branch_boundary([rewritten, prefill], branch) == 2
+ # And with the turn left alone, the same two messages are still the boundary.
+ assert llama_cpp._branch_boundary([user_latest, prefill], branch) == 2
+
+
+def test_a_conversation_search_charges_token_dense_text_properly(archived, monkeypatch):
+ """Four characters per token is an English rule, and CJK runs near one per character.
+
+ A result accepted at a quarter of its real size lands in the current tool exchange,
+ which the window cannot evict, so the turn can only end in a context-length error.
+ """
+ from core.rag import config as rag_config
+
+ asked = []
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ asked.append(top_k)
+ return ("\u6df1\u5c64\u5b66\u7fd2" * 250 * (top_k or 1), [{"id": "1"}])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ answer = tools_mod._search_conversation(
+ {"query": "pelicans", "top_k": 4},
+ {"thread_id": THREAD, "budget_tokens": rag_config.CHUNK_TOKENS * 2},
+ )
+
+ # The room clamps the request to 2 chunks, and then the size does the rest: 1,000 CJK
+ # characters is about 1,000 tokens, not the 250 the shared estimator claims, so even
+ # one chunk does not fit a 1,000-token budget.
+ assert asked == [2, 1]
+ assert "no room" in answer.lower()
+
+
+def test_a_tool_exchange_this_request_created_stays_on_the_branch(monkeypatch):
+ """A long agent run can evict, and archive, its own earlier tool exchange.
+
+ Filtered against the messages the client sent, that document looks like an abandoned
+ branch and is refused, so the model cannot get back a tool result it still needs.
+ """
+ from pathlib import Path
+
+ source = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"
+ text = " ".join(source.read_text().split())
+
+ # The branch handed to both the forced recall and a model-initiated search is the
+ # accumulated one, never the request's own messages.
+ assert "branch_messages = _extend_live_branch(" in text
+ assert 'kwargs["conversation_branch"] = _extend_live_branch(' in text
+ assert "branch_messages = _request_branch" not in text
+ assert 'kwargs["conversation_branch"] = _request_branch' not in text
+ # And the boundary is still measured against the client's messages, which is what it
+ # will be re-applied to.
+ assert "_branch_boundary(conversation, _request_branch)" in text
+
+
+def test_a_dense_ascii_result_is_priced_by_the_callers_tokenizer(archived, monkeypatch):
+ """Four characters per token is optimistic for code, minified JSON and hashes.
+
+ Those run nearer two or three, so a result could be admitted at well under its real
+ cost and land in the current tool exchange, which the window is not allowed to evict.
+ A tokenizer-backed caller passes its own counter, and the GGUF path is one.
+ """
+ from core.inference import tools as tools_mod
+
+ source = "def f(x):\n return {'a':1,'b':[2,3]}\n" * 400
+
+ def fake_recall(
+ thread_id,
+ query,
+ *,
+ top_k = None,
+ branch_messages = None,
+ ):
+ return (source, [])
+
+ monkeypatch.setattr(conversation_archive, "recall", fake_recall)
+
+ estimated = tools_mod._conversation_search_tokens(source)
+ exact = int(len(source) / 2.6)
+ assert estimated < exact, (estimated, exact)
+
+ # A budget the estimate clears with room to spare and the tokenizer does not.
+ budget = estimated + tools_mod._TOOL_MESSAGE_FRAMING_TOKENS + 10
+ assert budget < exact, (budget, exact)
+
+ admitted = tools_mod._search_conversation(
+ {"query": "the code", "top_k": 1},
+ {"thread_id": THREAD, "budget_tokens": budget},
+ )
+ refused = tools_mod._search_conversation(
+ {"query": "the code", "top_k": 1},
+ {
+ "thread_id": THREAD,
+ "budget_tokens": budget,
+ "token_counter": lambda text: int(len(text) / 2.6),
+ },
+ )
+
+ assert source in admitted
+ assert "no room" in refused.lower()
+
+
+def test_the_anchor_survives_a_tool_call_message_with_no_text(monkeypatch):
+ """The first kept message is often an assistant tool call, which has no content.
+
+ Reading `content` alone recorded an empty anchor there, and an empty anchor is not a
+ stale anchor, it is no anchor: the rebase is skipped entirely and the next request
+ replays the absolute count against a transcript that lost a message in front of it,
+ evicting one live turn for each deleted one. The anchor is taken from the tool calls
+ when there is no text, and read back the same way.
+ """
+ from core.inference import llama_cpp
+
+ call = {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{"function": {"name": "terminal", "arguments": '{"command":"ls -la"}'}}],
+ }
+ branch = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "evicted prompt"},
+ {"role": "assistant", "content": "evicted reply"},
+ call,
+ {"role": "tool", "content": "total 0"},
+ {"role": "user", "content": "the turn just sent"},
+ ]
+ conversation = [branch[0]] + branch[3:]
+
+ anchor = llama_cpp._branch_boundary_anchor(conversation, branch)
+ assert anchor, "a tool-call message left the anchor empty, which disables the rebase"
+ assert llama_cpp._branch_boundary(conversation, branch) == 2
+
+ # The user then deletes one already-evicted turn, so the same cut is one shallower.
+ _fake_studio_db(monkeypatch, [_anchored_row(2, anchor)])
+ shortened = [
+ {"role": "user", "content": "evicted prompt"},
+ call,
+ {"role": "tool", "content": "total 0"},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ assert llama_cpp._sticky_compaction_boundary("t1", shortened) == 1
+
+
+def test_the_anchor_is_bounded_so_a_pasted_prompt_is_not_persisted_per_turn():
+ """The anchor rides in every truncation event and every assistant turn's metadata.
+
+ While the boundary stays sticky that is one copy per reply, so returning a large
+ pasted message whole duplicated it across the thread's SSE payloads and history rows.
+ A head names the message just as well, and the read side only ever clamps the boundary
+ SHALLOWER, so two messages sharing a head cost one extra compaction, never a live turn.
+ """
+ from core.inference import llama_cpp
+
+ pasted = "PASTE " + "z" * 40_000
+ branch = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "evicted prompt"},
+ {"role": "assistant", "content": "evicted reply"},
+ {"role": "user", "content": pasted},
+ {"role": "assistant", "content": "noted"},
+ {"role": "user", "content": "the turn just sent"},
+ ]
+ conversation = [branch[0]] + branch[3:]
+
+ anchor = llama_cpp._branch_boundary_anchor(conversation, branch)
+
+ assert 0 < len(anchor) <= llama_cpp._ANCHOR_TEXT_CHARS
+ assert pasted.startswith(anchor)
+
+
+def test_any_room_at_all_is_worth_one_recall_attempt():
+ """`CHUNK_TOKENS` is a ceiling, not the size of a turn.
+
+ Flooring the budget by it returned zero for every window with less than a full chunk
+ to spare, so automatic recall was disabled on exactly the tight contexts it exists
+ for, even though most archived turns are far smaller. The exact recount downstream is
+ what decides admission, and it rejects a chunk that truly does not fit.
+ """
+ from core.inference import llama_cpp
+ from core.rag import config as rag_config
+
+ assert llama_cpp._recall_top_k(0) == 0
+ assert llama_cpp._recall_top_k(-5) == 0
+ assert llama_cpp._recall_top_k(rag_config.CHUNK_TOKENS - 1) == 1
+ assert llama_cpp._recall_top_k(rag_config.CHUNK_TOKENS * 2) >= 2
diff --git a/studio/backend/tests/test_conversation_search_safetensors_loop.py b/studio/backend/tests/test_conversation_search_safetensors_loop.py
new file mode 100644
index 00000000000..f9316877f9f
--- /dev/null
+++ b/studio/backend/tests/test_conversation_search_safetensors_loop.py
@@ -0,0 +1,193 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`search_conversation` under a safetensors model.
+
+The tool is advertised by thread, not by backend: a GGUF-compacted chat keeps its
+archive across a model switch and `_select_request_tools` is shared, so this loop offers
+the tool too and needs both guards the GGUF loop applies.
+"""
+
+import os
+import sys
+import threading
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from core.inference.safetensors_agentic import run_safetensors_tool_loop # noqa: E402
+from core.inference.tool_call_parser import RAG_MAX_SEARCHES_PER_TURN # noqa: E402
+
+MESSAGES = [
+ {"role": "user", "content": "what was the code from earlier"},
+ {"role": "assistant", "content": "let me look"},
+ {"role": "user", "content": "please"},
+]
+
+
+def _searching_model(calls_wanted):
+ """A model that issues one distinct conversation search per iteration."""
+ state = {"n": 0}
+
+ def single_turn(messages):
+ state["n"] += 1
+ if state["n"] > calls_wanted:
+ yield "done"
+ return
+ call = (
+ '<tool_call>{"name":"search_conversation","arguments":'
+ '{"query":"the code %d"}}</tool_call>' % state["n"]
+ )
+ buffer = ""
+ for char in call:
+ buffer += char
+ yield buffer
+
+ return single_turn
+
+
+def _run(calls_wanted, execute_tool):
+ return list(
+ run_safetensors_tool_loop(
+ single_turn = _searching_model(calls_wanted),
+ messages = list(MESSAGES),
+ tools = [{"type": "function", "function": {"name": "search_conversation"}}],
+ execute_tool = execute_tool,
+ cancel_event = threading.Event(),
+ max_tool_iterations = calls_wanted + 1,
+ thread_id = "t-sf",
+ )
+ )
+
+
+def test_the_loop_hands_its_search_the_active_branch():
+ """Without it the search falls back to the whole stored DAG, siblings included."""
+ seen = []
+
+ def execute_tool(name, arguments, **kwargs):
+ seen.append(kwargs.get("conversation_branch"))
+ return "an earlier turn"
+
+ _run(1, execute_tool)
+
+ assert seen == [MESSAGES]
+
+
+def test_conversation_searches_share_the_per_turn_cap():
+ """Paraphrased re-searches slip past the exact-args duplicate guard.
+
+ Each appends passages into the protected current tool exchange, so uncapped the turn
+ can only end in a context-length error.
+ """
+ executed = []
+
+ def execute_tool(name, arguments, **kwargs):
+ executed.append(arguments.get("query"))
+ return "an earlier turn"
+
+ _run(RAG_MAX_SEARCHES_PER_TURN + 2, execute_tool)
+
+ assert len(executed) == RAG_MAX_SEARCHES_PER_TURN
+
+
+def test_the_budget_charges_token_dense_text_at_its_real_rate():
+ """Four characters per token is about right for English and half the truth for CJK.
+
+ The result side already prices non-ASCII at a token per character; the spend side did
+ not, so a CJK chat reported roughly twice the room it had. This path runs no rolling
+ fit, so nothing downstream recovers: the tool exchange it sized lands in the next
+ prompt and takes it past the window.
+ """
+ from core.inference.context_window import (
+ estimate_messages_tokens,
+ estimate_messages_tokens_dense,
+ prompt_budget,
+ )
+
+ dense_messages = [
+ {"role": "user", "content": "設定を確認してください。" * 40},
+ {"role": "assistant", "content": "承知しました。" * 40},
+ {"role": "user", "content": "先ほどのコードは何でしたか"},
+ ]
+ seen = {}
+ tools = [{"type": "function", "function": {"name": "search_conversation"}}]
+
+ list(
+ run_safetensors_tool_loop(
+ single_turn = _searching_model(1),
+ messages = list(dense_messages),
+ tools = tools,
+ execute_tool = lambda name, arguments, **kwargs: (
+ seen.update(kwargs) or "an earlier turn"
+ ),
+ cancel_event = threading.Event(),
+ max_tool_iterations = 2,
+ thread_id = "t-sf",
+ context_length = 4096,
+ max_tokens = 512,
+ )
+ )
+
+ budget = seen.get("conversation_budget_tokens")
+ assert budget is not None
+ # The flat estimate is the one that overstates the room. Charged densely, the budget
+ # has to be at most what is left after the real cost of what is already there.
+ assert budget <= prompt_budget(4096, 512) - estimate_messages_tokens_dense(dense_messages)
+ assert estimate_messages_tokens_dense(dense_messages) > estimate_messages_tokens(dense_messages)
+
+
+def test_the_dense_estimate_matches_the_flat_one_on_plain_ascii():
+ """It corrects a known undercount, it does not make every English chat pessimistic."""
+ from core.inference.context_window import (
+ estimate_messages_tokens,
+ estimate_messages_tokens_dense,
+ )
+ assert estimate_messages_tokens_dense(MESSAGES) == estimate_messages_tokens(MESSAGES)
+
+
+def test_the_loop_budgets_its_search_against_this_models_context():
+ """Without it the clamp in the tool is skipped and top_k 8 lands unbudgeted.
+
+ Roughly 4K tokens appended into the current tool exchange, which the rolling window
+ protects and cannot evict.
+ """
+ from core.inference.context_window import estimate_messages_tokens, prompt_budget
+
+ seen = {}
+ tools = [{"type": "function", "function": {"name": "search_conversation"}}]
+
+ def execute_tool(name, arguments, **kwargs):
+ seen.update(kwargs)
+ return "an earlier turn"
+
+ list(
+ run_safetensors_tool_loop(
+ single_turn = _searching_model(1),
+ messages = list(MESSAGES),
+ tools = tools,
+ execute_tool = execute_tool,
+ cancel_event = threading.Event(),
+ max_tool_iterations = 2,
+ thread_id = "t-sf",
+ context_length = 4096,
+ max_tokens = 512,
+ )
+ )
+
+ budget = seen.get("conversation_budget_tokens")
+ assert budget is not None
+ # Everything already in the prompt is charged: the messages and the catalogue.
+ assert budget <= prompt_budget(4096, 512) - estimate_messages_tokens(tools)
+ assert budget < prompt_budget(4096, 512) - estimate_messages_tokens(MESSAGES)
+
+
+def test_the_loop_omits_the_budget_when_the_context_is_unknown():
+ """An absent budget must not become a budget of zero, which would refuse every search."""
+ seen = {}
+
+ def execute_tool(name, arguments, **kwargs):
+ seen.update(kwargs)
+ return "an earlier turn"
+
+ _run(1, execute_tool)
+
+ assert "conversation_budget_tokens" not in seen
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 335730a0635..a39e32e2d65 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -3697,7 +3697,12 @@ def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(mo
],
payloads,
)
- backend._effective_context_length = 100
+ # Sized so each window overflows by roughly one turn-group. Compaction trims a
+ # headroom margin BELOW the budget and the turn-picking estimator is coarser than
+ # the exact count, so single-group steps would evict the whole history in one pass
+ # and leave the second preflight nothing to refit. The property under test is that
+ # BOTH preflight paths refit against the window they were given.
+ backend._effective_context_length = 2000
monkeypatch.setattr(
backend,
"count_chat_tokens",
@@ -3707,17 +3712,17 @@ def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(mo
)
def fake_respawn():
- backend._effective_context_length = 60
+ 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" * 25},
- {"role": "assistant", "content": "a" * 25},
- {"role": "user", "content": "u" * 25},
- {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
{"role": "user", "content": "final"},
],
tools = [{"type": "function", "function": {"name": "python"}}],
@@ -3728,8 +3733,8 @@ def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(mo
notices = [event for event in events if event.get("type") == "context_truncated"]
assert [notice["dropped_messages"] for notice in notices] == [2, 2]
- assert [notice["context_length"] for notice in notices] == [100, 60]
- assert [payload["max_tokens"] for payload in payloads] == [100, 60]
+ assert [notice["context_length"] for notice in notices] == [2000, 1000]
+ assert [payload["max_tokens"] for payload in payloads] == [2000, 1000]
assert len(payloads[0]["messages"]) == 3
assert len(payloads[1]["messages"]) == 1
@@ -3897,6 +3902,119 @@ def test_rolling_preflight_counts_the_sanitized_payload(monkeypatch):
assert counted[0] != messages
+def test_a_respawn_refit_archives_what_it_evicts(monkeypatch):
+ """The respawn refits run against a smaller replacement window.
+
+ They evict more of the conversation, and without archiving there those turns are
+ gone for good: unlike the ordinary preflight, nothing else sees them.
+ """
+ import httpx
+ from core.inference import llama_cpp
+
+ archived: list = []
+
+ def fake_archive(conversation, before, **kwargs):
+ archived.append(llama_cpp.evicted_messages(before, conversation))
+ return {"conversation": conversation, "events": [], "counts": {}, "recalled": False}
+
+ monkeypatch.setattr(llama_cpp, "_archive_and_recall", fake_archive)
+
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [httpx.ConnectError("server is down"), [_sse({"content": "OK"}), _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 fake_respawn():
+ backend._effective_context_length = 1000
+ return True
+
+ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "final"},
+ ],
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tool_iterations = 1,
+ context_overflow = "truncate_oldest",
+ thread_id = "t-respawn-archive",
+ )
+ )
+
+ # More than one archiving pass, and the respawn's own evictions are among them.
+ assert len(archived) >= 2
+ assert any(batch for batch in archived[1:])
+
+
+def test_the_respawn_retry_keeps_the_thread(monkeypatch):
+ """The retry refits for the replacement window, so it can evict more.
+
+ Without the thread those extra turns are archived nowhere and no reserve or boundary
+ applies, on the one path that deliberately compacts a second time.
+ """
+ import httpx
+ from core.inference import llama_cpp
+
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [httpx.ConnectError("server is down"), [_sse({"content": "OK"}), _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 fake_respawn():
+ backend._effective_context_length = 1000
+ return True
+
+ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
+ seen: list = []
+ monkeypatch.setattr(
+ llama_cpp,
+ "_conversation_recall_reserve",
+ lambda thread_id: seen.append(thread_id) or 0,
+ )
+
+ list(
+ backend.generate_chat_completion(
+ messages = [
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "final"},
+ ],
+ context_overflow = "truncate_oldest",
+ thread_id = "t-respawn",
+ )
+ )
+
+ # Both fits, the original and the one the retry runs, know which thread they are on.
+ assert len(seen) == 2
+ assert seen == ["t-respawn", "t-respawn"]
+
+
def test_rolling_respawn_retry_refits_when_the_effective_context_changes(monkeypatch):
"""A smaller replacement window can evict more without repeating the first eviction."""
import httpx
@@ -3907,7 +4025,12 @@ def test_rolling_respawn_retry_refits_when_the_effective_context_changes(monkeyp
[httpx.ConnectError("server is down"), [_sse({"content": "OK"}), _done()]],
payloads,
)
- backend._effective_context_length = 100
+ # Sized so each window overflows by roughly one turn-group. Compaction trims a
+ # headroom margin BELOW the budget and the turn-picking estimator is coarser than
+ # the exact count, so single-group steps would evict the whole history in one pass
+ # and leave the second preflight nothing to refit. The property under test is that
+ # BOTH preflight paths refit against the window they were given.
+ backend._effective_context_length = 2000
monkeypatch.setattr(
backend,
"count_chat_tokens",
@@ -3917,17 +4040,17 @@ def test_rolling_respawn_retry_refits_when_the_effective_context_changes(monkeyp
)
def fake_respawn():
- backend._effective_context_length = 60
+ backend._effective_context_length = 1000
return True
monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
events = list(
backend.generate_chat_completion(
messages = [
- {"role": "user", "content": "u" * 25},
- {"role": "assistant", "content": "a" * 25},
- {"role": "user", "content": "u" * 25},
- {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
+ {"role": "user", "content": "u" * 400},
+ {"role": "assistant", "content": "a" * 400},
{"role": "user", "content": "final"},
],
context_overflow = "truncate_oldest",
@@ -3940,8 +4063,8 @@ def test_rolling_respawn_retry_refits_when_the_effective_context_changes(monkeyp
if isinstance(event, dict) and event.get("type") == "context_truncated"
]
assert [notice["dropped_messages"] for notice in notices] == [2, 2]
- assert [notice["context_length"] for notice in notices] == [100, 60]
- assert [payload["max_tokens"] for payload in payloads] == [100, 60]
+ assert [notice["context_length"] for notice in notices] == [2000, 1000]
+ assert [payload["max_tokens"] for payload in payloads] == [2000, 1000]
assert len(payloads[0]["messages"]) == 3
assert len(payloads[1]["messages"]) == 1
@@ -5575,3 +5698,313 @@ def test_parallel_disabled_suppresses_provisional_for_reused_index(monkeypatch):
if e.get("tool_call_id") == "call_term"
and e.get("type") in {"tool_start", "tool_args", "tool_end"}
]
+
+
+def test_conversation_search_budget_counts_the_tool_catalogue(monkeypatch):
+ """The estimator sees the messages only; the tools array is prompt too.
+
+ A large (MCP) catalogue can be thousands of tokens, so a budget ignoring it reports
+ room the request lacks, into a tool exchange the next iteration cannot evict.
+ """
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_s",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query":"the code"}',
+ },
+ }
+ ]
+ }
+ ),
+ _finish("tool_calls"),
+ _done(),
+ ],
+ [_sse({"content": "It was 5150."}), _finish("stop"), _done()],
+ ],
+ payloads,
+ )
+ backend._effective_context_length = 4096
+ # What llama-server would really return: the messages, plus a catalogue that on its
+ # own fills most of the window. The estimator counts the messages and nothing else.
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_a, **_k: 2800
+ + sum(len(str(message.get("content", ""))) for message in candidate) // 10,
+ )
+
+ seen = {}
+
+ def execute_tool(name, arguments, **kwargs):
+ seen.update(kwargs)
+ return "an earlier turn"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute_tool)
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {"role": "user", "content": "u" * 2000},
+ {"role": "assistant", "content": "a" * 2000},
+ {"role": "user", "content": "u" * 2000},
+ {"role": "assistant", "content": "a" * 2000},
+ {"role": "user", "content": "what was the code"},
+ ],
+ tools = [{"type": "function", "function": {"name": "search_conversation"}}],
+ max_tokens = 512,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ from core.inference.context_window import prompt_budget
+
+ budget = seen.get("conversation_budget_tokens")
+ assert budget is not None
+ # 2,800 of the 3,584-token budget is catalogue and framing the estimator cannot see,
+ # so what is left is hundreds of tokens, not the thousands it would have claimed.
+ assert 0 <= budget < 1000
+
+
+def test_a_long_tool_run_reports_a_boundary_in_the_requests_own_terms(monkeypatch):
+ """dropped_messages is summed by the client, and it counts THIS request's messages.
+
+ A tool loop refits every iteration, so a long agent run also counts the tool
+ exchanges it created, which the next request's transcript lacks. Re-applying that
+ total advances the boundary past the turns actually evicted, so the boundary is
+ carried separately, measured against the messages the request was sent with.
+ """
+ calls = 6
+ streams = []
+ for index in range(calls):
+ streams.append(
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": f"c{index}",
+ "function": {
+ "name": "python",
+ "arguments": '{"code": "step %d"}' % index,
+ },
+ }
+ ]
+ }
+ ),
+ _finish("tool_calls"),
+ _done(),
+ ]
+ )
+ streams.append([_sse({"content": "done."}), _finish("stop"), _done()])
+
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, streams, payloads)
+ backend._effective_context_length = 4000
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_a, **_k: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ )
+ // 4,
+ )
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool", lambda name, arguments, **_k: "R" * 3200
+ )
+
+ branch = [
+ # Studio always prepends one and a fit never evicts it, so counting it as the
+ # front of the branch reported zero on every compaction.
+ {"role": "system", "content": "you are helpful"},
+ {"role": "user", "content": "u" * 1200},
+ {"role": "assistant", "content": "a" * 1200},
+ {"role": "user", "content": "u2" * 600},
+ {"role": "assistant", "content": "a2" * 600},
+ {"role": "user", "content": "keep going"},
+ ]
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = branch,
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tokens = 400,
+ max_tool_iterations = calls + 1,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ notices = [
+ event for event in events if event.get("type") == "context_truncated" and event.get("fits")
+ ]
+ assert len(notices) > 1, "the fixture must refit more than once"
+ # Summed, this passes the number of evictable messages the branch ever had.
+ assert sum(notice["dropped_messages"] for notice in notices) > len(branch)
+ # The boundary does not: it says where the branch was cut, so it never passes what the
+ # branch had to give (4; the system prompt and the latest turn are neither evictable
+ # nor counted) and it only ever moves forward.
+ boundaries = [notice["boundary_messages"] for notice in notices]
+ assert max(boundaries) == 4
+ assert boundaries == sorted(boundaries)
+
+
+def test_conversation_search_budget_is_exact_when_nothing_was_truncated(monkeypatch):
+ """`fit_rolling_context` returns None when it drops nothing.
+
+ A prompt that simply FITS, after a context-length increase or on a shorter branch,
+ therefore left the budget to a character estimate that cannot see the template's own
+ framing. It reported room the request did not have, the recall appended a passage too
+ large for the real window, and the next iteration could not evict it again because the
+ current tool exchange is protected.
+ """
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_s",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query":"the code"}',
+ },
+ }
+ ]
+ }
+ ),
+ _finish("tool_calls"),
+ _done(),
+ ],
+ [_sse({"content": "It was 5150."}), _finish("stop"), _done()],
+ ],
+ payloads,
+ )
+ backend._effective_context_length = 4096
+ # Most of the window is catalogue and template framing, which no character estimate
+ # can see. The messages themselves are short, so the fit drops nothing at all.
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_a, **_k: 2800
+ + sum(len(str(message.get("content", ""))) for message in candidate) // 10,
+ )
+
+ seen = {}
+
+ def execute_tool(name, arguments, **kwargs):
+ seen.update(kwargs)
+ return "an earlier turn"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute_tool)
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "what was the code"}],
+ tools = [{"type": "function", "function": {"name": "search_conversation"}}],
+ max_tokens = 512,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ budget = seen.get("conversation_budget_tokens")
+ assert budget is not None
+ # 3,584 of budget against a real prompt of roughly 2,800: hundreds of tokens of room,
+ # not the thousands the estimate claimed from a handful of short messages.
+ assert 0 <= budget < 1000, budget
+
+
+def test_the_exact_recall_budget_is_recomputed_after_an_intervening_tool(monkeypatch):
+ """The exact count is absolute, so caching it for the request goes stale.
+
+ The loop appends the assistant call and the tool result of every intervening tool to
+ the conversation, so a figure taken before them understates the prompt by exactly
+ those exchanges and hands the search room that is already spent.
+ """
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_t",
+ "function": {"name": "terminal", "arguments": '{"command":"ls"}'},
+ }
+ ]
+ }
+ ),
+ _finish("tool_calls"),
+ _done(),
+ ],
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_s",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query":"the code"}',
+ },
+ }
+ ]
+ }
+ ),
+ _finish("tool_calls"),
+ _done(),
+ ],
+ [_sse({"content": "It was 5150."}), _finish("stop"), _done()],
+ ],
+ payloads,
+ )
+ backend._effective_context_length = 4096
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_a, **_k: 1000
+ + sum(len(str(message.get("content", ""))) for message in candidate) // 10,
+ )
+
+ budgets: list = []
+
+ def execute_tool(name, arguments, **kwargs):
+ if name == "search_conversation":
+ budgets.append(kwargs.get("conversation_budget_tokens"))
+ return "an earlier turn"
+ # A big result, which the loop appends before the search runs.
+ return "x" * 12000
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute_tool)
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "what was the code"}],
+ tools = [
+ {"type": "function", "function": {"name": "terminal"}},
+ {"type": "function", "function": {"name": "search_conversation"}},
+ ],
+ max_tokens = 512,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ assert budgets and budgets[0] is not None
+ # The 12,000-character tool result is roughly 1,200 tokens of the 3,584-token budget,
+ # and the count taken before it cannot see them.
+ assert budgets[0] < 1400, budgets
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index a32d3e50126..9af299cb6a1 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -218,6 +218,56 @@ def test_structured_call_executes_and_continues(executed):
assert follow_up[-1]["content"] == "RESULT<web_search>"
+def test_a_conversation_search_here_gets_the_active_branch(executed):
+ """The provider loops share the local paths' tool catalogue.
+
+ So search_conversation is advertised here once a thread has an archive, and needs the
+ branch for the same reason: the stored rows are the whole DAG, Retry included.
+ """
+ branch = [
+ {"role": "user", "content": "what was the code"},
+ {"role": "assistant", "content": "let me look"},
+ {"role": "user", "content": "please"},
+ ]
+ transport = FakeTransport(
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_c",
+ "function": {
+ "name": "search_conversation",
+ "arguments": '{"query":"the code"}',
+ },
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "It was 5150."}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+
+ _run(transport, tools = [_tool("search_conversation")], messages = branch)
+
+ assert [call["name"] for call in executed] == ["search_conversation"]
+ assert executed[0]["conversation_branch"] == branch
+ # And a budget, or the tool's clamp is skipped and a model-chosen top_k of 8 appends
+ # roughly 4K tokens to a prompt this loop replays. Studio cannot measure an external
+ # model's window, so the cap is one ordinary recall's worth.
+ from core.rag import config as rag_config
+
+ assert (
+ executed[0]["conversation_budget_tokens"]
+ == rag_config.CHUNK_TOKENS * rag_config.CONVERSATION_ARCHIVE_TOP_K
+ )
+
+
def test_streamed_tool_name_fragments_are_not_concatenated(executed):
"""llama-server re-sends the whole name as it grows: web -> web_search."""
transport = FakeTransport(
diff --git a/studio/frontend/src/components/assistant-ui/compaction-notice.tsx b/studio/frontend/src/components/assistant-ui/compaction-notice.tsx
new file mode 100644
index 00000000000..0f49ff0ca0e
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/compaction-notice.tsx
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { ArchiveIcon } from "lucide-react";
+import type { FC } from "react";
+
+import type { ContextTruncation } from "@/features/chat/utils/context-truncation";
+
+/**
+ * Tells the user their conversation was compacted, on the turn where it STARTED.
+ *
+ * Deliberately NOT a message: it renders inside the assistant message's container from
+ * `metadata.custom.contextTruncation`, so it is never sent to the model, editable, or
+ * exported as content, yet unlike a toast it survives a reload and stays attached to the
+ * turn it describes.
+ *
+ * Rendered once per COMPACTION, gated by the caller, not once per compacted turn: a
+ * thread past its window refits on every request, so per-turn would mean a notice on
+ * every reply forever. The caller shows this only when the eviction boundary moved.
+ */
+export const CompactionNotice: FC<{ truncation: ContextTruncation }> = ({
+ truncation,
+}) => {
+ if (!truncation?.fits || !truncation.dropped_messages) return null;
+
+ const dropped = truncation.dropped_messages;
+ const archived = truncation.archived_messages ?? 0;
+ const recalled = truncation.recalled_chunks ?? 0;
+
+ const detail = archived
+ ? "They are saved and searchable, and the parts relevant to each question are brought back automatically."
+ : "The full conversation is still visible and saved here.";
+
+ return (
+ <div
+ className="aui-compaction-notice mb-3 flex items-start gap-2 rounded-lg border border-border/60 bg-muted/40 px-3 py-2 text-ui-13 text-muted-foreground"
+ data-testid="compaction-notice"
+ data-dropped={dropped}
+ data-archived={archived}
+ data-recalled={recalled}
+ >
+ <ArchiveIcon className="mt-0.5 size-3.5 shrink-0" aria-hidden />
+ <div className="min-w-0">
+ <span className="font-medium text-foreground/80">
+ This conversation got long, so it was compacted.
+ </span>{" "}
+ <span>
+ Older messages were dropped from the model&apos;s context to make room. {detail}
+ </span>
+ <span>
+ {" "}
+ ({dropped} {dropped === 1 ? "message" : "messages"} dropped here
+ {recalled > 0
+ ? `, ${recalled} earlier ${recalled === 1 ? "passage" : "passages"} recalled`
+ : ""}
+ .)
+ </span>
+ </div>
+ </div>
+ );
+};
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 1bb7109f0c5..09d4e6d6aef 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -9,6 +9,11 @@ import {
GeneratedImageOverlayProvider,
useGeneratedImageOverlay,
} from "@/components/assistant-ui/generated-image-overlay-context";
+import { CompactionNotice } from "@/components/assistant-ui/compaction-notice";
+import {
+ compactionBoundary,
+ type ContextTruncation,
+} from "@/features/chat/utils/context-truncation";
import { downloadImagePart } from "@/components/assistant-ui/image";
import { MarkdownText } from "@/components/assistant-ui/markdown-text";
import { MessageHtmlArtifacts } from "@/components/assistant-ui/message-html-artifacts";
@@ -6792,6 +6797,42 @@ const AssistantMessage: FC = () => {
? custom.researchRunId
: null;
});
+ // Persisted on the assistant turn that compacted, so the notice survives a reload.
+ const contextTruncation = useAuiState(({ message }) => {
+ const custom = (
+ message.metadata as
+ | { custom?: { contextTruncation?: unknown } }
+ | undefined
+ )?.custom;
+ const value = custom?.contextTruncation;
+ return value && typeof value === "object"
+ ? (value as ContextTruncation)
+ : null;
+ });
+ // Once a thread outgrows the window every request runs the fit, so "this turn
+ // compacted" is true of every later reply and would put a notice on all of them. What
+ // matters is when MORE of the conversation fell out of view: the eviction boundary
+ // rising above the last turn that reported one. Between moves the model sees the same
+ // history, so there is nothing new to say.
+ const showsNotice = useAuiState(({ thread }) => {
+ let previousDropped = 0;
+ for (const message of thread.messages) {
+ if (message.role !== "assistant") continue;
+ const value = (
+ message.metadata as
+ | { custom?: { contextTruncation?: unknown } }
+ | undefined
+ )?.custom?.contextTruncation as ContextTruncation | undefined;
+ const dropped = compactionBoundary(value);
+ if (dropped > previousDropped) {
+ if (message.id === messageId) return true;
+ previousDropped = dropped;
+ } else if (message.id === messageId) {
+ return false;
+ }
+ }
+ return false;
+ });
const incognito = useChatRuntimeStore((s) => s.incognito);
// Use global store for editing state to ensure a single source of truth
@@ -6866,6 +6907,9 @@ const AssistantMessage: FC = () => {
onBlur={focusReveal.onBlur}
>
<div className="aui-assistant-message-content wrap-break-word min-w-0 text-[#0d0d0d] dark:text-foreground leading-relaxed">
+ {contextTruncation && showsNotice && !isEditing && (
+ <CompactionNotice truncation={contextTruncation} />
+ )}
{isEditing ? (
<div className="flex flex-col gap-2 w-full">
<textarea
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 7a278ec1883..21b2be2f5ef 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -5663,16 +5663,29 @@ 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;
if (
+ reallyCompacted &&
resolvedThreadId &&
activeThreadId === resolvedThreadId &&
!rollingContextNoticeThreads.has(resolvedThreadId)
) {
rollingContextNoticeThreads.add(resolvedThreadId);
- toast.info("Older turns omitted from model context", {
- description:
- "The full conversation is still visible and saved. " +
- "Studio removed complete older turns from this request so the chat can continue.",
+ // Once per thread per page load; the persistent record is the notice on
+ // the assistant turn that compacted.
+ const archived = contextTruncation?.archived_messages ?? 0;
+ toast.info("This conversation was compacted", {
+ description: archived
+ ? "It got long, so older turns were removed from the model's " +
+ "context. They are saved and searchable, and relevant parts are " +
+ "brought back automatically."
+ : "The full conversation is still visible and saved. " +
+ "Studio removed complete older turns from this request so the chat can continue.",
duration: 8000,
});
}
@@ -6764,14 +6777,45 @@ export function createOpenAIStreamAdapter(
duration: 8000,
});
} else if (isContextLimitError(msg)) {
- // llama-server runs with --no-context-shift, returning a hard
- // error instead of silently dropping old KV-cache turns. Point
- // the user at the control that raises the ceiling.
+ // `fits: false` means everything evictable was evicted and the request STILL
+ // does not fit, so the message just sent is the problem and the usual advice
+ // is wrong: the history is already gone. Say which part is too long.
+ const irreducible =
+ contextTruncation?.fits === false ? contextTruncation : null;
+ // Against prompt_target, not context_length: the fit reserves up to a quarter
+ // of the window for the reply, so a 3,500-token message cannot fit a 4,096
+ // context, and comparing with the raw window would blame the conversation and
+ // send the user to a new chat that fails identically.
+ const budget =
+ irreducible?.prompt_target ?? irreducible?.context_length ?? 0;
+ const oneTurnIsTheProblem =
+ irreducible != null && (irreducible.latest_turn_tokens ?? 0) > budget;
+ // Whose turn it is decides the advice: in a tool loop the offending turn is
+ // often output the user never wrote and cannot edit, so "shorten this
+ // message" names the wrong thing and offers no remedy.
+ const userCanShortenIt =
+ (irreducible?.latest_turn_role ?? "user") === "user";
+ const tooLong =
+ `${irreducible?.latest_turn_tokens?.toLocaleString()} tokens on its own, ` +
+ `against the ${budget.toLocaleString()} tokens this ` +
+ `${irreducible?.context_length?.toLocaleString()}-token window leaves for the prompt. ` +
+ "The earlier turns were already removed and it still does not fit, so " +
+ "shortening the conversation will not help. ";
toast.error("Context limit reached", {
- description:
- "The conversation has filled the model's context window. " +
- 'Increase "Context Length" in the chat Settings panel (⚙ in the top-right), ' +
- "or start a new chat.",
+ description: oneTurnIsTheProblem
+ ? userCanShortenIt
+ ? `This message is ${tooLong}` +
+ 'Shorten this message, or raise "Context Length" ' +
+ "in the chat Settings panel (⚙ in the top-right)."
+ : `The last tool result is ${tooLong}` +
+ 'Raise "Context Length" in the chat Settings panel (⚙ in the top-right), ' +
+ "or ask for less output from that tool."
+ : // llama-server runs with --no-context-shift, returning a hard
+ // error instead of silently dropping old KV-cache turns. Point
+ // the user at the control that raises the ceiling.
+ "The conversation has filled the model's context window. " +
+ 'Increase "Context Length" in the chat Settings panel (⚙ in the top-right), ' +
+ "or start a new chat.",
duration: 8000,
});
} else {
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 8a0b2546fe0..81aba150069 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -698,5 +698,29 @@ export interface OpenAIChatChunk {
prompt_tokens_after?: number;
context_length?: number;
fits: boolean;
+ // Present when the evicted turns were archived and searched. Counts only, never
+ // message text: this rides an SSE chunk that reaches the client.
+ archived_messages?: number;
+ recalled_chunks?: number;
+ // Present only when `fits` is false: the floor the conversation cannot go below, and
+ // how much of it is the message just sent. Together they say whether the history or
+ // that one message is the problem, i.e. whether "shorten the conversation" helps.
+ irreducible_tokens?: number;
+ latest_turn_tokens?: number;
+ // Where the compaction boundary sits in the messages THIS request was sent with.
+ // Absolute, unlike dropped_messages, so re-sending it after a turn that refit several
+ // times cannot advance the boundary past the turns actually evicted.
+ boundary_messages?: number;
+ // The text the boundary landed ON, so the count can be re-derived by position. A count
+ // is only valid against the transcript it was counted on, and deleting an already
+ // evicted prompt shortens that transcript; without the anchor the replayed count then
+ // evicts live turns instead. Carried through untouched, like boundary_messages.
+ boundary_anchor?: string;
+ // Whose message that is: in a tool loop the last one is often a tool result rather
+ // than anything the user typed.
+ latest_turn_role?: string;
+ // The prompt's share of the window (context_length minus the reply reserve), which is
+ // what one turn must fit inside. Not re-derived here: the formula lives in the fit.
+ prompt_target?: number;
};
}
diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.ts
index a888b5a409a..ef3f23ec332 100644
--- a/studio/frontend/src/features/chat/utils/context-truncation.ts
+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts
@@ -7,13 +7,33 @@ export type ContextTruncation = NonNullable<
OpenAIChatChunk["context_truncated"]
>;
+function spreadSum(
+ key: "archived_messages" | "recalled_chunks",
+ a: number | undefined,
+ b: number | undefined,
+): Record<string, number> {
+ if (a === undefined && b === undefined) return {};
+ return { [key]: (a ?? 0) + (b ?? 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;
+}
+
export function mergeContextTruncation(
current: ContextTruncation | undefined,
incoming: ContextTruncation,
): ContextTruncation {
if (!current) return incoming;
- return {
+ const merged = {
...current,
...incoming,
dropped_messages: current.dropped_messages + incoming.dropped_messages,
@@ -21,5 +41,25 @@ export function mergeContextTruncation(
current.prompt_tokens_before ?? incoming.prompt_tokens_before,
prompt_tokens_after:
incoming.prompt_tokens_after ?? current.prompt_tokens_after,
+ // A turn can compact more than once (the tool loop refits per iteration), so these
+ // accumulate rather than taking the last chunk's value. Spread conditionally so a
+ // plain rolling-window response keeps its old shape, with no archive keys set to
+ // undefined.
+ ...spreadSum("archived_messages", current.archived_messages, incoming.archived_messages),
+ ...spreadSum("recalled_chunks", current.recalled_chunks, incoming.recalled_chunks),
};
+
+ // boundary_messages needs no rule: it is absolute, so the spread above already keeps
+ // the latest fit's value. Summing it is the bug it exists to fix. boundary_anchor rides
+ // along with it for the same reason, and the two must come from the SAME fit.
+
+ // The irreducible diagnosis describes ONE fit that gave up, so an earlier failure
+ // followed by a later success would otherwise leave those numbers on a result that fit.
+ // Deleted rather than spread as undefined, which would put both keys on every ordinary
+ // response; delete on an absent key is a no-op.
+ if (incoming.fits) {
+ delete merged.irreducible_tokens;
+ delete merged.latest_turn_tokens;
+ }
+ return merged;
}
diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.ts
index 65f2e79570b..7950a42ad3d 100644
--- a/studio/frontend/tests/rolling-context-window.test.ts
+++ b/studio/frontend/tests/rolling-context-window.test.ts
@@ -4,7 +4,10 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
-import { mergeContextTruncation } from "../src/features/chat/utils/context-truncation.ts";
+import {
+ compactionBoundary,
+ mergeContextTruncation,
+} from "../src/features/chat/utils/context-truncation.ts";
const adapter = readFileSync(
new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
@@ -18,7 +21,7 @@ const transport = readFileSync(
test("local chat opts into the rolling context policy", () => {
assert.match(adapter, /isGguf === true/);
assert.match(adapter, /context_overflow:\s*"truncate_oldest"/);
- assert.match(adapter, /Older turns omitted from model context/);
+ assert.match(adapter, /This conversation was compacted/);
});
test("the transport preserves standard chunks with context metadata", () => {
@@ -27,6 +30,40 @@ test("the transport preserves standard chunks with context metadata", () => {
assert.match(adapter, /contextTruncation = mergeContextTruncation\(/);
});
+test("the compaction notice follows the boundary, not the accumulated drops", () => {
+ // A tool-heavy turn reports 12 drops while the boundary moved to 4. Recording 12 as
+ // the high-water mark means the next two real advances, to 8 and to 10, are silent.
+ assert.equal(
+ compactionBoundary({ dropped_messages: 12, boundary_messages: 4, fits: true }),
+ 4,
+ );
+ // Turns saved before the boundary existed still report something.
+ assert.equal(compactionBoundary({ dropped_messages: 6, fits: true }), 6);
+ // A fit that gave up moved no boundary at all.
+ assert.equal(
+ compactionBoundary({ dropped_messages: 0, boundary_messages: 0, fits: false }),
+ 0,
+ );
+ assert.equal(compactionBoundary(undefined), 0);
+});
+
+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
+ // past the turns actually evicted. The boundary is carried separately and absolutely.
+ const combined = mergeContextTruncation(
+ mergeContextTruncation(undefined, {
+ dropped_messages: 4,
+ boundary_messages: 4,
+ fits: true,
+ }),
+ { dropped_messages: 4, boundary_messages: 4, fits: true },
+ );
+
+ assert.equal(combined.dropped_messages, 8);
+ assert.equal(combined.boundary_messages, 4);
+});
+
test("tool-loop truncation metadata accumulates across stream events", () => {
const first = mergeContextTruncation(undefined, {
dropped_messages: 2,
@@ -51,3 +88,233 @@ test("tool-loop truncation metadata accumulates across stream events", () => {
fits: true,
});
});
+
+
+test("compaction counts accumulate and stay absent on a plain rolling window", () => {
+ // A plain rolling-window response must keep exactly the shape it had before the
+ // conversation archive existed, rather than carrying archive keys set to undefined.
+ const plain = mergeContextTruncation(
+ { dropped_messages: 1, fits: true },
+ { dropped_messages: 2, fits: true },
+ );
+ assert.ok(!("archived_messages" in plain));
+ assert.ok(!("recalled_chunks" in plain));
+
+ const archived = mergeContextTruncation(
+ { dropped_messages: 1, fits: true, archived_messages: 2, recalled_chunks: 4 },
+ { dropped_messages: 2, fits: true, archived_messages: 3, recalled_chunks: 1 },
+ );
+ assert.equal(archived.archived_messages, 5);
+ assert.equal(archived.recalled_chunks, 5);
+});
+
+test("the compaction notice renders from persisted metadata, not from a message", () => {
+ const notice = readFileSync(
+ new URL("../src/components/assistant-ui/compaction-notice.tsx", import.meta.url),
+ "utf8",
+ );
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ // Read off metadata.custom so it can never become part of the conversation.
+ assert.match(thread, /custom\?\.contextTruncation/);
+ assert.match(thread, /<CompactionNotice truncation=\{contextTruncation\}/);
+ assert.match(notice, /This conversation got long, so it was compacted/);
+});
+
+test("the compaction notice is gated on the eviction boundary MOVING", () => {
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ // Every request after the window fills runs the fit, so "this turn compacted" puts a
+ // notice on every reply. The trigger is dropped_messages rising above the last turn
+ // that reported it: more of the conversation actually leaving the context.
+ assert.match(thread, /const showsNotice = useAuiState/);
+ assert.match(thread, /contextTruncation && showsNotice && !isEditing/);
+ assert.match(thread, /dropped > previousDropped/);
+ // Walked in order, not against the preceding message: turns between two moves report
+ // the same count and must not reset the baseline.
+ assert.match(thread, /for \(const message of thread\.messages\)/);
+});
+
+// The gate is a pure function of the thread's persisted truncation counts, so it can be
+// evaluated directly on the sequences the server actually produces.
+const noticeTurns = (dropped: (number | null)[]): number[] => {
+ const shown: number[] = [];
+ let previousDropped = 0;
+ dropped.forEach((value, index) => {
+ const d = value ?? 0;
+ if (d > previousDropped) {
+ shown.push(index);
+ previousDropped = d;
+ }
+ });
+ return shown;
+};
+
+test("one notice per compaction, and silence on the turns in between", () => {
+ // A compaction, a stretch of turns whose boundary does not move, then another.
+ assert.deepStrictEqual(
+ noticeTurns([0, 0, 52, 52, 52, 52, 52, 62, 62, 62, 74]),
+ [2, 7, 10],
+ );
+ // The uncompacted case stays silent throughout.
+ assert.deepStrictEqual(noticeTurns([0, 0, 0]), []);
+ // A single compaction that never moves again is reported exactly once.
+ assert.deepStrictEqual(noticeTurns([36, 36, 36]), [0]);
+});
+
+test("a boundary that goes BACKWARDS does not re-announce", () => {
+ // A rollback leaves a shorter branch needing less eviction. Less is missing than
+ // before, so there is nothing to say and the baseline must not be dragged down.
+ assert.deepStrictEqual(noticeTurns([52, 20, 20, 20]), [0]);
+});
+
+/** The source of one function, by brace matching from its declaration. */
+const functionBody = (source: string, name: string): string => {
+ const start = source.indexOf(`function ${name}(`);
+ if (start < 0) return "";
+ const open = source.indexOf("{", start);
+ let depth = 0;
+ for (let index = open; index < source.length; index += 1) {
+ if (source[index] === "{") depth += 1;
+ else if (source[index] === "}") {
+ depth -= 1;
+ if (depth === 0) return source.slice(start, index + 1);
+ }
+ }
+ return "";
+};
+
+test("the notice is a NOTICE, never part of the conversation", () => {
+ const thread = readFileSync(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const adapter = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ const exporter = readFileSync(
+ new URL("../src/features/chat/utils/conversation-markdown-export.ts", import.meta.url),
+ "utf8",
+ );
+
+ // 1. A sibling of the rendered content parts, not one of them: inside
+ // MessagePrimitive.Parts everything that walks parts would pick it up.
+ const noticeAt = thread.indexOf("<CompactionNotice");
+ const partsAt = thread.indexOf("<MessagePrimitive.Parts", noticeAt);
+ assert.ok(noticeAt > 0 && partsAt > noticeAt);
+ assert.ok(
+ !/<MessagePrimitive\.Parts[^>]*>[\s\S]*<CompactionNotice/.test(thread),
+ "the notice must not be rendered inside the message's content parts",
+ );
+
+ // 2. Nothing that builds a request may read the key it renders from. Bounded to the
+ // function bodies: slicing to end-of-file also catches the streaming handler,
+ // which reads contextTruncation legitimately on the way IN.
+ for (const name of ["toOpenAIMessages", "serializeAssistantReplayMessages"]) {
+ const body = functionBody(adapter, name);
+ assert.ok(body.length > 0, `${name} not found`);
+ assert.ok(
+ !body.includes("contextTruncation"),
+ `${name} must never read contextTruncation`,
+ );
+ }
+
+ // 3. Nor may the user-facing export, which is the other way text leaves a thread.
+ assert.ok(!exporter.includes("contextTruncation"));
+ assert.ok(!exporter.includes("compacted"));
+
+ // 4. Suppressed while editing, so it cannot be saved back as message text.
+ assert.match(thread, /contextTruncation && showsNotice && !isEditing/);
+});
+
+test("an irreducible fit reports a diagnosis, and it is dropped once something fits", () => {
+ // A fit that gave up carries the numbers that say WHICH part is too long.
+ const failed = mergeContextTruncation(undefined, {
+ dropped_messages: 0,
+ fits: false,
+ prompt_tokens_before: 10290,
+ prompt_tokens_after: 10290,
+ context_length: 4096,
+ irreducible_tokens: 5050,
+ latest_turn_tokens: 5000,
+ });
+ assert.equal(failed.fits, false);
+ assert.equal(failed.latest_turn_tokens, 5000);
+
+ // The loop refits per iteration, and an iteration that DOES fit must not carry the
+ // earlier failure's numbers forward, where they describe nothing.
+ const recovered = mergeContextTruncation(failed, {
+ dropped_messages: 12,
+ fits: true,
+ prompt_tokens_after: 3000,
+ context_length: 4096,
+ });
+ assert.equal(recovered.fits, true);
+ assert.ok(!("irreducible_tokens" in recovered));
+ assert.ok(!("latest_turn_tokens" in recovered));
+
+ // And an ordinary response never grows the keys at all, not even set to undefined.
+ const plain = mergeContextTruncation(
+ { dropped_messages: 1, fits: true },
+ { dropped_messages: 2, fits: true },
+ );
+ assert.ok(!("irreducible_tokens" in plain));
+ assert.ok(!("latest_turn_tokens" in plain));
+});
+
+test("the too-long advice depends on WHICH part does not fit", () => {
+ const adapterSource = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ // Telling someone to shorten the conversation is a dead end when the history has
+ // already been evicted and the single message is what overflows.
+ assert.match(adapterSource, /contextTruncation\?\.fits === false/);
+ assert.match(adapterSource, /shortening the conversation will not help/);
+ assert.match(adapterSource, /latest_turn_tokens/);
+});
+
+test("a fits:false diagnosis is not a compaction", () => {
+ const source = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "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/);
+});
+
+test("the advice depends on WHOSE turn does not fit", () => {
+ const source = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ // A tool loop refits with the tool result appended, so the offending turn is often
+ // output the user never wrote and cannot edit, leaving no remedy.
+ assert.match(source, /latest_turn_role/);
+ assert.match(source, /const userCanShortenIt =/);
+ assert.match(source, /The last tool result is/);
+ // The user-authored case keeps its advice, and an older server that sends no role
+ // still gets it (the default is "user").
+ assert.match(source, /latest_turn_role \?\? "user"/);
+ assert.match(source, /Shorten this message/);
+});
+
+test("the too-long check uses the prompt budget, not the raw window", () => {
+ const source = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ // The fit reserves up to a quarter of the window for the reply, so a 3,500-token
+ // message cannot fit a 4,096-token context. The raw window would blame the
+ // conversation and send the user to a new chat that fails identically.
+ assert.match(source, /irreducible\?\.prompt_target \?\? irreducible\?\.context_length/);
+ assert.match(source, /latest_turn_tokens \?\? 0\) > budget/);
+});