Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: recall the latest version of a fact, not the most quotable one (#9161)
Daniel Han2affd53e1fac
diff --git a/studio/backend/core/inference/instruction_pin.py b/studio/backend/core/inference/instruction_pin.pynew file mode 100644index 00000000000..c541065a643--- /dev/null+++ b/studio/backend/core/inference/instruction_pin.py@@ -0,0 +1,278 @@+# 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 user's standing instructions when the rolling window evicts everything else.++The defect this exists for. `context_window.truncate_oldest_messages` protects system and+developer groups, the final group, and the newest USER group. So "do task B, and always+report results as a table" is safe only while it IS the newest user turn. After a few+agent turns and a short follow-up -- "continue", "yes", "keep going" -- the newest user+group is that filler, and the instruction becomes an ordinary eviction candidate: the+oldest one, so the first to go.++Then the archive cannot rescue it either, because the forced recall on the compaction+turn uses the latest user message as its query. The archive gets searched for the word+"continue".++That follow-up is not a contrived case. OpenCode writes a synthetic "Continue if you have+next steps" turn after every auto compaction, and Zed emits "Continue where you left+off", so in both, the newest user turn straight after a compaction is filler by+construction. Everyone else's answer is to ask a summarizer to remember the instruction;+this is the deterministic version, and Zed's 80 KB verbatim replay of recent user+messages is the closest existing thing to it.++Two knobs, both off by default so the change ships inert:++ ROLLING_INSTRUCTION_PIN_GROUPS how many instruction groups to hold (0 = today)+ ROLLING_INSTRUCTION_PIN_MAX_TOKENS absolute ceiling on what they may cost++The pin is applied through `truncate_oldest_messages`'s existing `protected_message_ids`+parameter, so nothing in the rolling-window layer changes.+"""++from __future__ import annotations++import os+import re++from core.inference.context_window import estimate_messages_tokens_dense, group_turns++# 80 characters: someone who typed a paragraph wrote an instruction. Nothing inspects+# meaning or keywords, which are the heuristics a user trips by accident.+INSTRUCTION_MIN_CHARS = int(os.environ.get("ROLLING_INSTRUCTION_MIN_CHARS", "80"))+PIN_GROUPS = int(os.environ.get("ROLLING_INSTRUCTION_PIN_GROUPS", "0"))+PIN_MAX_TOKENS = int(os.environ.get("ROLLING_INSTRUCTION_PIN_MAX_TOKENS", "1024"))+# ... and never more than this share of the prompt budget, so the pin stays a minority of+# the window on a small model as well as a large one.+PIN_MAX_FRACTION = float(os.environ.get("ROLLING_INSTRUCTION_PIN_MAX_FRACTION", "0.10"))++# A pure REJECT list: it can only stop something being treated as an instruction, never+# promote one.+_CONTINUATIONS = frozenset(+ {+ "continue",+ "continue please",+ "carry on",+ "go on",+ "go ahead",+ "keep going",+ "proceed",+ "next",+ "more",+ "yes",+ "y",+ "yeah",+ "yep",+ "ok",+ "okay",+ "k",+ "sure",+ "no",+ "n",+ "nope",+ "thanks",+ "thank you",+ "ta",+ "done",+ "good",+ "great",+ "fine",+ "please continue",+ "please carry on",+ "resume",+ "and",+ "then",+ }+)+# U+2026 and U+2025 as well as the ASCII spellings: keyboards autocorrect "..." to one+# ellipsis character, so `continue…` matched nothing and recall searched for "continue".+_PUNCTUATION = re.compile(r"[\s\.,!\?;:\-–—\u2025\u2026]+")++# "Anaphoric" as a closed list rather than a word count: words that cannot name the+# subject of a request. "what about it" has nothing to search for; "review billing" names+# its own subject and keeps its retrieval slots. Negation is left out on purpose, as in+# `store._ARCHIVE_STOPWORDS`: a missed anchor is cheaper than a wrong one.+_FUNCTION_WORDS = frozenset(+ """+a about all also am an and another any anything are as at be been being both but by can+could did do does doing each either else even ever for from get give had has have he her+here him his how i if in into is it its just like me mine my of on once one only or other+our ours out over please same she should so some someone something still such than that+the their theirs them then there these they thing things this those to too us was we were+what when where which while who whom whose why will with would you your yours+""".split()+)+++def _text_of(message: dict) -> str:+ content = message.get("content")+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ parts = []+ for part in content:+ if isinstance(part, dict) and isinstance(part.get("text"), str):+ parts.append(part["text"])+ return "\n".join(parts)+ return ""+++def _has_non_text_part(message: dict) -> bool:+ """An upload is never filler. A one-word message with an image attached is a real+ request, and treating it as a continuation would pin the wrong turn."""+ content = message.get("content")+ if not isinstance(content, list):+ return False+ return any(+ isinstance(part, dict) and part.get("type") not in (None, "text") for part in content+ )+++def is_substantive(message: dict, *, min_chars: int = INSTRUCTION_MIN_CHARS) -> bool:+ """Whether a user message is an instruction rather than a nudge to keep going."""+ if message.get("role") != "user":+ return False+ if _has_non_text_part(message):+ return True+ text = _text_of(message).strip()+ if len(text) < min_chars:+ return False+ normalised = _PUNCTUATION.sub(" ", text.lower()).strip()+ return normalised not in _CONTINUATIONS+++def last_substantive_instruction(+ messages: list[dict],+ *,+ min_chars: int = INSTRUCTION_MIN_CHARS,+ skip_latest: bool = True,+) -> str | None:+ """The most recent real instruction, for use as a recall query.++ ``skip_latest`` skips the newest user message, which is the one that was too thin to+ search with in the first place.+ """+ users = [m for m in messages if m.get("role") == "user"]+ if skip_latest and users:+ users = users[:-1]+ for message in reversed(users):+ if is_substantive(message, min_chars = min_chars):+ text = _text_of(message).strip()+ if text:+ return text+ return None+++def is_thin_query(text: str, *, min_chars: int = INSTRUCTION_MIN_CHARS) -> bool:+ """Whether searching an archive for this text is worth a retrieval slot.++ Thin means the message NAMES NOTHING TO SEARCH FOR: every word of it is a function+ word, an anaphor or a continuation. It deliberately does not mean "short". Counting+ words instead swept in every self-contained two-word request -- "review billing",+ "restart nginx", "ZQXVARA123?" -- and the anchor a thin query earns is spent ahead of+ the user's own words in `conversation_archive.recall`. At the top_k of 1 that both the+ over-budget backoff (4 -> 2 -> 1) and a small window (`_recall_top_k` is+ `budget // CHUNK_TOKENS`) reach, the anchor takes the only slot: measured on a+ nine-turn archive, "review billing" at top_k=1 recalled the standing instruction and+ NOT the billing turn, which the same recall returns without an anchor.+ """+ stripped = (text or "").strip()+ if not stripped:+ return True+ if len(stripped) >= min_chars:+ return False+ normalised = _PUNCTUATION.sub(" ", stripped.lower()).strip()+ if normalised in _CONTINUATIONS:+ return True+ # Short AND anaphoric: "what is ZQXVARA123?" names something and stays the query.+ words = normalised.split()+ if not words:+ # Punctuation only ("???"): nothing survives tokenisation, so the query is empty.+ return True+ return all(word in _FUNCTION_WORDS or word in _CONTINUATIONS for word in words)+++def _protected_cost(turns: list[list[dict]], index: int) -> int:+ """What pinning the head of ``turns[index]`` actually costs the window.++ `truncate_oldest_messages` protects by GROUP, not by message, and `group_turns` puts+ an assistant reply that carries no tool calls in the SAME group as the user message it+ answers. So pinning a one-line instruction also holds that reply, and charging only the+ instruction let a pin exceed the ceiling by an arbitrary amount: measured at 28 tokens+ charged against 20037 actually held. The budget has to count what is really kept, or it+ is not a budget.++ It must not count more than that either. A trailing tool exchange is NOT held: an+ assistant message with tool calls opens its own group, and `truncate_oldest_messages`+ skips a protected group BEFORE the `starts_user_turn` expansion that would otherwise+ absorb the groups behind it, so that tool group stays its own eviction unit and is+ evicted independently of the pin. Charging it would let one large tool result cost a+ small instruction its pin over tokens the pin never keeps -- which is the case the pin+ exists for, since an agent run is exactly where the filler follow-up appears.+ """+ # Dense: 4 chars per token undercharges CJK and emoji ~2x, so a 1056-token turn was+ # charged 276 and cleared a 1024 ceiling. Over-charging only refuses the pin.+ return estimate_messages_tokens_dense(turns[index])+++def pinned_instruction_ids(+ messages: list[dict],+ *,+ groups: int = PIN_GROUPS,+ min_chars: int = INSTRUCTION_MIN_CHARS,+ max_tokens: int = PIN_MAX_TOKENS,+ prompt_target: int | None = None,+) -> set[int]:+ """`id()`s of the messages in the most recent instruction groups worth protecting.++ Bounded twice over. At most ``groups`` of them, and never more than ``max_tokens``+ summed across everything the pin actually holds: only the USER message is named, but+ the window protects by group, so the reply in that group is held with it and is charged+ with it -- and a trailing tool exchange, which is its own group and stays independently+ evictable, is not (see `_protected_cost`). Anything larger+ than the ceiling is not pinned AT ALL rather than partially: the single enormous+ instruction is precisely the thing that could starve the window, so it is the thing+ excluded.++ ``groups`` of 0 returns an empty set, which makes every downstream byte identical to+ today.+ """+ if groups <= 0 or not messages:+ return set()+ ceiling = max_tokens+ if prompt_target:+ ceiling = min(ceiling, int(prompt_target * PIN_MAX_FRACTION))+ if ceiling <= 0:+ return set()++ turns = group_turns(messages)+ # The newest user group is already protected by the window, and the inline recall path+ # replaces that message with a new dict, so its id would go stale anyway.+ newest_user = next(+ (+ index+ for index in range(len(turns) - 1, -1, -1)+ if any(m.get("role") == "user" for m in turns[index])+ ),+ None,+ )++ pinned: set[int] = set()+ spent = 0+ taken = 0+ for index in range(len(turns) - 1, -1, -1):+ if taken >= groups:+ break+ if index == newest_user:+ continue+ group = turns[index]+ head = group[0]+ if not is_substantive(head, min_chars = min_chars):+ continue+ cost = _protected_cost(turns, index)+ if spent + cost > ceiling:+ continue+ pinned.add(id(head))+ spent += cost+ taken += 1+ return pinneddiff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex dbf5da7f379..82c4f10a519 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -83,6 +83,49 @@ from core.inference.llama_server_args import (strip_split_mode_only,)++def _fit_with_instruction_pins(+ messages,+ *,+ anchor_ids = None,+ **kwargs,+):+ """`fit_rolling_context`, plus the user's standing instructions held back from eviction.++ Applied through the existing `protected_message_ids` seam rather than by changing the+ evictor, so the rolling-window layer is untouched and this ships as an addition to it.++ Three things this must never do, each of which the code below is shaped by:++ * mutate the caller's anchor set. It is also the recall-anchor set and it is carried+ across tool-loop iterations, so a pin id leaking into it would outlive the message+ the id belonged to.+ * hold pins computed against an older copy of the conversation. Inline recall REPLACES+ the latest user message with a new dict, so ids go stale; recomputing per fit is the+ only version that stays true.+ * turn a servable request into a refusal. If pinning is what made the prompt not fit,+ the pins are dropped and the fit is redone without them. One extra fit, only on a+ path that was already failing.+ """+ anchors = set(anchor_ids or ())+ try:+ from core.inference import instruction_pin+ pins = instruction_pin.pinned_instruction_ids(+ messages,+ prompt_target = prompt_budget(+ kwargs.get("context_length") or 0, kwargs.get("max_tokens") or 0+ ),+ )+ except Exception: # noqa: BLE001 -- a protection heuristic must never break a chat+ pins = set()+ fitted, truncation = fit_rolling_context(+ messages, protected_message_ids = (anchors | pins) or None, **kwargs+ )+ if pins and truncation and not truncation.get("fits"):+ return fit_rolling_context(messages, protected_message_ids = anchors or None, **kwargs)+ return fitted, truncation++# Share strip / signal constants with the multi-format parser so BUFFERING also# catches Llama-3 / Mistral / Gemma 4 (legacy helper only knew <tool_call> / <function=).from core.inference.tool_call_parser import (@@ -808,7 +851,16 @@ def _archive_and_recall(return resultgone = evicted_messages(before, conversation)- archived = conversation_archive.archive_turns(thread_id, gone) if gone else 0+ # `conversation` is the fitted prompt, so it says which repeats of a turn the model+ # can still read. Without it a twice-said turn is archived twice and spends two+ # recall slots on text already in the prompt.+ archived = (+ conversation_archive.archive_turns(+ thread_id, gone, live = conversation, branch = branch_messages or conversation+ )+ if gone+ else 0+ )counts = {"archived_messages": archived}if recall_done:@@ -21872,7 +21924,7 @@ class LlamaCppBackend:):try:_before_fit = openai_messages- openai_messages, truncation = fit_rolling_context(+ openai_messages, truncation = _fit_with_instruction_pins(openai_messages,context_length = self._effective_context_length,max_tokens = payload["max_tokens"],@@ -22487,7 +22539,7 @@ class LlamaCppBackend:_preflight_context_length = self._effective_context_lengthtry:_before_fit = conversation- conversation, truncation = fit_rolling_context(+ conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,max_tokens = max_tokens,@@ -22504,7 +22556,7 @@ class LlamaCppBackend:),should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),- protected_message_ids = _rolling_anchor_ids,+ anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),reserve_tokens = _conversation_recall_reserve(thread_id),sticky_dropped = (@@ -22637,7 +22689,7 @@ class LlamaCppBackend:if max_tokens is None:payload["max_tokens"] = self._effective_context_lengthtry:- conversation, truncation = fit_rolling_context(+ conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,max_tokens = max_tokens,@@ -22654,7 +22706,7 @@ class LlamaCppBackend:),should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),- protected_message_ids = _rolling_anchor_ids,+ anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),)if truncation and truncation["fits"]:@@ -23992,7 +24044,7 @@ class LlamaCppBackend:_final_preflight_context_length = self._effective_context_lengthtry:_before_final_fit = conversation- conversation, truncation = fit_rolling_context(+ conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,max_tokens = _final_max_tokens,@@ -24004,7 +24056,7 @@ class LlamaCppBackend:chat_template_kwargs = _reasoning_kw,should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),- protected_message_ids = _rolling_anchor_ids,+ anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),reserve_tokens = _conversation_recall_reserve(thread_id),sticky_dropped = (@@ -24106,7 +24158,7 @@ class LlamaCppBackend:if max_tokens is None:stream_payload["max_tokens"] = self._effective_context_lengthtry:- conversation, truncation = fit_rolling_context(+ conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,max_tokens = max_tokens,@@ -24118,7 +24170,7 @@ class LlamaCppBackend:chat_template_kwargs = _reasoning_kw,should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),- protected_message_ids = _rolling_anchor_ids,+ anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),)if truncation and truncation["fits"]:diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 0f9f6234d5f..cb2d7d12d62 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10590,7 +10590,7 @@ def build_synthetic_search_exchange(_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"+ "Relevant earlier turns of this chat are quoted below, retrieved verbatim.\n""{text}\n""</recalled_conversation>\n\n")@@ -10634,9 +10634,23 @@ def build_conversation_recall(query = _last_user_text(branch_messages or conversation) or _last_user_text(conversation)if not query:return None+ # A nudge ("continue", "yes") retrieves nothing, so the user's last real instruction is+ # asked for as a SECOND query. Not applied to the model's own `search_conversation`+ # calls: the model wrote that query, and overriding it answers a different question.+ anchor = None+ try:+ from core.inference import instruction_pin+ if instruction_pin.is_thin_query(query):+ anchor = instruction_pin.last_substantive_instruction(branch_messages or conversation)+ except Exception: # noqa: BLE001 -- a query refinement must never break a chat+ anchor = Nonetry:found = conversation_archive.recall(- thread_id, query, top_k = top_k, branch_messages = branch_messages+ thread_id,+ query,+ top_k = top_k,+ branch_messages = branch_messages,+ extra_queries = [anchor] if anchor else None,)except Exception:logger.warning("Conversation recall failed", exc_info = True)diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.pyindex 56769e4936c..f6533c76761 100644--- a/studio/backend/core/rag/config.py+++ b/studio/backend/core/rag/config.py@@ -41,6 +41,13 @@ CONVERSATION_ARCHIVE_TOP_K = int(os.environ.get("RAG_CONVERSATION_ARCHIVE_TOP_K"CONVERSATION_RECALL_RESERVE_TOKENS = int(os.environ.get("RAG_CONVERSATION_RECALL_RESERVE_TOKENS", "2048"))+# Shape the archive's lexical query: require identifier-like tokens first, drop function+# words from the fallback. Off restores the plain OR-of-every-token other scopes use.+CONVERSATION_QUERY_FOCUS = os.environ.get("RAG_CONVERSATION_QUERY_FOCUS", "1") == "1"+# "chronological" presents recalled turns oldest first, labelled, with later superseding+# earlier; "relevance" restores the previous rendering. Presentation only: neither changes+# which turns are selected.+CONVERSATION_RECALL_ORDER = os.environ.get("RAG_CONVERSATION_RECALL_ORDER", "chronological")UPLOAD_EXTS = {".pdf", ".txt", ".md", ".markdown", ".docx", ".html", ".htm"}# Reject uploads larger than this, so one pathological file can't drive unbounded parsediff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.pyindex 7ade85fad3a..ad23954c664 100644--- a/studio/backend/core/rag/conversation_archive.py+++ b/studio/backend/core/rag/conversation_archive.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport hashlibimport logging+import bisectimport jsonimport refrom typing import Optional@@ -299,12 +300,21 @@ def can_archive(thread_id: Optional[str]) -> bool:return False-def archive_turns(thread_id: str, evicted: list[dict]) -> int:+def archive_turns(+ thread_id: str,+ evicted: list[dict],+ live: Optional[list[dict]] = None,+ branch: Optional[list[dict]] = None,+) -> 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 requestin the session, so re-archiving has to be free. After the first write each repeatcosts one indexed SELECT and writes nothing.++ ``live`` is the fitted conversation, i.e. what the model can still see. It bounds how+ many copies of a repeated turn the archive is allowed to hold right now; see+ ``_write_budget``. Optional, and omitting it keeps the previous behaviour."""if not thread_id or not evicted or not enabled():return 0@@ -334,6 +344,9 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int:model = config.effective_embedding_model()scope = store.conversation_archive_scope(thread_id)+ # Conversation order from the persisted thread, not arrival order (`_transcript_positions`).+ positions = _transcript_positions(thread_id, branch or live)+ live_positions = _live_positions(live)written = 0conn = Nonetry:@@ -352,7 +365,26 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int:if not text:continuedigest = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()- if _archived_under(conn, scope, digest, expected_identity):+ seats = _occurrences(positions, group)+ budget = _write_budget(positions, seats, live_positions, group)+ if _archived_under(conn, scope, digest, expected_identity, occurrences = budget):+ # Commit here: this path holds no transaction of its own and can return+ # before reaching the write lock, the ordinary case on a re-compacted+ # thread, so it is the only chance an upgraded archive has to converge.+ #+ # Bounded by the LIVE-AWARE budget, not by every seat: a rewind or a bigger+ # window can put one occurrence of a repeated turn back in the prompt, and+ # keeping a copy per seat then left two byte-identical documents, both+ # passing the branch filter, so a recall slot went on text the model could+ # already read. Measured: 3 passages of which 2 were distinct. At least one+ # survives, since a turn that is momentarily all-live still has an archive.+ _restamp(+ conn,+ scope,+ digest,+ seats[: max(1, budget)] if seats else seats,+ commit = True,+ )_widen_span(conn, scope, digest, span)continuechunks = chunk_pages(@@ -362,7 +394,7 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int:count = count,)if chunks:- pending.append((group, span, digest, chunks))+ pending.append((group, span, digest, chunks, seats, budget))if not pending:return 0@@ -374,7 +406,7 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int:normalize = True,)offset = 0- for group, span, digest, chunks in pending:+ for group, span, digest, chunks, seats, budget in pending:group_vectors = vectors[offset : offset + len(chunks)]offset += len(chunks)roles = " + ".join(@@ -394,24 +426,43 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int: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)+ copies = store.documents_by_hash(conn, scope, digest)+ stale = _stale_document(conn, scope, digest, identity, occurrences = budget)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.+ _restamp(conn, scope, digest, seats, copies = copies)if _write_lock:- conn.rollback()+ conn.commit()+ # Widened here too, not only on the pre-check: both turns can arrive in ONE+ # compaction, 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. After the commit+ # above, since the widen carries its own._widen_span(conn, scope, digest, span)continue+ ordinal = None+ archived_at = Noneif 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.+ # The copy is replaced rather than deduplicated, as ingestion does, since+ # skipping it would leave the turn invisible to dense search forever.+ #+ # It keeps its POSITION and its TIMESTAMP: a re-embed rewrites HOW a turn+ # is indexed, not WHEN it was said, and renumbering or restamping would+ # reorder the archive by the order its vectors were rebuilt. NULL stays+ # NULL, since numbering a pre-column row moves the oldest turn behind every+ # numbered one and the header would call it the conversation's last word.+ previous = store.get_document(conn, stale) or {}+ ordinal = previous.get("archive_ordinal")+ archived_at = previous.get("created_at")store.delete_document(conn, stale, commit = False)+ else:+ # The nth copy of a repeated turn takes the nth occurrence's position, so a+ # verbatim repeat lands where it was said, not behind its first saying.+ ordinal = (+ seats[len(copies)]+ if seats and len(copies) < len(seats)+ else _fallback_ordinal(conn, scope, positions)+ )document_id = store.create_document(conn,scope = scope,@@ -420,12 +471,20 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int: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.+ # The turn's real size in the TRANSCRIPT, so the branch check can bound its+ # run exactly. Role labels only approximate it (a pasted transcript writes+ # the same lines) and the archived messages undercount what `_archivable`+ # dropped.archive_messages = span,+ # Where this turn sits in the conversation. Allocated inside the write lock+ # in `group_turns` order, so it holds within and across epochs, which+ # `created_at` cannot: one compaction writes every evicted turn microseconds+ # apart. Written unconditionally, so switching ordering off punches no+ # permanent holes in the sequence.+ archive_ordinal = ordinal,+ # When the turn was archived, not when this row was written. None for a turn+ # seen for the first time, which takes the clock as before.+ created_at = archived_at,commit = False,)try:@@ -433,8 +492,49 @@ def archive_turns(thread_id: str, evicted: list[dict]) -> int:except Exception:conn.rollback()raise+ # Surplus only, NOT a restamp: the re-embed path never reaches the+ # already-archived branch that retires copies, so a repeat archived twice and+ # then rewound kept its extra copy. Restamping here would renumber a pre-column+ # row. Runs after the new row exists, so the count is what the scope holds.+ _retire_surplus(conn, scope, digest, seats)+ # A re-embed keeps the ordinal it found, which goes wrong once a copy is+ # retired: twins at 0 and 2 with the FIRST rewound away left the survivor on 0,+ # so a contradiction at 1 rendered as the later, superseding statement.+ # Restamped against the seats that remain, skipping NULLs.+ if stale is not None:+ _restamp(conn, scope, digest, seats, skip_null = True)conn.commit()written += 1+ # A REPLACEMENT is not an addition: the re-embed branch swaps one copy's+ # vectors and keeps the count, so a repeat evicted while the embedder identity+ # changed was never written at all. Top the copies up to the budget here,+ # reusing the vectors already in hand.+ #+ # Only where the budget counts EVICTED occurrences, which is what `live` buys.+ # Otherwise it falls back to every transcript seat, and topping up to that+ # would write a copy of a turn whose repeat is still in the prompt.+ while (+ stale is not None+ and live_positions is not None+ and len(store.documents_by_hash(conn, scope, digest)) < budget+ ):+ if not _write_copy(+ conn,+ scope = scope,+ thread_id = thread_id,+ roles = roles,+ digest = digest,+ identity = identity,+ group = group,+ span = span,+ chunks = chunks,+ vectors = group_vectors,+ seats = seats,+ ):+ break+ _retire_surplus(conn, scope, digest, seats)+ conn.commit()+ written += 1if _INGEST_FAILED:globals()["_INGEST_FAILED"] = Falseexcept Exception:@@ -482,27 +582,768 @@ def degraded() -> bool:_ARCHIVED = "archived"-def _stale_document(conn, scope: str, digest: str, identity: str):+# How many leaves a branch seed will try. A thread gains one leaf per abandoned retry and+# the branch the user went BACK to is older than all of them, so a tight cap excluded the+# very branch this exists to find. Paid for by rendering each stored message once rather+# than once per leaf: sibling chains share nearly all their ancestors.+_BRANCH_SEED_MAX_LEAVES = 512+++def _walk_from(by_id: dict, parent_of: dict, leaf) -> list[dict]:+ """The rows from ``leaf`` back to the root, oldest first."""+ chain: list[dict] = []+ seen: set = set()+ current = leaf+ while current is not None and current not in seen:+ seen.add(current)+ record = by_id.get(current)+ if record is None:+ break+ chain.append(record)+ current = parent_of.get(current)+ chain.reverse()+ return chain+++def _branch_seed(messages: list[dict], by_id: dict, parent_of: dict, branch) -> Optional[str]:+ """Which stored leaf the REQUEST is on, by matching its text. None when nothing does.++ The newest stored row is not the branch the request is on. Switching to a sibling,+ continuing there and switching back leaves the abandoned branch holding the greatest+ created_at, and the frontend says so outright in `refresh-context-usage.ts`: after a+ retry the newest stored leaf is a branch the user left. Measured on a thread with one+ such switch, the walk read the abandoned branch and BOTH of the request branch's+ evicted turns matched no position, taking MAX + 1 over an archive the other branch had+ already pushed up, which the recall header presents as superseding.++ Matched on text, not id: the wire carries no message ids. Scored rather than compared,+ since the newest branch message is usually not persisted yet and the evicted turns are+ no longer in the fitted conversation.+ """+ if not branch:+ return None+ # A LIST, in order, not a set: sets lose repetition and ordering, so an abandoned+ # sibling with the same distinct texts tied with the request's own branch and, being+ # newer, won. A multiset fixes the repeat case but not the reordered one, so this+ # scores an in-order run. System and developer messages are excluded: Studio's+ # prepended chat and project instructions are not part of the stored chain.+ wanted = [+ text+ for text in (+ _normalise_cased(_probe_text(message))+ for message in _as_wire(branch)+ if str(message.get("role") or "") not in ("system", "developer")+ )+ if text+ ]+ if not wanted:+ return None+ # Where each text may be matched, so the scan can SKIP an entry with no stored+ # counterpart. A strict cursor stalled on the first one, every leaf scored zero, and+ # the fallback to the newest row picked the abandoned branch this exists to avoid.+ where: dict = {}+ for index, text in enumerate(wanted):+ where.setdefault(text, []).append(index)+ parents = {parent for parent in parent_of.values() if parent is not None}+ order = {message.get("id"): index for index, message in enumerate(messages)}+ leaves = sorted(+ (identifier for identifier in by_id if identifier not in parents),+ key = lambda identifier: order.get(identifier, -1),+ reverse = True,+ )+ best = None+ best_score = 0+ # Rendered once per STORED ROW, not per leaf: `_as_wire` expands a row the same way+ # whichever chain it is walked in.+ rendered: dict = {}++ def _texts_of(record: dict) -> list:+ identifier = record.get("id")+ if identifier is None:+ return [_normalise_cased(_probe_text(m)) for m in _as_wire([record])]+ if identifier not in rendered:+ rendered[identifier] = [_normalise_cased(_probe_text(m)) for m in _as_wire([record])]+ return rendered[identifier]++ for leaf in leaves[:_BRANCH_SEED_MAX_LEAVES]:+ # Greedy in-order scan with gaps allowed on both sides: the newest branch message+ # is usually unpersisted and evicted turns have left the fitted conversation, so+ # neither side is a subsequence of the other.+ cursor = 0+ score = 0+ for record in _walk_from(by_id, parent_of, leaf):+ for text in _texts_of(record):+ spots = where.get(text) if text else None+ if not spots:+ continue+ index = bisect.bisect_left(spots, cursor)+ if index < len(spots):+ cursor = spots[index] + 1+ score += 1+ if score > best_score:+ best, best_score = leaf, score+ if best_score >= len(wanted):+ # Every message the request carries is on this chain; nothing can beat it.+ break+ return best+++def _active_chain(messages: list[dict], branch = None) -> list[dict]:+ """The rows on ONE branch, oldest first, rather than the whole stored DAG.++ `list_chat_messages` is an unfiltered SELECT ordered by time, but a thread is a tree:+ `parent_id` is a real column and Retry leaves the replaced reply in place as a sibling.+ Read as a flat list, an abandoned sibling lands between two live turns and the grouper+ glues it onto whichever turn precedes it, so the regenerated turn matches no position+ at all and falls back to MAX + 1. Measured on five turns with one Retry: the+ regenerated turn 2 came back numbered 5 out of 4 live turns, colliding with live turn+ 3, under the header that says the higher number supersedes. The cumulative archive is+ what makes MAX + 1 land past everything -- the abandoned branch has already taken the+ high numbers -- so this does not depend on the eviction order.++ Walked newest leaf back to root, the same shape the frontend's `orderBySelectedBranch`+ uses to decide what the model is actually shown. `parent_id` is missing on rows written+ before that column, so the previous row stands in for it, which is exactly a flat list+ when nothing branches.+ """+ if not messages:+ return []+ by_id: dict = {}+ parent_of: dict = {}+ previous = None+ for message in messages:+ identifier = message.get("id")+ if identifier is None:+ continue+ by_id[identifier] = message+ parent_of[identifier] = message.get("parentId") or message.get("parent_id") or previous+ previous = identifier+ if not by_id:+ return list(messages)+ # The request's own branch when it can be found, the newest row when it cannot: empty+ # positions empty every seat and send every turn to MAX + 1, which is worse than+ # reading the wrong branch.+ seed = _branch_seed(messages, by_id, parent_of, branch) or messages[-1].get("id")+ return _walk_from(by_id, parent_of, seed) or list(messages)+++# `JSON.stringify({ result: "" })` byte for byte. `json.dumps` puts a space after the+# colon and `JSON.stringify` does not, so the obvious spelling never equals the archived+# message: every comparison downstream is exact, and `_normalise` collapses whitespace+# RUNS, not a single space.+_EMPTY_TOOL_RESULT = '{"result":""}'+++# `SERVER_SIDE_BUILTIN_TOOL_NAMES` in `chat-adapter.ts`. The NAME alone never decides: a+# user function may legitimately be called `web_search`, so the marker or a Gemini native+# part has to be there too, as the frontend also requires.+_SERVER_BUILTIN_NAMES = frozenset({"web_search", "web_fetch", "code_execution", "image_generation"})+# `SANDBOX_FILE_TOOLS`, and `tool_loop_controller._SANDBOX_TOOLS`. Only these two wrap.+_SANDBOX_TOOL_NAMES = frozenset({"python", "terminal"})+++def _server_builtin(part: dict) -> tuple[bool, bool]:+ """Whether a persisted call is a provider-side builtin, and whether it has a native part.++ The frontend drops a builtin from the replayed history entirely when there is no+ native part, and replays one WITH a native part as a call carrying no `tool` result.+ Reconstructing either as an ordinary local call inserted a phantom exchange, so the+ request-shaped turn no longer matched the persisted run and the turn took a fallback+ ordinal. Both signals ride on the persisted `args`, so this is decidable here.+ """+ args = part.get("args")+ args = args if isinstance(args, dict) else {}+ if str(part.get("toolName") or "").lower() not in _SERVER_BUILTIN_NAMES:+ return False, False+ google = args.get("google")+ native = isinstance(google, dict) and isinstance(google.get("native_part"), dict)+ return bool(args.get("_server_tool") is True or native), native+++def _unwrapped(result, tool_name: str):+ """A sandbox or MCP-image wrapper reduced to the text the model actually saw.++ `python` and `terminal` results are wrapped in `{text, images, sessionId, files}` on+ EVERY call, and the replay adapter sends `result.text` alone rather than feeding the+ model a session id and file metadata. Serialising the whole wrapper reconstructed a+ tool message that can never equal the archived one.++ Both gates are the frontend's: the name, because a third-party tool answering with+ `{text, sessionId, images}` is someone else's and unwrapping it would drop every other+ field, and the shape.+ """+ if not isinstance(result, dict) or not isinstance(result.get("text"), str):+ return None+ images = result.get("images")+ if not isinstance(images, list):+ return None+ if tool_name in _SANDBOX_TOOL_NAMES and isinstance(result.get("sessionId"), str):+ files = result.get("files")+ if files is None or (+ isinstance(files, list)+ and all(isinstance(f, dict) and isinstance(f.get("name"), str) for f in files)+ ):+ return result["text"]+ # The MCP image shape carries no session and always has at least one image.+ if (+ result.get("sessionId") is None+ and images+ and all(+ isinstance(image, dict)+ and isinstance(image.get("data"), str)+ and isinstance(image.get("mimeType"), str)+ for image in images+ )+ ):+ return result["text"]+ return None+++def _tool_result_content(result, tool_name: str = "") -> str:+ """A persisted tool result in the string the replay serializer would have sent.++ An empty string becomes the sentinel above, because the backend's ChatMessage+ validator rejects a `tool` message with empty content; everything else is JSON with+ JavaScript's separators. Rendering it any other way makes the reconstructed message+ differ from the one that was actually archived, which is the whole point of this+ module comparing the two.+ """+ if isinstance(result, str):+ return result if result else _EMPTY_TOOL_RESULT+ unwrapped = _unwrapped(result, tool_name)+ if unwrapped is not None:+ return unwrapped if unwrapped else _EMPTY_TOOL_RESULT+ # `ensure_ascii = False` because `JSON.stringify` does not escape non-ASCII. Otherwise+ # an accented tool result reconstructs as `Montr\\u00e9al`, loses its transcript seat+ # and is filtered out of recall.+ return json.dumps(result, ensure_ascii = False, separators = (",", ":"))+++def _replayable(part: dict) -> bool:+ """Whether the serializer replays this tool call at all.++ `chat-adapter.ts` drops the whole call when it has no result to send and cannot be+ replayed without one: `if (!toolResult && !canReplayToolCallWithoutRoleTool(part))+ continue`. That is every cancelled or still-running LOCAL card. Keeping it here and+ merely omitting its `tool` message invented an assistant `tool_calls` message the+ request never carried, which shifts the groups either side of it and can send an+ otherwise live turn to a wrong ordinal or out of the branch check entirely.++ A provider-side builtin is replayable without a result, but one with no native part+ is dropped by `serializeAssistantToolCallPart` instead, so it is not a call here.+ """+ builtin, native = _server_builtin(part)+ if builtin:+ return native+ return part.get("result") is not None+++def _local_round_id(part: dict):+ """`codexLocalToolRoundId`: the round a LOCAL tool call belongs to, or None."""+ provenance = part.get("provenance")+ if not isinstance(provenance, dict) or provenance.get("source") != "local":+ return None+ round_id = provenance.get("round_id")+ if isinstance(round_id, bool) or not isinstance(round_id, int):+ return None+ return round_id+++def _flushes_local_pair(part: dict) -> bool:+ """`shouldFlushCompletedLocalToolPair`: a completed local call is its own round.++ A local tool card that already has its result is flushed both BEFORE and AFTER it, so+ two adjacent completed local calls replay as two sequential assistant/tool groups and+ not as one parallel group. Batching them made `group_turns`, the occurrence ordinals+ and the live-branch check all describe a transcript shape the request never sent.+ """+ provenance = part.get("provenance")+ if not isinstance(provenance, dict) or provenance.get("source") != "local":+ return False+ if _server_builtin(part)[0]:+ return False+ return part.get("result") is not None+++def _as_wire(messages: list[dict]) -> list[dict]:+ """Persisted chat rows in the shape the inference layer sends them.++ The store keeps a tool call as a ``tool-call`` CONTENT PART carrying its own result,+ while the wire form is three messages: the assistant's `tool_calls`, a `tool` result,+ then the assistant's reply. Nothing put them back, and everything here reads the+ persisted rows as if they were wire messages, so an agent turn was invisible twice+ over. `group_turns` splits on `tool_calls`, which a persisted row never has, so the+ whole exchange folded into the preceding user group and the evicted tool group found+ no position of its own -- measured, seats came back empty and the exchange took+ MAX + 1, the number its own opening question already had. And `_live_transcript`+ probes these rows in the same shape, so the branch check compared a call/result/reply+ render against a row reading call/reply/result: measured, the archived agent turn+ failed the live-branch filter and NO query could return it, on every tool-using turn.++ The result is stripped from the call part and carried by the `tool` message instead,+ so `_probe_text` renders each piece exactly once and in the order `render_turn` wrote+ it. Only the id goes into `tool_calls`: the arguments stay on the content part, where+ `_probe_text` already offers both JSON spellings, and `_is_injected` still sees the id+ it filters our own injections by.+ """+ wire: list[dict] = []+ for message in messages:+ content = message.get("content")+ parts = content if isinstance(content, list) else None+ # Reasoning is not content: the serializer never puts it in `content`, but+ # `_probe_text` renders any part with a `text` field, so forwarding the stored list+ # put a model's thinking inline and the turn matched no transcript seat. Dropped+ # rather than moved, since nothing reads `reasoning_content` on the live side.+ if parts is not None and any(+ isinstance(part, dict) and part.get("type") == "reasoning" for part in parts+ ):+ parts = [+ part+ for part in parts+ if not (isinstance(part, dict) and part.get("type") == "reasoning")+ ]+ content = parts+ # A provider-side builtin with no native part is not replayed, so it is not a call+ # here either: counting it invented an exchange the request never carried. Any+ # other tool-call part takes the replay loop even when the serializer drops it,+ # since passthrough would keep it in `content` and render a call never sent.+ calls = [+ part+ for part in (parts or [])+ if isinstance(part, dict) and part.get("type") == "tool-call"+ ]+ if not calls:+ wire.append(+ {+ "role": message.get("role"),+ "content": content,+ "tool_calls": message.get("tool_calls"),+ }+ )+ continue+ # Replayed the way `chat-adapter.ts` replays it: parts in order, flushing pending+ # calls whenever text arrives, so a row holding two rounds goes out as+ # call/result/text+call/result. Collecting every call into one message rebuilt a+ # different order, and the later calls took an invented ordinal. Text accumulated+ # before a flush rides ON that flush's call message, as it does live.+ pending_calls: list[dict] = []+ pending_text: list = []+ # A one-slot box because `_flush` resets it and Python closures cannot rebind.+ pending_round: list = [None]++ def _flush(role = message.get("role")) -> None:+ pending_round[0] = None+ if not pending_calls and not pending_text:+ return+ body: list = [+ {key: value for key, value in call.items() if key != "result"}+ for call in pending_calls+ ] + pending_text+ entry: dict = {"role": role, "content": body}+ if pending_calls:+ entry["tool_calls"] = [+ {"id": call.get("toolCallId"), "function": {}} for call in pending_calls+ ]+ wire.append(entry)+ for call in pending_calls:+ if _server_builtin(call)[0]:+ # A builtin WITH a native part replays as a call and no `tool`+ # message: its result travels in the provider's own native part.+ continue+ if "result" not in call or call.get("result") is None:+ # Only an ABSENT result is absent. The serializer skips exactly+ # `undefined` and `null`, so treating "" / {} / [] as nothing dropped a+ # message the wire carries and left the run short of the archived one.+ continue+ wire.append(+ {+ "role": "tool",+ "tool_call_id": call.get("toolCallId"),+ "content": _tool_result_content(+ call.get("result"), str(call.get("toolName") or "")+ ),+ }+ )+ pending_calls.clear()+ pending_text.clear()++ for part in parts:+ if isinstance(part, dict) and part.get("type") == "tool-call":+ if not _replayable(part):+ # Dropped whole, call and result, exactly as the serializer does.+ continue+ round_id = _local_round_id(part)+ if (+ pending_calls+ and pending_round[0] is not None+ and round_id is not None+ and pending_round[0] != round_id+ ):+ # `startsNewCodexToolRound`: a new local round is a new group.+ _flush()+ if round_id is not None:+ pending_round[0] = round_id+ flush_pair = round_id is None and _flushes_local_pair(part)+ if flush_pair and pending_calls:+ _flush()+ pending_calls.append(part)+ if flush_pair:+ _flush()+ continue+ if pending_calls:+ _flush()+ pending_text.append(part)+ _flush()+ return wire+++def _fallback_ordinal(conn, scope: str, positions: Optional[list[list[str]]]) -> int:+ """Where a turn that matched no seat goes: past the archive AND past the transcript.++ The two numbering spaces are different. Seats are TRANSCRIPT positions, while+ `next_archive_ordinal` counts what has been ARCHIVED, and the newest user group is+ protected from eviction, so during a long tool loop it is in the transcript and not+ in the archive. An in-flight tool group evicted before its assistant row is persisted+ matches no seat and took the archive's next number, which the user turn then claimed+ from the transcript: measured, both documents landed on ordinal 0, and since+ `created_at` breaks the tie the tool answer rendered ahead of the prompt that caused+ it, under the header saying a higher number was said later.++ The transcript length is the right floor because an unmatched group is unmatched for+ being newer than the saved rows. A gap in the numbering costs nothing: ordinals only+ have to order.+ """+ return max(store.next_archive_ordinal(conn, scope), len(positions or []))+++def _transcript_positions(thread_id: str, branch = None) -> Optional[list[str]]:+ """The thread's saved messages as normalised probe text, in the order they were said.++ The ordinal has to come from the CONVERSATION, not from the moment a turn happened to+ be archived. Eviction is not strictly oldest-first: `truncate_oldest_messages` always+ protects the newest user group, so an agent turn's tool groups are evicted while the+ user message that opened them is held, and a pinned instruction is evicted only once+ it stops being pinned. Numbering by archive time then records the genuinely oldest+ turn as the newest, and `format_conversation_recall` states outright that the higher+ number "was said later and supersedes the earlier one". Measured before this: a+ standing instruction archived second came back as turn 3 of 3, presented to the model+ as superseding the two turns that actually followed it.++ Read from the persisted transcript rather than the request, because four of the five+ archive call sites pass the tool loop's already-fitted messages, whose indices shift+ as earlier groups drop out. `studio_db` holds the whole thread and is never truncated.+ """+ try:+ from core.inference.context_window import group_turns+ from storage import studio_db+ messages = studio_db.list_chat_messages(thread_id)+ except Exception:+ return None+ if not messages:+ return None+ # Grouped with the evictor's own grouper, so a position is a TURN's index, which is+ # what the ordinal is compared against.+ wire = _as_wire(_active_chain(messages, branch))+ return [+ [_normalise_cased(_probe_text(message)) for message in group]+ for group in group_turns(wire)+ if group+ ]+++def _occurrences(positions: Optional[list[list[str]]], group: list[dict]) -> list[int]:+ """Where this turn sits in the transcript, every time it was said.++ The WHOLE turn, not just its opening line. Matching on the first message alone made+ two different turns that merely start the same -- a repeated "continue", the same+ question re-asked, a regenerated reply -- claim each other's seats: measured, both+ were stamped with ordinal 0, and because each then believed it had two occurrences to+ fill, the next compaction wrote both of them AGAIN. Four documents for two turns,+ twice the recall slots spent on the same content, and the older answer quoted under+ the higher turn number, which the header presents as the one that supersedes.++ Compared as a prefix, because the transcript legitimately lags the evicted group: a+ turn is archived mid-request, before its own reply has been persisted. A turn that+ matches nothing yields no seats and falls back to the previous allocator, so this can+ never do worse than not looking.++ A list rather than one index because a conversation may legitimately contain the same+ turn twice, and the later occurrence is usually the one that matters -- "set X to 1",+ "set X to 2", "set X to 1" ends with X at 1.+ """+ if not positions or not group:+ return []+ texts = [_normalise_cased(_probe_text(message)) for message in group]+ if not texts or not texts[0]:+ return []+ calls = [bool(message.get("tool_calls")) for message in group]++ def _same(stored: str, live: str, is_call: bool) -> bool:+ # A tool call is compared as needle in haystack, never for equality: the store+ # keeps arguments as an OBJECT and the request carries the model's raw string, so+ # `_probe_text` offers both JSON spellings for the stored copy and one for the live+ # one. Every other message is compared exactly.+ #+ # In two pieces when the whole needle does not fit, since the second spelling is+ # inserted BETWEEN the arguments and what followed them: a call with a preamble+ # renders live as name/args/text and stored as name/args/args/text, so the live+ # string is no longer contiguous. One split point, so this tolerates exactly the+ # one insertion `_probe_text` makes.+ if is_call:+ if not live:+ return False+ if live in stored:+ return True+ words = live.split(" ")+ for cut in range(1, len(words)):+ head = " ".join(words[:cut])+ tail = " ".join(words[cut:])+ at = stored.find(head)+ if at >= 0 and stored.find(tail, at + len(head)) >= 0:+ return True+ return False+ return stored == live++ return [+ index+ for index, position in enumerate(positions)+ if position+ # A position SHORTER than the turn may only match the trailing one: `zip` stops at+ # the shorter side, so an orphan user row (a deleted reply, or a reload before the+ # reply was appended) prefix-matched and gave the answered turn two seats.+ # `>=` rather than `==`, since a position legitimately runs LONGER: `_archivable`+ # strips our injections and `_as_wire` expands one tool row into several messages.+ and (len(position) >= len(texts) or index == len(positions) - 1)+ and all(+ _same(stored, live, is_call) for stored, live, is_call in zip(position, texts, calls)+ )+ ]+++def _write_copy(+ conn,+ *,+ scope: str,+ thread_id: str,+ roles: str,+ digest: str,+ identity: str,+ group: list[dict],+ span: int,+ chunks,+ vectors,+ seats: list[int],+) -> bool:+ """One more copy of an already-embedded turn, at the next unfilled seat.++ Only for topping up after a re-embed, which replaces a copy rather than adding one.+ Returns False when there is no seat left to fill, so the caller stops rather than+ allocating a fresh ordinal and putting a repeat at the end of its own conversation.++ ``span`` is the turn's size in the TRANSCRIPT and not ``len(group)``: `_archivable`+ strips a retrieval call and its result, so a group of three can span four live+ messages. Written short, the branch check bounds its run by the smaller figure and+ filters this copy out of every recall -- the same bug the primary write path was+ fixed for, reappearing on the top-up path.+ """+ copies = store.documents_by_hash(conn, scope, digest)+ if not seats or len(copies) >= len(seats):+ return 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,+ archive_messages = span,+ archive_ordinal = seats[len(copies)],+ commit = False,+ )+ try:+ store.add_chunks(conn, scope, document_id, chunks, vectors)+ except Exception:+ conn.rollback()+ raise+ return True+++def _live_positions(live: Optional[list[dict]]) -> Optional[list[list[str]]]:+ """The fitted conversation grouped exactly as ``_transcript_positions`` groups the+ stored one, so a live turn can be matched by the same rules a stored seat is."""+ if live is None:+ return None+ try:+ from core.inference.context_window import group_turns+ except Exception:+ return None+ positions = [+ [_normalise_cased(_probe_text(message)) for message in group]+ for group in group_turns(_as_wire(live))+ if group+ ]+ return positions or None+++def _write_budget(+ positions: Optional[list[list[str]]],+ seats: list[int],+ live_positions: Optional[list[list[str]]],+ group: Optional[list[dict]] = None,+) -> int:+ """How many copies of a repeated turn the archive may hold RIGHT NOW.++ ``seats`` is every place the turn was said, which is what allocates ordinals, but it+ is the wrong number to spend on writes. A thread can hold the same turn twice with+ only the older one evicted; the archive then sees one stored copy against two seats,+ decides it is short, and writes a second document for the occurrence still sitting in+ the prompt. Both are then recallable, so identical text takes two of the four recall+ slots and one of them repeats what the model can already read.++ Counted against the LIVE conversation instead: a seat whose every message is still in+ the prompt has not been evicted and buys no write. When that turn is evicted later the+ budget rises on its own and the copy is written then, at its own ordinal.++ COUNTED, not tested for membership. A set of live texts cannot tell "one of three+ identical turns is still in the prompt" from "all three are", so every seat looked+ live and a turn said three times with two of them evicted was archived once. Counting+ the live occurrences with `_occurrences`, the same matcher that finds the seats,+ subtracts exactly as many as the prompt really holds.++ Floors at 1 so a turn whose seats cannot be told apart from live text is still stored;+ and with no ``live`` to compare against, this is exactly the old ``len(seats)``.+ """+ if not seats:+ return 1+ if not live_positions or not positions:+ return len(seats)+ live = len(_occurrences(live_positions, group)) if group else 0+ return max(len(seats) - live, 1)+++def _retire_surplus(+ conn,+ scope: str,+ digest: str,+ seats: list[int],+ *,+ rows = None,+) -> bool:+ """Delete copies of this turn the conversation no longer holds. True if any went.++ More copies than occurrences means a rewind removed one. The survivors are+ byte-identical, so the branch filter validates every copy against the single remaining+ occurrence and `recall` dedups on chunk id, which differs: measured, a recall slot went+ on quoting one turn twice, and the surplus kept an ordinal a genuinely later turn had+ since taken.++ Does nothing without seats, so a turn that failed to match its occurrences at all --+ an unreconstructable transcript, a thread with no persisted rows -- never loses a copy.+ """+ if not seats:+ return False+ try:+ copies = rows if rows is not None else store.documents_by_hash(conn, scope, digest)+ surplus = copies[len(seats) :]+ for copy in surplus:+ store.delete_document(conn, copy["id"], commit = False)+ return bool(surplus)+ except Exception: # noqa: BLE001 -- tidying an archive is not worth a chat+ logger.debug("conversation_archive.retire_surplus_failed", exc_info = True)+ return False+++def _restamp(+ conn,+ scope: str,+ digest: str,+ seats: list[int],+ *,+ copies = None,+ commit: bool = False,+ skip_null: bool = False,+) -> None:+ """Move existing copies of this turn onto the positions the transcript gives them.++ An archive written by an earlier build numbered turns as they arrived, and one written+ before the column existed has no number at all. Both keep an order that was never+ true, and `format_conversation_recall` states that the higher number was said later+ and supersedes the earlier one, so the block asserts it. Re-stamping at the next+ compaction lets those archives converge with no migration pass and no reindex: this is+ an UPDATE on rows that already exist, so nothing is duplicated.++ Called from BOTH archived paths. The cheap pre-check that runs before chunking fires+ on exactly the condition the write-lock branch does, so a restamp only in the latter+ was unreachable outside a race: measured, a forced-legacy archive still read NULL,NULL+ after a full re-compaction, and an archive-time order of 1,0 stayed 1,0 with the+ recall rendering the second turn first.+ """+ if not seats:+ return+ try:+ rows = copies if copies is not None else store.documents_by_hash(conn, scope, digest)+ moved = False+ for seat, copy in zip(seats, rows):+ if skip_null and copy.get("archive_ordinal") is None:+ # A row archived before the column existed stays unnumbered, or it moves to+ # the end of its own conversation and the header calls the oldest statement+ # the latest one.+ continue+ if copy.get("archive_ordinal") != seat:+ store.set_archive_ordinal(conn, copy["id"], seat)+ moved = True+ moved = _retire_surplus(conn, scope, digest, seats, rows = rows) or moved+ if moved and commit:+ conn.commit()+ except Exception: # noqa: BLE001 -- ordering an old archive is not worth a chat+ logger.debug("conversation_archive.restamp_failed", exc_info = True)+++def _stale_document(+ conn,+ scope: str,+ digest: str,+ identity: str,+ *,+ occurrences: int = 1,+):"""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.+ Hash alone is not enough, twice over.++ 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.++ And a hash is not an identity when a user repeats themselves. ``occurrences`` is how+ many times this exact turn appears in the transcript, so a copy is only "already+ archived" once every occurrence has one. Without it the third turn of "set X to 1",+ "set X to 2", "set X to 1" was dropped on the floor: never indexed, so no query could+ reach it, and the recall then handed the model the superseded value under a header+ saying the higher turn number supersedes the lower. Measured: 3 turns in, 2 documents+ stored, and the block asserted X was 2."""- existing = store.document_by_hash(conn, scope, digest)- if existing is None:+ copies = store.documents_by_hash(conn, scope, digest)+ if not copies: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+ for copy in copies:+ if not config.embedding_identity_matches(copy.get("embedding_model"), identity):+ # Re-index the stale copy before considering writing a new one.+ return copy["id"]+ return _ARCHIVED if len(copies) >= max(1, occurrences) else None-def _archived_under(conn, scope: str, digest: str, identity: str) -> bool:+def _archived_under(+ conn,+ scope: str,+ digest: str,+ identity: str,+ *,+ occurrences: int = 1,+) -> bool:"""Cheap pre-check before the chunking and embedding pass."""- return _stale_document(conn, scope, digest, identity) is _ARCHIVED+ return _stale_document(conn, scope, digest, identity, occurrences = occurrences) is _ARCHIVEDdef _widen_span(conn, scope: str, digest: str, span: int) -> None:@@ -579,6 +1420,22 @@ def _normalise(text: str) -> str:return (text or "").strip()+def _normalise_cased(text: str) -> str:+ """Whitespace-collapsed but CASE-PRESERVING, for transcript seat matching.++ `Set key Foo` and `Set key FOO` are two different turns: they hash differently, so the+ archive keeps a document for each. Folding case here made `_occurrences` hand BOTH+ seats to BOTH of them, and a turn that believes it has two occurrences to fill gets+ written twice at the next compaction. Measured: four documents for two turns, both+ stamped at both ordinals, and the recall unable to say which spelling was said later+ -- exactly the duplication the whole-turn comparison was added to stop. The two sides+ compared here are the same strings from the same thread, so there is no casing to be+ tolerant of; only the free-text branch filter, which compares a QUERY against saved+ text, still folds case.+ """+ return " ".join((text or "").split())++def _live_transcript(thread_id: str) -> Optional[list[str]]:"""The thread's saved messages, one normalised string each, or None if it has none.@@ -597,7 +1454,9 @@ def _live_transcript(thread_id: str) -> Optional[list[str]]:return Noneif not messages:return None- texts = [_normalise(_probe_text(message)) for message in messages]+ # Through the same reconstruction: a persisted tool call read as ONE message renders in+ # a different order, and the in-order branch check then rejected every agent turn.+ texts = [_normalise(_probe_text(message)) for message in _as_wire(messages)]return [text for text in texts if text] or None@@ -987,9 +1846,249 @@ def _document_matches_one_run(return any(_one_run_from(start) for start in range(len(transcript)))+def _conversation_order(row) -> tuple:+ """Sort key putting recalled turns in the order they were said.++ NULL ordinals sort FIRST, and that is not a fallback so much as a fact: they were+ written by a build that had no such column, so they genuinely predate every numbered+ turn in the same scope. Within a turn, `chunk_index` keeps a long message's pieces+ contiguous and in order, which relevance ordering gets wrong today. `created_at`+ breaks ties, because the ordinal is deliberately not UNIQUE: the write lock is+ best-effort, so two concurrent archive passes can compute the same MAX + 1 and must+ tie-break rather than raise.+ """+ if row is None:+ return (2, 0, "", 0)+ ordinal = tool._row_value(row, "archive_ordinal")+ created = tool._row_value(row, "created_at") or ""+ index = tool._row_value(row, "chunk_index") or 0+ if ordinal is None:+ return (0, 0, created, index)+ return (1, int(ordinal), created, index)+++def _ends_first_within_ties(conn, hits: list) -> list:+ """Reorder each run of EQUAL lexical scores as newest, oldest, next-newest, ...++ A tie is not an order. FTS5 floors the IDF of a term appearing in more than half the+ index at 1e-6, so in a per-thread archive every turn naming the subject of the+ conversation can score identically -- measured at ONE distinct bm25 across eight+ revisions of the same variable. The candidate list then arrives in rowid order, the+ caller truncates it at `top_k`, and the slots go to the OLDEST turns purely because+ SQLite emitted them first: the current value never reached the model, while+ `format_conversation_recall` told it a later turn supersedes an earlier one. A stale+ answer presented as the authoritative one is worse than a miss.++ Newest-first outright is the obvious fix and it is wrong: measured, it fails BOTH+ `test_asking_what_it_was_originally_still_returns_the_first_assignment` -- the guard+ against a fix that just returns the latest thing it can find -- and the tie test+ below it. Both ends is what keeps "what is it now" and "what was it originally"+ answerable out of the same tied run.++ Only WITHIN a run of equal scores, so nothing ever moves past a chunk the ranking pass+ actually separated. Ordering is `_conversation_order`, so legacy NULL ordinals still+ count as oldest.+ """+ if not config.CONVERSATION_QUERY_FOCUS:+ # Reordering candidates is selection, not presentation, so it belongs behind the+ # rollback knob that promises an identical candidate set.+ return hits+ if len(hits) < 2:+ return hits+ if len({hit.lexical_score for hit in hits}) == len(hits):+ # Nothing tied: skip the row fetch entirely, which is the common case.+ return hits+ try:+ rows = store.chunks_by_id(conn, [hit.chunk_id for hit in hits])+ except Exception: # noqa: BLE001 -- ordering must never break a recall+ return hits+ ordered: list = []+ run: list = []++ def _flush():+ if not run:+ return+ by_time = sorted(run, key = lambda hit: _conversation_order(rows.get(hit.chunk_id)))+ while by_time:+ ordered.append(by_time.pop())+ if by_time:+ ordered.append(by_time.pop(0))++ for hit in hits:+ if run and run[-1].lexical_score != hit.lexical_score:+ _flush()+ run = []+ run.append(hit)+ _flush()+ return ordered+++def _lexical_pass(+ conn,+ scope: str,+ query: str,+ model,+ k: int,+ expression,+ *,+ newest_first: bool = False,+ oldest_first: bool = False,+) -> list:+ if newest_first or oldest_first:+ # The archive's lexical legs are always mode "lexical", so this is the same call+ # one layer down, with the tie-break reversed.+ return _ends_first_within_ties(+ conn,+ retrieval.retrieve_lexical(+ conn,+ scope,+ query,+ k,+ match_query = expression,+ newest_first = newest_first,+ oldest_first = oldest_first,+ ),+ )+ return _ends_first_within_ties(+ conn,+ retrieval.retrieve_hybrid(+ conn,+ scope,+ query,+ k = k,+ model_name = model,+ mode = "lexical",+ lexical_query = expression,+ ),+ )+++def _both_ends(oldest: list, newest: list) -> list:+ """One candidate list from a run fetched from each end, oldest side first, no repeats."""+ seen = {hit.chunk_id for hit in oldest}+ return oldest + [hit for hit in newest if hit.chunk_id not in seen]+++def _focused_lexical(conn, scope: str, query: str, model, fetch: int) -> list:+ """Archive lexical candidates: the identifiers FILTER, the content words RANK.++ The identifier pass cannot also do the ranking. FTS5 floors the BM25 IDF of a term+ that appears in more than half of the index at 1e-6 (`ext/fts5/fts5_aux.c`: "if+ (N < 2*nHit), the IDF is negative. Which is undesirable. So the minimum allowable IDF+ is (1e-6)"), and in a per-thread archive the identifier the whole conversation is+ about is exactly such a term. Its hits therefore come back in an order that carries+ no information, so cutting that pass off at ``fetch`` drops turns effectively at+ random -- measured on a 20-turn archive naming one variable, the turn stating its+ current value fell outside the 16 candidates and the recall answered with the four+ oldest turns instead.++ So the identifiers decide WHICH chunks are eligible and the content-word pass decides+ the order among them. Chunks the ranking pass never saw keep their place behind the+ ones it did, and chunks that match only the content words stay last, which is what+ keeps every slot on the subject of the question.+ """+ expressions = (+ store.conversation_match_queries(query) if config.CONVERSATION_QUERY_FOCUS else [None]+ )+ # Only the kill switch takes the plain path. A query made ONLY of an identifier shapes+ # to a single expression, and returning here would hand the query most likely to tie on+ # the IDF floor the one-ended fetch the comment below exists to prevent.+ if not expressions or expressions[0] is None:+ return _lexical_pass(conn, scope, query, model, fetch, None)+ # Fetched from BOTH ENDS of the tied run, not just the front. Every hit on the+ # conversation's own identifier scores the same on the IDF floor and SQLite returns a+ # tied run in rowid order, so `LIMIT 256` is "the oldest 256": on a 300-turn archive+ # the window held ordinals 0-255 and the last turn's value was unreachable. Half from+ # each end keeps "what is it now" and "what was it originally" both answerable.+ _newest_half = _BRANCH_FILTER_MAX_CANDIDATES // 2+ # Re-ordered over the MERGED run, not per half: concatenating two ends-first halves+ # leaves the newest end behind a full window of old turns.+ strict = _ends_first_within_ties(+ conn,+ _both_ends(+ _lexical_pass(+ conn,+ scope,+ query,+ model,+ _BRANCH_FILTER_MAX_CANDIDATES - _newest_half,+ expressions[0],+ oldest_first = True,+ ),+ _lexical_pass(+ conn, scope, query, model, _newest_half, expressions[0], newest_first = True+ ),+ ),+ )+ # One expression means the two passes would run the same query twice: the filter pass+ # already IS the ranking pass, and it is ends-first over both halves.+ if len(expressions) < 2:+ return strict+ # The ranking pass is fetched to the same bound as the filter pass, not to `fetch`. It+ # ranks the ELIGIBLE chunks, and at `fetch` rows its window can be spent entirely on+ # chunks that never name the identifier, since a content word ("current") is ordinary+ # English: nothing eligible is left to order and the answer is dropped. Two-ended for+ # the same reason, and it matters MORE here, because the merged order comes from this+ # pass.+ _loose_k = max(fetch, _BRANCH_FILTER_MAX_CANDIDATES)+ _loose_newest = _loose_k // 2+ loose = _ends_first_within_ties(+ conn,+ _both_ends(+ _lexical_pass(+ conn,+ scope,+ query,+ model,+ _loose_k - _loose_newest,+ expressions[-1],+ oldest_first = True,+ ),+ _lexical_pass(+ conn, scope, query, model, _loose_newest, expressions[-1], newest_first = True+ ),+ ),+ )+ # Eligibility is asked of the index, not read off the strict pass's top rows: that pass+ # is capped and arbitrarily ordered, so past `_BRANCH_FILTER_MAX_CANDIDATES` chunks on+ # the subject the turn stating the current value can be the one left out.+ eligible = {hit.chunk_id for hit in strict}+ try:+ eligible |= store.lexical_matching_ids(+ conn, [hit.chunk_id for hit in loose], expressions[0]+ )+ except Exception:+ # An exact membership test is an improvement, not a dependency: the strict rows on+ # their own are what this did before.+ logger.warning("conversation_archive.eligibility_probe_failed", exc_info = True)+ ranked = [hit for hit in loose if hit.chunk_id in eligible]+ already = {hit.chunk_id for hit in ranked}+ ranked += [hit for hit in strict if hit.chunk_id not in already]+ already |= {hit.chunk_id for hit in strict}+ ranked += [hit for hit in loose if hit.chunk_id not in already]+ return ranked++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")+ """Up to ``fetch`` archive chunks for ``query``: lexical first, hybrid for the rest.++ The lexical pass runs TWICE when the question contains an identifier: once requiring+ one of them, then once over the content words. Requiring them is what stops an+ incidental word in the question outranking the subject of the whole conversation (see+ `store.conversation_match_queries`); running the permissive pass as well is what+ orders the survivors and what stops a filter that matches nothing from reading+ as an empty archive (see `_focused_lexical`). The merged list is what the caller's+ widening loop measures, so a filter returning few rows cannot be mistaken for+ "nothing left to widen into".+ """+ hits: list = []+ seen: set = set()+ for hit in _focused_lexical(conn, scope, query, model, fetch):+ if hit.chunk_id not in seen:+ hits.append(hit)+ seen.add(hit.chunk_id)+ if len(hits) >= fetch:+ breakif len(hits) < fetch:try:seen = {hit.chunk_id for hit in hits}@@ -1016,6 +2115,7 @@ def recall(*,top_k: Optional[int] = None,branch_messages: Optional[list[dict]] = None,+ extra_queries: Optional[list[str]] = None,) -> Optional[tuple[str, list[dict]]]:"""Most relevant archived turns for ``query``, rendered like any other RAG hit.@@ -1038,6 +2138,63 @@ def recall(scope = store.conversation_archive_scope(thread_id)limit = top_k or config.CONVERSATION_ARCHIVE_TOP_K+ # Two queries rather than one concatenated string, which would recreate the defect the+ # shaped query fixes: the filler's tokens dilute the instruction's identifiers and the+ # conjunctive pass would AND two unrelated intents. Run separately, each is shaped on+ # its own and spends its own half of the budget; at a limit of one the anchor wins.+ queries = [query] + [q.strip() for q in (extra_queries or []) if (q or "").strip()]+ if len(queries) > 1:+ share = max(1, -(-limit // len(queries)))+ merged: list = []+ seen_ids: set = set()+ for index, one in enumerate(reversed(queries)):+ # Anchors first: they are the reason the extra query was added at all.+ room = limit - len(merged) if index == len(queries) - 1 else share+ if room <= 0:+ break+ # Over-fetched by what is already held, because the cut used to happen BEFORE+ # the dedup: two queries from the same thread overlap by construction, so every+ # shared chunk cost a slot that was never refilled and adding the anchor made+ # the recall smaller than leaving it out.+ found = recall(+ thread_id, one, top_k = room + len(seen_ids), branch_messages = branch_messages+ )+ if not found:+ continue+ fresh = [source for source in found[1] if source["chunkId"] not in seen_ids]+ # Re-sorted because the inner call orders its OWN slice chronologically, so a+ # widened fetch arrives oldest-first and its head would spend the refilled+ # slots on the oldest turns. By retrieval rank first, score second: the score+ # is rounded for display and identical across a tied run, so sorting on it+ # alone preserved the chronological order. Re-ordered chronologically below.+ fresh.sort(+ key = lambda source: (+ source.get("rank") if source.get("rank") is not None else 1 << 30,+ -(source.get("score") or 0.0),+ )+ )+ for source in fresh[:room]:+ seen_ids.add(source["chunkId"])+ merged.append(source)+ if not merged:+ return None+ if config.CONVERSATION_RECALL_ORDER == "chronological":+ # The same key `_conversation_order` uses on the single-query path: a turn with+ # no ordinal predates every numbered one, and `chunkIndex` keeps a long turn's+ # pieces in writing order rather than in the order the two queries returned+ # them, which a stable sort would otherwise preserve.+ merged.sort(+ key = lambda source: (+ source.get("turn") is not None,+ source.get("turn") or 0,+ source.get("createdAt") or "",+ source.get("chunkIndex") or 0,+ )+ )+ kept = merged[:limit]+ return tool.render_conversation_sources(kept), kept+ kept = merged[:limit]+ return tool.render_sources(kept), keptconn = Nonetry:conn = rag_db.get_connection()@@ -1084,7 +2241,20 @@ def recall(fetch = min(_BRANCH_FILTER_MAX_CANDIDATES, fetch * _BRANCH_FILTER_OVERFETCH)if not hits:return None- text, sources = tool._format(rows, hits)+ if config.CONVERSATION_RECALL_ORDER == "chronological":+ # Retrieval rank, kept before the chronological sort throws it away. The+ # two-query merge refills its slots from these sources and score alone cannot+ # order them: it is rounded to four places, so on a tied archive every+ # candidate carries the SAME score and the refill takes the oldest.+ rank_of = {hit.chunk_id: rank for rank, hit in enumerate(hits)}+ # AFTER the top-k slice, never before: sorting first would make the slice take+ # the oldest turns rather than the most relevant ones.+ hits.sort(key = lambda hit: _conversation_order(rows.get(hit.chunk_id)))+ text, sources = tool.format_conversation_recall(rows, hits)+ for source in sources:+ source["rank"] = rank_of.get(source.get("chunkId"))+ else:+ text, sources = tool._format(rows, hits)return (text, sources) if sources else Noneexcept Exception:logger.warning("conversation_archive.recall_failed thread_id=%s", thread_id, exc_info = True)diff --git a/studio/backend/core/rag/retrieval.py b/studio/backend/core/rag/retrieval.pyindex 920c717aa63..505e6ecb7d2 100644--- a/studio/backend/core/rag/retrieval.py+++ b/studio/backend/core/rag/retrieval.py@@ -28,9 +28,24 @@ def retrieve_lexical(scope: str | list[str],query: str,k: int | None = None,+ *,+ match_query: str | None = None,+ newest_first: bool = False,+ oldest_first: bool = False,) -> list[Hit]:k = k or config.TOP_K_LEXICAL- return [Hit(cid, s, lexical_score = s) for cid, s in store.search_lexical(conn, scope, query, k)]+ return [+ Hit(cid, s, lexical_score = s)+ for cid, s in store.search_lexical(+ conn,+ scope,+ query,+ k,+ match_query = match_query,+ newest_first = newest_first,+ oldest_first = oldest_first,+ )+ ]def retrieve_dense(@@ -111,16 +126,22 @@ def retrieve_hybrid(k: int | None = None,model_name: str | None = None,mode: str = "hybrid",+ lexical_query: str | None = None,) -> list[Hit]:"""``mode`` picks the backend: lexical-only, dense-only, or RRF of both- (default). Pool sizes and the RRF constant come from config."""+ (default). Pool sizes and the RRF constant come from config.++ ``lexical_query`` replaces the FTS5 expression on the LEXICAL leg only. The dense leg+ always encodes the natural-language ``query``, because a conjunction of quoted tokens+ is not a sentence and embedding it would throw away the paraphrase recall that is the+ dense leg's whole reason for existing. No ranking maths changes here."""k = k if k is not None else config.TOP_K_HYBRIDk = int(k) # tool-call / scope top_k may arrive as a float; LIMIT + slice need intif mode == "lexical":- return retrieve_lexical(conn, scope, query, k)+ return retrieve_lexical(conn, scope, query, k, match_query = lexical_query)if mode == "dense":return retrieve_dense(conn, scope, query, k, model_name = model_name)- lexical = retrieve_lexical(conn, scope, query, config.TOP_K_LEXICAL)+ lexical = retrieve_lexical(conn, scope, query, config.TOP_K_LEXICAL, match_query = lexical_query)dense = retrieve_dense(conn, scope, query, config.TOP_K_DENSE, model_name = model_name)return _rrf([lexical, dense], config.RRF_K, k)diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex 76b341762a1..a1360df20a2 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -64,6 +64,9 @@ def _now() -> str:_TOKEN = re.compile(r"\w+", re.UNICODE)+# Straight and curly double quotes, single quotes and backticks: how a user names a word+# instead of using it. Non-greedy and single-line so an unclosed quote spans nothing.+_QUOTED = re.compile(r"\"([^\"\n]+)\"|\u201c([^\u201d\n]+)\u201d|'([^'\n]+)'|`([^`\n]+)`")def _match_query(query: str) -> str:@@ -73,6 +76,138 @@ def _match_query(query: str) -> str:return " OR ".join(f'"{t}"' for t in toks)+# A closed list of function words, so behaviour is identical on every install. Nothing+# here can carry the subject of a question.+#+# `no` and `not` are deliberately NOT here: they carry the whole difference in "what did I+# say not to delete?", where dropping them leaves only terms BM25 floors at 1e-6.+_ARCHIVE_STOPWORDS = frozenset(+ """+a about all am an and any are as at be been being but by can could did do does doing+for from get give had has have how i if in into is it its just let me my now of+on or please should so tell that the their them then there these they this those to us+was we were what when where which who why will with would you your+""".split()+)++# Identifier-ish: a token containing a digit (ZQXVARA123, 9134) or an underscore, or one+# written in capitals and long enough not to be an "I" or an "OK". These are the tokens a+# person uses when they mean one specific thing. Containing a digit, not mixing one with a+# letter: a purely numeric subject ("the current value of 9134") otherwise has no shape at+# all once the capitals rule needs contrast.+_HAS_DIGIT = re.compile(r"\d", re.UNICODE)+_HAS_LETTER = re.compile(r"[^\W\d_]", re.UNICODE)+++def _is_identifier(token: str, raw_tokens: frozenset[str]) -> bool:+ """``raw_tokens`` is the query's tokens BEFORE lower-casing, tokenized once.++ Once, and as a set, because the caller runs this per distinct token: re-scanning the+ query text inside the loop made the whole function quadratic in the question's+ length, which a pasted log turns into a multi-second stall on the request that+ compacts the thread (48 KB of pasted text measured at 4.6s, 96 KB at 17.7s, against+ 2.3ms for the same text through `_match_query`).++ The capitals rule needs CONTRAST, not just capitals: in a line with no lower case+ anywhere every word satisfies it and the filter stops filtering. The caller passes an+ empty ``raw_tokens`` for such a line, so shape alone decides there.+ """+ if "_" in token:+ return True+ if _HAS_DIGIT.search(token):+ # A bare number needs LENGTH to be a name, the same bar the capitals rule carries.+ # Without it "answer in 2 sentences" filters the archive on "2". A token mixing+ # letters and digits is a name at any length.+ return bool(_HAS_LETTER.search(token)) or len(token) >= 3+ return len(token) >= 3 and token.upper() in raw_tokens+++def conversation_match_queries(query: str) -> list[str]:+ """FTS5 expressions for searching a CONVERSATION ARCHIVE, most selective first.++ Why the archive needs its own query shaping, when `_match_query` is fine everywhere+ else: in a per-thread archive the SUBJECT of the conversation is by construction+ present in many chunks, so BM25 gives it almost no weight, while an incidental word+ from the question appears once and dominates. Measured on an archive of 17 chunks+ about one variable: `zqxvara123` scored 0.16 and `value`, from "what is the current+ value of X", scored 4.755. ORing them lets the filler decide the ranking, and a chunk+ about "a good default value for a retry budget" outranks every chunk that names the+ variable. The subject of a long conversation becomes the least discriminative term in+ its own archive.++ So: first REQUIRE the identifier-like tokens, which restricts the candidates to+ chunks that are actually about the thing asked about; then fall back to an OR over+ the content words. Two expressions rather than one, because a filter that matches+ nothing must not mean "this archive has nothing to say".++ A question made entirely of function words ("what about it?") keeps all its tokens:+ an empty expression would make `search_lexical` return nothing at all, and a query+ that retrieves the wrong turns is still better than a recall that silently vanishes+ on exactly the turns that needed it.++ SEVERAL identifiers are ORed, not ANDed. "What are the current values of A123 and+ B456" is two questions in one envelope, and the turn answering either one names one+ of them: requiring both keeps only the turns that DISCUSS the pair, which are exactly+ the older comparisons, and drops both current assignments. Measured on an archive of+ six comparison turns plus one latest assignment each: the conjunction returned the+ four oldest comparisons and neither value, where the permissive pass returns both.+ The filter's job is to keep every slot on something the question asked about, and one+ identifier out of two is still that; the content-word pass still does the ranking,+ and a chunk naming both still outranks a chunk naming one, because it matches more.+ """+ tokens = list(dict.fromkeys(_TOKEN.findall(query.lower())))+ if not tokens:+ return []+ # The capitals rule needs CONTRAST: in an all-caps line every word passes it, so the+ # filter ORs in "what" and "the" and filters nothing. Shape still decides, so+ # ZQXVARA123 is an identifier either way; only shouted prose changes.+ raw_tokens = frozenset() if query == query.upper() else frozenset(_TOKEN.findall(query))+ identifiers = [t for t in tokens if _is_identifier(t, raw_tokens)]+ # A QUOTED word is the subject whatever the stopword list thinks: `What did I say about+ # "this"?` otherwise reduces to '"say"' and an archived `Use this endpoint` is+ # unreachable. Quoted tokens stay out of `identifiers`, so this widens only the+ # permissive pass.+ quoted = frozenset(+ token+ for match in _QUOTED.findall(query.lower())+ for token in _TOKEN.findall("".join(match))+ )+ content = [t for t in tokens if t not in _ARCHIVE_STOPWORDS or t in quoted] or tokens+ permissive = " OR ".join(f'"{t}"' for t in content)+ if not identifiers:+ return [permissive]+ focused = " OR ".join(f'"{t}"' for t in identifiers)+ return [focused] if focused == permissive else [focused, permissive]+++def lexical_matching_ids(conn: sqlite3.Connection, chunk_ids, expression: str) -> set:+ """Which of ``chunk_ids`` match ``expression``, by the index's own tokenizer.++ Membership, not ranking, and therefore not subject to any top-k window. A ranked pass+ truncated at k answers "is this chunk among the k the index happened to return",+ which is a different question and the wrong one when the scores are tied: FTS5 floors+ the BM25 IDF of a term present in more than half the index at 1e-6, so the identifier+ a whole thread is about orders nothing and the k that come back are arbitrary. Asking+ the index directly, restricted to candidates already in hand, is exact however long+ the thread gets.+ """+ ids = list(dict.fromkeys(chunk_ids))+ if not ids or not expression:+ return set()+ found: set = set()+ # Chunked to stay under SQLITE_MAX_VARIABLE_NUMBER, which is 999 on older builds.+ for start in range(0, len(ids), 500):+ batch = ids[start : start + 500]+ placeholders = ",".join("?" * len(batch))+ rows = conn.execute(+ f"SELECT chunk_id FROM chunks_fts WHERE chunks_fts MATCH ? "+ f"AND chunk_id IN ({placeholders})",+ [expression, *batch],+ ).fetchall()+ found.update(row[0] for row in rows)+ return found++def create_kb(conn: sqlite3.Connection,*,@@ -145,13 +280,25 @@ def create_document(linked_folder_id: str | None = None,linked_relative_path: str | None = None,archive_messages: int | None = None,+ archive_ordinal: int | None = None,+ created_at: str | None = None,commit: bool = True,) -> str:+ """``created_at`` is for a REWRITE of a row that already exists, and nothing else.++ A re-embed deletes the old row and inserts a new one for the same content, so stamping+ it with the current time would say the turn was archived when its vectors were+ rebuilt. That is not a cosmetic difference for an archived turn: an archive written+ before `archive_ordinal` existed is ordered by `created_at` alone, so a rewrite that+ takes a fresh timestamp moves that turn to the end of its own conversation. Omitted,+ this is byte for byte what every other caller has always got.+ """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, archive_messages) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",+ "linked_relative_path, archive_messages, archive_ordinal) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",(document_id,scope,@@ -162,11 +309,12 @@ def create_document(sha256,status,stored_path,- _now(),+ created_at or _now(),embedding_model,linked_folder_id,linked_relative_path,archive_messages,+ archive_ordinal,),)if commit:@@ -229,6 +377,21 @@ def list_all_documents(conn: sqlite3.Connection) -> list[dict]:return [dict(r) for r in rows]+def next_archive_ordinal(conn: sqlite3.Connection, scope: str) -> int:+ """The next conversation position for an archived turn group in this scope.++ Deliberately not derived from `created_at`: every turn a single compaction evicts is+ written microseconds apart, so wall-clock separates compaction EPOCHS and says+ nothing about order WITHIN one. This counter does, because `archive_turns` allocates+ it in `group_turns` order.+ """+ row = conn.execute(+ "SELECT COALESCE(MAX(archive_ordinal), -1) + 1 AS n FROM documents WHERE scope=?",+ (scope,),+ ).fetchone()+ return int(row["n"]) if row else 0++def get_document(conn: sqlite3.Connection, document_id: str) -> dict | None:row = conn.execute("SELECT * FROM documents WHERE id=?", (document_id,)).fetchone()return dict(row) if row else None@@ -254,6 +417,27 @@ def document_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> str |return row["id"] if row else None+def documents_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> list[dict]:+ """Every live copy of this text in the scope, oldest first.++ The archive can legitimately hold more than one: a user who says the same thing twice+ in one conversation said it twice, and the second time is often the one that matters.+ Ordered so the nth copy lines up with the nth occurrence in the transcript.+ """+ rows = conn.execute(+ "SELECT id, archive_ordinal, embedding_model, created_at FROM documents "+ "WHERE scope=? AND sha256=? AND status!='failed' AND linked_folder_id IS NULL "+ "ORDER BY COALESCE(archive_ordinal, -1), created_at",+ (scope, sha256),+ ).fetchall()+ return [dict(row) for row in rows]+++def set_archive_ordinal(conn: sqlite3.Connection, document_id: str, ordinal: int) -> None:+ """Re-stamp one document's position. Used to migrate rows numbered by archive time."""+ conn.execute("UPDATE documents SET archive_ordinal=? WHERE id=?", (int(ordinal), document_id))++def failed_documents_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> list[dict]:rows = conn.execute("SELECT id, stored_path FROM documents WHERE scope=? AND sha256=? AND status='failed' "@@ -353,10 +537,31 @@ def linked_folder_rows_exist(conn: sqlite3.Connection) -> bool:)-def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):+def search_lexical(+ conn: sqlite3.Connection,+ scope,+ query: str,+ k: int,+ *,+ match_query: str | None = None,+ newest_first: bool = False,+ oldest_first: bool = False,+):"""BM25 lexical search over one scope or several. Returns- [(chunk_id, score)], higher = better."""- mq = _match_query(query)+ [(chunk_id, score)], higher = better.++ `match_query` lets a caller supply the FTS5 expression itself; the conversation+ archive shapes its own (see `conversation_match_queries`). Omitted, this is byte for+ byte what every other caller has always got.++ `newest_first` breaks TIES the other way round. FTS5 floors the IDF of a term the+ whole index shares, so every hit on a per-thread archive's own subject scores the+ same, and `ORDER BY s LIMIT k` then returns the k OLDEST rows: past k chunks on that+ subject the newest assignment is unreachable at any k. Ordering is by rowid, which is+ insertion order rather than exact conversation order, so this widens the candidate+ set and does not decide anything; the caller still orders what it gets.+ """+ mq = match_query if match_query is not None else _match_query(query)if not mq:return []scopes = _scopes(scope)@@ -373,7 +578,36 @@ def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):# The filtered form joins chunks and documents and runs both subqueries for every# matched row BEFORE the LIMIT, so it costs more the commoner the query terms are.# With nothing linked that work is provably wasted (linked_folder_rows_exist).- if linked_folder_rows_exist(conn):+ if oldest_first:+ # The mirror of `newest_first`, for the same reason: rowid ordering is+ # scrambled by a re-embed, which can push the oldest turn out of the window.+ # NULLs first, since a row archived before the column existed is the oldest.+ # Then `created_at`, then the chunk id: on a LEGACY archive every ordinal is+ # NULL, so every term after the score was constant and both halves of the+ # two-ended fetch returned the same arbitrary subset, which `_both_ends` then+ # deduplicated -- the 256-candidate strategy reaching one end twice and the+ # later revisions not at all.+ sql = (+ f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "+ f"JOIN chunks c ON c.id=chunks_fts.chunk_id "+ f"JOIN documents d ON d.id=c.document_id "+ f"WHERE chunks_fts MATCH ? AND chunks_fts.scope IN ({placeholders}) "+ f"ORDER BY s, d.archive_ordinal IS NOT NULL, d.archive_ordinal ASC, "+ f"d.created_at ASC, chunks_fts.chunk_id ASC LIMIT ?"+ )+ elif newest_first:+ # Ordered by archive ordinal, not rowid: rowid is insertion order, and a+ # re-embed reinserts a chunk, so a rowid DESC window returned ordinals+ # 70, 193, 116, ... and missed the newest turn. NULLs sort last, as oldest.+ sql = (+ f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "+ f"JOIN chunks c ON c.id=chunks_fts.chunk_id "+ f"JOIN documents d ON d.id=c.document_id "+ f"WHERE chunks_fts MATCH ? AND chunks_fts.scope IN ({placeholders}) "+ f"ORDER BY s, d.archive_ordinal IS NULL, d.archive_ordinal DESC, "+ f"d.created_at DESC, chunks_fts.chunk_id DESC LIMIT ?"+ )+ elif linked_folder_rows_exist(conn):sql = (f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "f"JOIN chunks c ON c.id=chunks_fts.chunk_id "@@ -533,7 +767,7 @@ def chunks_by_id(conn: sqlite3.Connection, ids) -> dict:placeholders = ",".join("?" * len(ids))rows = conn.execute(f"SELECT c.id, c.text, c.document_id, c.chunk_index, c.page_number, "- f"c.source_page_index, d.filename "+ f"c.source_page_index, d.filename, d.archive_ordinal, d.created_at "f"FROM chunks c JOIN documents d ON d.id=c.document_id "f"WHERE c.id IN ({placeholders}) AND NOT EXISTS "f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "diff --git a/studio/backend/core/rag/tool.py b/studio/backend/core/rag/tool.pyindex 4cc4b876701..e4494f0c1fa 100644--- a/studio/backend/core/rag/tool.py+++ b/studio/backend/core/rag/tool.py@@ -104,6 +104,92 @@ def _format(rows, hits) -> tuple[str, list[dict]]:return "\n\n".join(blocks), sources+CONVERSATION_RECALL_HEADER = (+ "These are earlier turns of THIS conversation, quoted verbatim and listed oldest "+ "first. The turn number is each one's position in the conversation; they are not "+ "consecutive. Where two turns state different things about the same subject, the one "+ "with the HIGHER turn number was said later and supersedes the earlier one."+)+++def format_conversation_recall(rows, hits) -> tuple[str, list[dict]]:+ """`_format`, plus what a recalled conversation needs and a knowledge base does not.++ Two additions, both presentation only:++ * each block carries ``turn``, the position of that turn in the conversation, so the+ passages can be told apart in time. Omitted where the archive predates the column,+ because a missing ordinal is not a position of zero.+ * a one-line header, emitted only when there are at least two passages, stating that+ they are oldest first and that a later turn supersedes an earlier one. It says+ SUPERSEDES rather than "is the answer", so a question about what was originally+ said still reads the first block as the original. With a single passage the header+ would be an ordering claim about nothing, and it would spend tokens on the rung the+ over-budget backoff falls to when there is least room.+ """+ if not hits:+ return "No matching turns were found in this conversation.", []+ blocks: list[str] = []+ sources: list[dict] = []+ for i, h in enumerate(hits, 1):+ r = rows.get(h.chunk_id)+ filename = (r["filename"] if r else None) or "unknown"+ text = r["text"] if r else ""+ ordinal = _row_value(r, "archive_ordinal")+ turn_attr = f" turn={quoteattr(str(int(ordinal) + 1))}" if ordinal is not None else ""+ blocks.append(f'<chunk id="{i}" source={quoteattr(filename)}{turn_attr}>\n{text}\n</chunk>')+ sources.append(+ {+ "citationId": i,+ "chunkId": h.chunk_id,+ "documentId": r["document_id"] if r else None,+ "filename": filename,+ "page": None,+ "text": text,+ "turn": int(ordinal) + 1 if ordinal is not None else None,+ # Carried so a merge of two searches can reorder one long turn's pieces;+ # nothing renders them. `createdAt` is the tie-breaker `_conversation_order`+ # needs, since pre-ordinal rows have `turn` None and ordinals are not UNIQUE.+ "chunkIndex": _row_value(r, "chunk_index"),+ "createdAt": _row_value(r, "created_at"),+ "score": round(float(h.score), 4) if h.score is not None else None,+ }+ )+ body = "\n\n".join(blocks)+ if len(hits) >= 2:+ body = f"{CONVERSATION_RECALL_HEADER}\n\n{body}"+ return body, sources+++def render_conversation_sources(sources: list[dict]) -> str:+ """`render_sources` for recalled conversation: keeps ``turn`` and the header.++ Used when two searches are merged into one block, where the sources are already built+ and there are no rows left to read them from.+ """+ blocks: list[str] = []+ for i, s in enumerate(sources, 1):+ s["citationId"] = i+ turn = s.get("turn")+ turn_attr = f" turn={quoteattr(str(turn))}" if turn is not None else ""+ blocks.append(+ f'<chunk id="{i}" source={quoteattr(s.get("filename") or "unknown")}'+ f'{turn_attr}>\n{s.get("text") or ""}\n</chunk>'+ )+ body = "\n\n".join(blocks)+ return f"{CONVERSATION_RECALL_HEADER}\n\n{body}" if len(sources) >= 2 else body+++def _row_value(row, key: str):+ """A column that may not exist on an older row object, without raising."""+ if row is None:+ return None+ try:+ return row[key]+ except (IndexError, KeyError):+ return None++def render_sources(sources: list[dict]) -> str:"""Render a citation-source list to sequentially-numbered ``<chunk>`` blocks,rewriting each source's ``citationId`` to match its 1-based position. Letsdiff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex 0e055c22f41..9641eda868b 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -259,6 +259,17 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:# 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")+ # An archived turn group's position in its conversation. NULL elsewhere and for older+ # archives, which fall back to created_at ordering. Not backfilled: created_at cannot+ # recover the order within a compaction epoch.+ if "archive_ordinal" not in cols:+ conn.execute("ALTER TABLE documents ADD COLUMN archive_ordinal INTEGER")+ # Partial, so it is empty until a chat is compacted and the MAX() that allocates the+ # next ordinal is an index probe rather than a scan.+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_documents_archive_ordinal "+ "ON documents(scope, archive_ordinal) WHERE archive_ordinal IS NOT NULL"+ )# 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/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.pyindex 1239b1830d4..8356efc8adc 100644--- a/studio/backend/tests/test_context_overflow_truncation.py+++ b/studio/backend/tests/test_context_overflow_truncation.py@@ -1017,3 +1017,275 @@ def test_the_compaction_headroom_needs_a_boundary_to_be_worth_it():# 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)+++# --- Keeping the user's standing instruction when everything else is evicted ---+#+# `truncate_oldest_messages` protects the newest USER group, so an instruction is safe only+# while it IS that group: one "continue" later it is the first thing evicted. These cover+# the pin that holds it and the bounds that stop the pin becoming the problem.+++def _instruction(text = None):+ return {+ "role": "user",+ "content": text+ or (+ "Standing instruction for the rest of this task: always report results as a "+ "markdown table, and end every reply with STATUS::ZQXVARA123-ALPHA."+ ),+ }+++def _filler_turns(count, chars = 800):+ """Short user nudges with long agent replies, which is the shape that produces the+ defect: the user types "keep going", the agent writes a page, and the newest USER+ group -- the only one the window protects -- is the nudge."""+ nudges = ["continue", "keep going", "yes", "ok", "go on", "proceed"]+ out = []+ for index in range(count):+ out.append({"role": "user", "content": nudges[index % len(nudges)]})+ out.append({"role": "assistant", "content": f"Section {index}. " + "x" * chars})+ return out+++def test_a_governing_instruction_survives_filler_turns():+ from core.inference import instruction_pin+ from core.inference.context_window import truncate_oldest_messages++ instruction = _instruction()+ messages = (+ [+ {"role": "system", "content": "you are helpful"},+ instruction,+ {"role": "assistant", "content": "Understood."},+ ]+ + _filler_turns(6)+ + [{"role": "user", "content": "continue"}]+ )++ pinned = instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 1024)+ kept, dropped = truncate_oldest_messages(messages, 0.3, protected_message_ids = pinned)++ assert any(message is instruction for message in kept)+ assert dropped >= 2+ # And with the knob at its shipped default the behaviour is exactly today's.+ kept_today, _ = truncate_oldest_messages(+ messages,+ 0.3,+ protected_message_ids = instruction_pin.pinned_instruction_ids(messages, groups = 0),+ )+ assert not any(message is instruction for message in kept_today)+++def test_a_pinned_instruction_cannot_starve_the_window():+ """The single enormous instruction is the thing that could starve the window, so it+ is the thing the ceiling excludes -- not partially, at all."""+ from core.inference import instruction_pin++ # ~890 tokens each, so any one of them fits under the 1024 ceiling and no two do.+ big = [_instruction("Please " + "consider this requirement carefully. " * 95) for _ in range(3)]+ messages = []+ for instruction in big:+ messages += [instruction, {"role": "assistant", "content": "ok"}]+ messages += [{"role": "user", "content": "continue"}]++ pinned = instruction_pin.pinned_instruction_ids(messages, groups = 3, max_tokens = 1024)++ assert len(pinned) == 1+++def test_later_long_user_turns_crowd_out_an_older_instruction():+ """The bound is newest-first over a fixed number of groups, so a standing instruction+ with enough long user turns after it is NOT pinned. This is the same hole Zed's 80 KB+ newest-first replay has, and it is recorded here rather than left to be discovered:+ the pin protects an instruction against FILLER, not against a long conversation.+ """+ from core.inference import instruction_pin++ instruction = _instruction()+ messages = [instruction, {"role": "assistant", "content": "Understood."}]+ for index in range(3):+ messages += [+ {+ "role": "user",+ "content": f"Now review section {index} of the "+ f"report and summarise it. " + "x" * 400,+ },+ {"role": "assistant", "content": f"Section {index} reviewed."},+ ]+ messages += [{"role": "user", "content": "continue"}]++ pinned = instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 4096)++ assert id(instruction) not in pinned+ # It is reachable, though, once the budget covers the turns in between.+ wide = instruction_pin.pinned_instruction_ids(messages, groups = 4, max_tokens = 4096)+ assert id(instruction) in wide+++def test_a_short_follow_up_is_never_pinned():+ """ "pin the last N user turns" would pin the nudge and leave the instruction."""+ from core.inference import instruction_pin++ instruction = _instruction()+ messages = [+ instruction,+ {"role": "assistant", "content": "Understood."},+ {"role": "user", "content": "ok, keep going"},+ {"role": "assistant", "content": "continuing"},+ {"role": "user", "content": "continue"},+ ]++ pinned = instruction_pin.pinned_instruction_ids(messages, groups = 3, max_tokens = 4096)++ assert pinned == {id(instruction)}+++def test_an_upload_is_never_treated_as_filler():+ """A one-word message with an image attached is a request, not a nudge."""+ from core.inference import instruction_pin++ message = {+ "role": "user",+ "content": [+ {"type": "text", "text": "this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ ],+ }++ assert instruction_pin.is_substantive(message)+++def test_a_thin_query_is_recognised_but_a_short_real_question_is_not():+ from core.inference import instruction_pin++ assert instruction_pin.is_thin_query("continue")+ assert instruction_pin.is_thin_query("yes")+ assert instruction_pin.is_thin_query("ok!")+ # Keyboards autocorrect "..." to one ellipsis character, which used to survive the+ # punctuation strip, so `continue…` was called substantive.+ assert instruction_pin.is_thin_query("continue…")+ assert instruction_pin.is_thin_query("and then…")+ assert instruction_pin.is_thin_query("continue...")+ # Short, but it names what it wants, so an older instruction must not replace it.+ assert not instruction_pin.is_thin_query("what is ZQXVARA123 now?")+ assert not instruction_pin.is_thin_query("what is ZQXVARA123 now…")+++def test_a_self_contained_two_word_request_is_not_thin():+ """Thin has to mean "names nothing", not "is short".++ A word count swept in every self-contained short request, and a thin query earns an+ anchor that `conversation_archive.recall` spends AHEAD of the user's own words. At+ top_k=1 -- which the over-budget backoff (4 -> 2 -> 1) and a small window both reach,+ since `_recall_top_k` is `budget // CHUNK_TOKENS` -- the anchor takes the only slot+ and the turn answering what was actually asked is never retrieved.+ """+ from core.inference import instruction_pin++ for request in ("review billing", "restart nginx", "fix authentication", "ZQXVARA123?"):+ assert not instruction_pin.is_thin_query(request), request++ # Still thin: every word is a function word or a nudge, so there is nothing to search.+ for nudge in ("what about it", "and then?", "do it", "yes please", "why?", "???"):+ assert instruction_pin.is_thin_query(nudge), nudge+++def test_a_pin_is_charged_for_everything_it_holds():+ """`truncate_oldest_messages` protects by GROUP, so the reply rides along with the+ instruction. Charging only the instruction let a 28-token pin hold 20037 tokens, past+ both the ceiling and the prompt-fraction cap, and `_fit_with_instruction_pins` then+ dropped every pin on the retry -- losing the instruction the pin exists to keep."""+ from core.inference import instruction_pin++ instruction = _instruction()+ messages = [+ {"role": "system", "content": "you are helpful"},+ instruction,+ {"role": "assistant", "content": "x " * 40000},+ {"role": "user", "content": "continue"},+ ]++ assert instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 1024) == set()++ # And the same instruction with a reply the budget can afford is still pinned.+ modest = list(messages)+ modest[2] = {"role": "assistant", "content": "Understood."}+ assert instruction_pin.pinned_instruction_ids(modest, groups = 2, max_tokens = 1024) == {+ id(instruction)+ }+++def test_a_pin_charges_token_dense_text_at_its_real_rate():+ """The ceiling is only a ceiling if the turn is charged what it really costs.++ Four characters per token undercharges CJK and emoji by roughly 2x or more, so a turn+ that really costs 1056 tokens was charged 276 and cleared a 1024 ceiling it was nowhere+ near. The pin then held far more than the budget allows and the fitter evicted recent+ turns to pay for it, which is the failure the budget exists to prevent.+ """+ from core.inference import instruction_pin++ dense_instruction = {+ "role": "user",+ "content": "必ず表形式で回答し、末尾に STATUS を付けてください。" * 40,+ }+ messages = [+ {"role": "system", "content": "you are helpful"},+ dense_instruction,+ {"role": "assistant", "content": "承知しました。" * 20},+ {"role": "user", "content": "continue"},+ ]++ # Its real cost is over the ceiling, so it is not pinned at all rather than partially.+ assert instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 1024) == set()+ # A ceiling that can afford it still pins it, so this is a charge and not a refusal.+ assert instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 4096) == {+ id(dense_instruction)+ }+++def test_a_pin_is_not_charged_for_a_tool_exchange_it_does_not_hold():+ """A trailing tool exchange is its own group, and `truncate_oldest_messages` skips a+ protected group BEFORE the `starts_user_turn` expansion, so that group stays an+ independent eviction unit and goes while the pinned instruction stays. Charging it to+ the pin would let one ordinary file read cost a one-line instruction its pin over+ tokens the pin never keeps -- and an agent run is exactly where the filler follow-up+ the pin exists for appears."""+ from core.inference import instruction_pin+ from core.inference.context_window import truncate_oldest_messages++ instruction = _instruction()+ tool_call = {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "read", "arguments": "{}"}}],+ }+ tool_result = {"role": "tool", "tool_call_id": "c1", "content": "y " * 40000}+ messages = [+ {"role": "system", "content": "you are helpful"},+ instruction,+ tool_call,+ tool_result,+ {"role": "user", "content": "continue"},+ ]++ pinned = instruction_pin.pinned_instruction_ids(messages, groups = 2, max_tokens = 1024)+ assert pinned == {id(instruction)}++ # And the 20k tokens it was being charged for are evicted anyway, with the pin on.+ kept, dropped = truncate_oldest_messages(messages, 0.01, protected_message_ids = pinned)+ assert any(message is instruction for message in kept)+ assert not any(message is tool_call for message in kept)+ assert not any(message is tool_result for message in kept)+ assert dropped == 2++ # The reply sharing the instruction's group is still charged, so the ceiling holds.+ with_reply = [+ {"role": "system", "content": "you are helpful"},+ instruction,+ {"role": "assistant", "content": "x " * 40000},+ {"role": "user", "content": "continue"},+ ]+ assert instruction_pin.pinned_instruction_ids(with_reply, groups = 2, max_tokens = 1024) == set()diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.pyindex 39ce78affd9..e15ebe5881d 100644--- a/studio/backend/tests/test_conversation_archive.py+++ b/studio/backend/tests/test_conversation_archive.py@@ -11,7 +11,7 @@ import pytestsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))-from core.rag import conversation_archive, retrieval, store # noqa: E402+from core.rag import config, conversation_archive, retrieval, store # noqa: E402from storage import rag_db # noqa: E402THREAD = "thread-abc"@@ -100,10 +100,17 @@ def test_evicted_turns_are_archived_under_the_conversation_scope(conn):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."""+ """The same turns are evicted again on every later request, so repeats must be free.++ `persist = False` on the repeat because that is what the scenario actually is: the+ transcript is written once and the SAME turns are handed to the archive again on the+ next request. Appending them to the thread a second time would describe a different+ situation, a user who said the same thing twice, which is now a real distinction:+ ordinals come from the transcript, and a genuine repeat is stored as its own turn.+ """turn = _turn("what is a duck", "a waterfowl")first = _archive(turn)- second = _archive(turn)+ second = _archive(turn, persist = False)scope = store.conversation_archive_scope(THREAD)assert (first, second) == (1, 0)@@ -183,10 +190,13 @@ def test_recall_degrades_to_lexical_when_dense_retrieval_raises(monkeypatch, conk = None,model_name = None,mode = "hybrid",+ lexical_query = None,):if mode != "lexical":raise RuntimeError("no embedding backend available")- return real_hybrid(conn_, scope, query, k = k, model_name = model_name, mode = mode)+ return real_hybrid(+ conn_, scope, query, k = k, model_name = model_name, mode = mode, lexical_query = lexical_query+ )monkeypatch.setattr(retrieval, "retrieve_hybrid", only_lexical_works)found = conversation_archive.recall(THREAD, "sourdough")@@ -1572,265 +1582,2486 @@ def test_a_first_compaction_embeds_its_turns_in_one_pass(conn, monkeypatch):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 subject of a conversation must not be the least findable thing in its archive ---+#+# Measured on the pre-fix build with `scripts/fact_update/retrieval_probe.py`: a variable+# revised seven times was archived 8/8 and retrieved 0/5, because BM25 gives almost no+# weight to a term present in half the chunks. `zqxvara123` scored 0.16; `value`, from the+# question itself, scored 4.755.++VARIABLE = "ZQXVARA123"+++# Filler that VARIES. The defect is an IDF collapse, so it only reproduces while the+# question's incidental word ("value") is rare: a fixture repeating one distractor made+# "value" as common as the variable and passed against the unfixed build.+_DISTRACTORS = [+ (+ "What is a good default value for a retry budget?",+ "Three attempts with backoff is a common default.",+ ),+ ("Change the log level to debug for now.", "Log level is debug."),+ ("Remind me to update the deployment notes later.", "I will remind you."),+ ("Is it better to set a timeout per request or per session?", "Per request is usually safer."),+ (+ "Correction to my earlier note about the changelog wording.",+ "Noted, the changelog wording is corrected.",+ ),+ ("Which branch should the release notes land on?", "The release branch."),+]+++def _revisions(+ count,+ thread_id = THREAD,+ *,+ distractors = 3,+):+ """A variable assigned, then revised, with filler that shares the vocabulary.- 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.+ Values are fixed rather than random so a failure is reproducible, and the filler never+ names the variable, so it can compete for slots without ever being a correct answer."""- 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+ values = [f"10000{index}" for index in range(count)]+ filler = 0+ for value in values:+ _archive(+ _turn(f"Set {VARIABLE} to {value}.", f"Understood. {VARIABLE} is {value}."), thread_id+ )+ for _ in range(distractors):+ question, answer = _DISTRACTORS[filler % len(_DISTRACTORS)]+ filler += 1+ _archive(_turn(f"{question} (note {filler})", answer), thread_id)+ return values- 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+def test_every_recall_slot_goes_to_the_subject_of_the_question(conn):+ """Pre-fix this returns four distractors and not one turn about the variable.- chat_history._remove_conversation_archives([thread_id], cutoff = cutoff)+ What the fix guarantees is the CANDIDATE SET: only turns naming the thing asked+ about. Which of eight equally-scoring assignments wins a slot is BM25's business and+ is not claimed here -- see `test_the_newest_revision_is_recalled_when_there_is_room`+ for the part that is.+ """+ values = _revisions(8)- 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()+ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE}?", top_k = 4)- 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 found is not None+ text, sources = found+ assert len(sources) == 4+ assert all(VARIABLE.lower() in source["text"].lower() for source in sources)+ assert any(value in text for value in values)- 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_the_newest_revision_is_recalled_when_there_is_room(conn):+ """With a slot per revision the newest must be there, and must be read last."""+ values = _revisions(4)-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.+ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE}?", top_k = 4+ )- `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 found is not None+ text, _sources = found+ assert values[-1] in text+ # Chronological presentation is the point: the LAST assignment read is the current one.+ assert max(text.index(value) for value in values if value in text) == text.index(values[-1])- assert conversation_archive._document_matches_one_run([{"text": text}], live, 2) is True+def test_the_questions_filler_cannot_outrank_the_subject(conn):+ """One slot, and it must go to the turn about the thing asked about."""+ for index in range(6):+ _archive(_turn(f"Set {VARIABLE} to 42{index}.", f"Understood. {VARIABLE} is 42{index}."))+ _archive(+ _turn(+ "What is a good default value for a retry budget?",+ "Three attempts with backoff is a common default value.",+ )+ )-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.+ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE}?", top_k = 1+ )- 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 found is not None+ assert VARIABLE.lower() in found[0].lower()- assert (- conversation_archive._document_matches_one_run([{"text": text}], live, 2) is True- ), f"cut {where}"+def test_the_archive_query_requires_the_rare_token_and_drops_filler():+ """The conjunctive pass first, the stopword-stripped OR second, and never nothing."""+ focused = store.conversation_match_queries(f"What is the current value of {VARIABLE}?")-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.+ assert focused[0] == f'"{VARIABLE.lower()}"'+ assert '"current"' in focused[1] and '"value"' in focused[1]+ assert '"what"' not in focused[1] and '"the"' not in focused[1]+ # An all-function-word question must still search for something: an empty expression+ # makes search_lexical return [] and the recall silently vanishes.+ filler = store.conversation_match_queries("what about it")+ assert filler and '"about"' in filler[0]+ assert store.conversation_match_queries("!!!") == []- 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_recalled_turns_are_presented_oldest_first(conn):+ """The model answers with the last assignment it reads, so the order IS the answer."""+ _archive(+ _turn(f"Set {VARIABLE} to 111111. " + "Some padding about the topic. " * 40, "Understood."))+ _archive(_turn(f"{VARIABLE} 222222", "Understood."))+ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE}?", top_k = 2+ )-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+ assert found is not None+ text, sources = found+ assert text.index("111111") < text.index("222222")+ assert "supersedes" in text+ assert sources[0]["citationId"] == 1- 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- )+def test_each_archived_turn_records_its_position(conn):+ _archive(_turn("first", "a"))+ _archive(_turn("second", "b"))+ _archive(_turn("third", "c"))- _archive(group)scope = store.conversation_archive_scope(THREAD)- spans = [- row["archive_messages"]+ ordinals = [+ row["archive_ordinal"]for row in conn.execute(- "SELECT archive_messages FROM documents WHERE scope=?", (scope,)+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),).fetchall()]- assert spans == [4], spans+ assert ordinals == [0, 1, 2]-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.+def test_re_embedding_a_turn_keeps_its_place(conn, monkeypatch):+ """Re-embedding walks the whole archive, so a fresh ordinal here would renumber the+ entire conversation into the order its vectors were rebuilt."""+ from core.rag import embeddings- 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))+ # `embedding_identity` too, not only the encode: `archive_turns` short-circuits on the+ # expected identity, so patching the encode alone never reaches the re-embed path.+ 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"])- _archive(short)- _archive(long)+ first = _turn("the oldest turn", "a")+ assert _archive([dict(message) for message in first]) == 1+ assert _archive(_turn("a later turn", "b")) == 1+ identity["name"] = "st:model-b"+ assert _archive([dict(message) for message in first]) == 1scope = store.conversation_archive_scope(THREAD)rows = conn.execute(- "SELECT archive_messages, sha256 FROM documents WHERE scope=?", (scope,)+ "SELECT filename, archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),).fetchall()- assert [row["archive_messages"] for row in rows] == [4], "the window stayed at the shorter span"+ assert [row["archive_ordinal"] for row in rows] == [0, 1]- # 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_an_archive_written_before_ordinals_still_recalls_in_order(conn):+ """NULL ordinals predate the column, so they sort first rather than not at all."""+ _archive(_turn("the pelican turn", "older"))+ _archive(_turn("the pelican answer", "newer"))+ scope = store.conversation_archive_scope(THREAD)+ oldest = conn.execute(+ "SELECT id FROM documents WHERE scope=? ORDER BY archive_ordinal", (scope,)+ ).fetchone()["id"]+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE id=?", (oldest,))+ conn.commit()-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.+ found = conversation_archive.recall(THREAD, "pelican", top_k = 2)- `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+ assert found is not None+ text, _sources = found+ assert text.index("older") < text.index("newer")+ assert 'turn="1"' not in text # the NULL one claims no position+ assert 'turn="2"' in text+++def test_asking_what_it_was_originally_still_returns_the_first_assignment(conn):+ """The guard against a fix that just prefers the newest thing it can find."""+ values = _revisions(8)++ found = conversation_archive.recall(+ THREAD, f"What was {VARIABLE} set to at the very start?", top_k = 4+ )++ assert found is not None+ text, sources = found+ assert values[0] in text+ # First block, because the original assignment is the oldest turn in the set.+ assert values[0] in sources[0]["text"]+++def test_relevance_order_is_restored_when_the_knobs_are_off(conn, monkeypatch):+ """The off setting has to reproduce the previous build, not approximate it."""+ from core.rag import config++ monkeypatch.setattr(config, "CONVERSATION_QUERY_FOCUS", False)+ monkeypatch.setattr(config, "CONVERSATION_RECALL_ORDER", "relevance")+ _archive(+ _turn(f"Set {VARIABLE} to 111111. " + "Some padding about the topic. " * 40, "Understood.")+ )+ _archive(_turn(f"{VARIABLE} 222222", "Understood."))++ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE}?", top_k = 2+ )++ assert found is not None+ text, _sources = found+ # The claim is the RENDERING, not the order: nothing the previous build did not emit.+ assert "111111" in text and "222222" in text+ assert "turn=" not in text+ assert "supersedes" not in text+ assert "oldest first" not in text+++def test_a_ubiquitous_identifier_cannot_crowd_out_the_newest_revision(conn):+ """The conjunctive pass FILTERS; it must not also rank, and must not fill `fetch`.++ FTS5 floors the BM25 IDF of a term present in more than half the index at 1e-6, so in+ an archive that is all about one variable the identifier orders nothing. Cutting that+ pass off at `fetch` therefore dropped the turn stating the current value and answered+ with the four oldest turns instead -- worse than the OR query it replaced.+ """+ for index in range(19):+ _archive(+ _turn(+ f"lets discuss {VARIABLE} aspect number {index}",+ f"{VARIABLE} is a config knob, remark {index} about how {VARIABLE} behaves",+ )+ )+ _archive(_turn(f"please update {VARIABLE}", f"the current value of {VARIABLE} is now 991234"))++ found = conversation_archive.recall(THREAD, f"what is the current value of {VARIABLE}?")++ assert found is not None+ text, _sources = found+ assert "991234" in text+++def test_a_question_about_two_variables_recalls_both_current_values(conn):+ """Two identifiers must not become a requirement to name BOTH.++ The turn that answers "what are A and B now" names one of them; the turns naming both+ are the older comparisons. Requiring the conjunction made every comparison eligible+ and both assignments ineligible, so the four slots went to the four oldest turns and+ neither current value came back -- the same lost answer as the ubiquitous-identifier+ case above, reached through the filter rather than through the ranking.+ """+ other = "ZQXVARB456"+ for index in range(6):+ _archive(+ _turn(+ f"How does {VARIABLE} compare with {other} in scenario {index}?",+ f"In scenario {index}, {VARIABLE} and {other} trade off differently.",+ )+ )+ _archive(_turn(f"please update {VARIABLE}", f"the current value of {VARIABLE} is now 700001"))+ _archive(_turn(f"please update {other}", f"the current value of {other} is now 800002"))++ found = conversation_archive.recall(+ THREAD, f"What is the current value of {VARIABLE} and of {other}?", top_k = 4+ )++ assert found is not None+ text, sources = found+ assert "700001" in text and "800002" in text+ # And the filter still did its job: every slot names something that was asked about.+ assert all(+ VARIABLE.lower() in source["text"].lower() or other.lower() in source["text"].lower()+ for source in sources+ )+++def test_the_newest_revision_survives_a_strict_pass_that_hit_its_cap(conn, monkeypatch):+ """Eligibility is a property of a chunk, not of the capped pass's top rows.++ The identifier pass is bounded at `_BRANCH_FILTER_MAX_CANDIDATES`, and by the same+ IDF floor its order within that bound carries no information. Past the bound the turn+ stating the current value can be the one left out, and reading absence from that list+ as "does not name the subject" ranked it behind every capped row, where the fetch+ window then dropped it. The cap is patched down here so the archive stays small; at+ the shipped 256 the same loss was measured on a 301-chunk archive, which a long+ thread reaches at roughly 60 turns once any of them carry a pasted block+ (CHUNK_TOKENS is 500).+ """+ monkeypatch.setattr(conversation_archive, "_BRANCH_FILTER_MAX_CANDIDATES", 16)+ for index in range(19):+ _archive(+ _turn(+ f"lets discuss {VARIABLE} aspect number {index}",+ f"{VARIABLE} is a config knob, remark {index} about how {VARIABLE} behaves",+ )+ )+ _archive(_turn(f"please update {VARIABLE}", f"the current value of {VARIABLE} is now 991234"))++ found = conversation_archive.recall(THREAD, f"what is the current value of {VARIABLE}?")++ assert found is not None+ assert "991234" in found[0]+++# Ordinary turns of a long engineering chat: each uses the question's content words the+# way a person would and none names the variable, so none can be a correct answer.+# "current" and "value" are plain English, which is the point.+_CONTENT_WORD_TURNS = [+ ("What is the current value of the retry budget?", "Three attempts, by default."),+ ("Is the timeout value still 30 seconds?", "Yes, that is the current setting."),+ ("What value should the batch size take?", "Whatever the current GPU allows."),+ ("Remind me of the current log level.", "Debug, as of the last change."),+ ("Does the cache TTL have a sensible value?", "The current one is an hour."),+ ("What is the current default for max tokens?", "The value is 2048."),+ ("Is that value configurable at runtime?", "Yes, the current build reads it live."),+ ("What is the current branch protection rule?", "One review, no stale value."),+]+++def test_the_ranking_pass_is_widened_until_it_has_eligible_chunks_to_order(conn):+ """The content-word pass ranks the ELIGIBLE chunks, so its window must reach them.++ Fetched at `fetch` it need not reach any: `fetch` ordinary turns using "current" or+ "value" about other things fill it end to end, none of them names the variable, and+ the membership probe -- which only classifies ids already in that window -- then has+ nothing to promote. The merged list falls back to the identifier pass's order, which+ the IDF floor makes uninformative (every turn merely discussing the variable scores+ the same, and the one stating its value scores WORSE, because it names the variable+ once where they name it three times). At 41 turns the assignment ranked 21st of 21+ and the recall answered with the four oldest turns instead.+ """+ for index in range(20):+ _archive(+ _turn(+ f"lets discuss {VARIABLE} aspect number {index}",+ f"{VARIABLE} is a config knob, remark {index} about how {VARIABLE} behaves",+ )+ )+ # A normal-length answer, not a one-liner: length normalisation is what puts it below+ # the short distractors in the content-word pass.+ _archive(+ _turn(+ f"please update {VARIABLE}",+ f"the current value of {VARIABLE} is now 991234. I bumped it after the load test "+ "showed the old setting was too low for the nightly job, so please redeploy the "+ "workers before the next run and keep an eye on the queue depth for the first hour",+ )+ )+ for index in range(20):+ question, answer = _CONTENT_WORD_TURNS[index % len(_CONTENT_WORD_TURNS)]+ _archive(_turn(f"{question} (note {index})", answer))++ found = conversation_archive.recall(THREAD, f"what is the current value of {VARIABLE}?")++ assert found is not None+ text, sources = found+ assert "991234" in text+ # And the filter still holds: no slot goes to a turn that never names the subject.+ assert all(VARIABLE.lower() in source["text"].lower() for source in sources)+++def test_the_archive_query_keeps_the_negation_that_carries_the_question(conn):+ """ "What did I say NOT to delete" is only that question while `not` survives."""+ assert '"not"' in store.conversation_match_queries("What did I say not to delete?")[0]++ _archive(_turn("Please do not delete the staging bucket, ever.", "Understood."))+ for question, answer in (+ ("delete the old build artifacts in dist", "Removed the dist folder."),+ ("can you delete the unused import in main.py", "Import removed."),+ ("delete the stale feature branch", "Branch deleted."),+ ("I want you to delete the temp uploads folder", "Temp uploads cleared."),+ ("delete every log older than a week", "Old logs cleared."),+ ("please delete the duplicated test file", "Duplicate test removed."),+ ("delete the leftover docker volumes", "Volumes pruned."),+ ("delete the commented out block in config", "Block removed."),+ ):+ _archive(_turn(question, answer))++ found = conversation_archive.recall(THREAD, "What did I say not to delete?", top_k = 4)++ assert found is not None+ assert "staging bucket" in found[0]+++def test_re_embedding_a_turn_archived_before_ordinals_leaves_it_unnumbered(conn, monkeypatch):+ """A NULL ordinal predates the column. Allocating one on re-embed would move the+ conversation's OLDEST turn behind every numbered one, and the renderer would then+ read it as the later, superseding statement."""+ from core.rag import embeddings++ 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"])++ oldest = _turn("the pelican turn", "the oldest statement about pelicans")+ assert _archive([dict(message) for message in oldest]) == 1+ scope = store.conversation_archive_scope(THREAD)+ # What an upgraded database looks like: written before the column, never backfilled.+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE scope=?", (scope,))+ conn.commit()+ assert _archive(_turn("newest pelican question", "the newest statement about pelicans")) == 1++ identity["name"] = "st:model-b"+ assert _archive([dict(message) for message in oldest]) == 1++ # By created_at, because the re-embed keeps the turn's original timestamp: the+ # unnumbered turn is still the oldest row in the scope.+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY created_at", (scope,)+ ).fetchall()+ ]+ # 1, not 0: the ordinal is the turn's POSITION, and the newest question is the second+ # turn. The old allocator said 0 by counting from MAX over a column holding one NULL.+ assert ordinals == [None, 1]+ text, _sources = conversation_archive.recall(THREAD, "pelicans", top_k = 4)+ assert text.index("oldest statement") < text.index("newest statement")+++def test_a_re_embed_that_stops_partway_does_not_reorder_a_legacy_archive(conn, monkeypatch):+ """An archive with no ordinals is ordered by `created_at` and by nothing else, so a+ re-embed that re-stamps the rows it reaches puts them AFTER the rows it never got to.++ `archive_turns` is built to survive a pass that dies partway -- it logs, sets+ `_INGEST_FAILED` and leaves whatever it wrote searchable -- and a locked database or+ a full disk is an ordinary way to get there. The turns it managed to rewrite then+ carry the newest timestamps in the scope, so the oldest statements in the+ conversation are quoted LAST, under a header that says the list is oldest first and+ that the later turn supersedes the earlier one. The model is told the first answer+ is the current one.+ """+ from core.rag import embeddings++ 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"])++ turns = [_turn(f"turn {n} about pelicans", f"STATEMENT{n} about pelicans") for n in range(1, 6)]+ history = [dict(message) for turn in turns for message in turn]+ _save_thread(THREAD, history, append = True)+ assert conversation_archive.archive_turns(THREAD, [dict(m) for m in history]) == 5+ scope = store.conversation_archive_scope(THREAD)+ # What an upgraded database looks like: archived before the column, never backfilled.+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE scope=?", (scope,))+ conn.commit()++ # The embedder changes, so the whole archive is rewritten, and the rewrite dies on the+ # third turn.+ identity["name"] = "st:model-b"+ real_add = store.add_chunks+ calls = {"n": 0}++ def add_chunks_until_the_disk_fills(*args, **kwargs):+ calls["n"] += 1+ if calls["n"] == 3:+ raise RuntimeError("database or disk is full")+ return real_add(*args, **kwargs)++ monkeypatch.setattr(store, "add_chunks", add_chunks_until_the_disk_fills)+ conversation_archive.archive_turns(THREAD, [dict(m) for m in history])+ monkeypatch.setattr(store, "add_chunks", real_add)+ # The pass really did stop partway: two rows re-embedded, three left on the old model.+ models = [+ row["embedding_model"]+ for row in conn.execute(+ "SELECT embedding_model FROM documents WHERE scope=? ORDER BY created_at", (scope,)+ ).fetchall()+ ]+ assert sorted(models) == ["st:model-a"] * 3 + ["st:model-b"] * 2++ text, sources = conversation_archive.recall(THREAD, "pelicans", top_k = 5)+ assert "supersedes" in text+ quoted = [source["text"].split("STATEMENT")[1][0] for source in sources]+ assert quoted == ["1", "2", "3", "4", "5"], quoted+++def test_merging_two_recall_queries_still_lists_legacy_turns_first(conn):+ """The merge key has to agree with `_conversation_order`, or the merged block+ contradicts its own "oldest first" header on an upgraded archive."""+ _archive(_turn("the pelican turn", "OLDLEGACY statement about pelicans"))+ _archive(_turn("more pelican talk", "NEWNUMBERED statement about pelicans"))+ scope = store.conversation_archive_scope(THREAD)+ oldest = conn.execute(+ "SELECT id FROM documents WHERE scope=? ORDER BY created_at", (scope,)+ ).fetchone()["id"]+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE id=?", (oldest,))+ conn.commit()++ merged = conversation_archive.recall(THREAD, "pelican", top_k = 4, extra_queries = ["statement"])++ assert merged is not None+ text, _sources = merged+ assert text.index("OLDLEGACY") < text.index("NEWNUMBERED")+++def test_merging_two_recall_queries_keeps_one_turns_chunks_in_order(conn, monkeypatch):+ """Both queries hit the same long turn, so every source carries the same `turn` and a+ stable sort would quote it in query order -- tail first."""+ monkeypatch.setattr(config, "CHUNK_TOKENS", 30)+ monkeypatch.setattr(config, "CHUNK_OVERLAP", 0)+ body = (+ "ALPHAHEAD the opening of the turn "+ + " ".join(f"w{index}" for index in range(25))+ + " OMEGATAIL the closing of the turn "+ + " ".join(f"z{index}" for index in range(25))+ )+ _archive(_turn("a very long turn", body))++ merged = conversation_archive.recall(THREAD, "ALPHAHEAD", top_k = 2, extra_queries = ["OMEGATAIL"])++ assert merged is not None+ text, _sources = merged+ assert text.index("ALPHAHEAD") < text.index("OMEGATAIL")+++def test_merging_two_recall_queries_keeps_legacy_turns_in_the_order_they_were_said(+ tmp_path, monkeypatch+):+ """Every pre-ordinal row has `turn` None, so ordering them only by chunk index leaves+ them in whatever order the two queries happened to return them: the anchor's hits+ first, then the follow-up's. `_conversation_order` breaks exactly this tie with+ `created_at`, and the merged path has to agree with it or the block contradicts its own+ oldest-first header on an upgraded database."""+ from core.rag import conversation_archive++ merged = [+ {"turn": None, "createdAt": "2026-01-02T00:00:00Z", "chunkIndex": 0, "text": "later"},+ {"turn": None, "createdAt": "2026-01-01T00:00:00Z", "chunkIndex": 0, "text": "earlier"},+ {"turn": 3, "createdAt": "2026-01-03T00:00:00Z", "chunkIndex": 0, "text": "numbered"},+ ]+ merged.sort(+ key = lambda source: (+ source.get("turn") is not None,+ source.get("turn") or 0,+ source.get("createdAt") or "",+ source.get("chunkIndex") or 0,+ )+ )++ assert [m["text"] for m in merged] == ["earlier", "later", "numbered"]+++def test_recall_sources_carry_the_fields_the_merge_orders_by():+ """The sort above is only as good as the field it reads, and nothing RENDERS+ `createdAt` or `chunkIndex`, so an unused-looking key is exactly the sort of thing a+ later cleanup deletes. This pins the producer."""+ from types import SimpleNamespace++ from core.rag import tool++ rows = {+ "c1": {+ "document_id": "d1",+ "filename": "chat",+ "text": "hello",+ "archive_ordinal": None,+ "chunk_index": 2,+ "created_at": "2026-01-01T00:00:00Z",+ },+ }+ hits = [SimpleNamespace(chunk_id = "c1", score = 0.5)]++ _, sources = tool.format_conversation_recall(rows, hits)++ assert sources[0]["createdAt"] == "2026-01-01T00:00:00Z"+ assert sources[0]["chunkIndex"] == 2+ assert sources[0]["turn"] is None+++def test_the_newest_revision_survives_a_tied_run_LONGER_than_the_cap(conn):+ """Reordering a window cannot reach a turn that never entered it.++ Every hit on the conversation's own identifier ties at the IDF floor, and SQLite+ returns a fully tied run in rowid order, so the candidate cap took the OLDEST rows.+ Past that many chunks on the subject, the newest assignment was unreachable at any k:+ the ends-first ordering ran inside the cap and could only pick both ends of the window+ it was handed. The existing tie tests patch the cap down instead of exceeding it,+ which is why this went unnoticed.+ """+ count = conversation_archive._BRANCH_FILTER_MAX_CANDIDATES + 40+ for index in range(count - 1):+ _archive(_turn(f"note {index:03d} about ZQXVARA123", "noted"))+ _archive(_turn("set ZQXVARA123 to 9999", "done"))++ found = conversation_archive.recall(THREAD, "what is ZQXVARA123 currently", top_k = 4)++ assert found is not None+ assert "9999" in found[0]+ # The oldest end is still reachable: a fix that just returns the newest turns fails.+ oldest = conversation_archive.recall(THREAD, "what was ZQXVARA123 originally", top_k = 4)+ assert oldest is not None+ assert "note 000" in oldest[0]+++def test_a_re_embedded_oldest_turn_is_still_reachable_past_the_cap(conn, monkeypatch):+ """Both halves have to be ordered by the ordinal, not just the newest one.++ A re-embed deletes and reinserts a chunk while keeping its ordinal, so rowid and+ conversation order diverge. Fetched by rowid, the oldest turn moved to the BACK of the+ front window while the newest-first leg deliberately skips it, and it was in neither+ half: measured, the ordinal-0 chunk's rowid went from 1 to 297 and "note 000" stopped+ being recallable at all.+ """+ from core.rag import embeddings++ 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"])++ oldest_turn = _turn("note 000 about ZQXVARA123", "noted")+ _archive([dict(message) for message in oldest_turn])+ count = conversation_archive._BRANCH_FILTER_MAX_CANDIDATES + 40+ for index in range(1, count - 1):+ _archive(_turn(f"note {index:03d} about ZQXVARA123", "noted"))+ _archive(_turn("set ZQXVARA123 to 9999", "done"))++ # Only the oldest turn is re-embedded, which reinserts its chunk at the newest rowid.+ identity["name"] = "st:model-b"+ _archive([dict(message) for message in oldest_turn])++ oldest = conversation_archive.recall(THREAD, "what was ZQXVARA123 originally", top_k = 4)+ assert oldest is not None+ assert "note 000" in oldest[0]+++def test_the_newest_revision_survives_a_tie_and_the_oldest_one_still_does(conn):+ """A tie in the score is not an order, and truncating it silently picked the past.++ FTS5 floors the IDF of a term that appears in more than half the index at 1e-6, and in+ a per-thread archive the identifier the whole conversation is about is exactly such a+ term. When the revisions share nothing else with the question, every one of them comes+ back with the SAME bm25, so `hits[:limit]` kept whichever rows SQLite happened to emit+ first, which is the oldest. Measured on eight revisions at top_k 4: one distinct score+ across all eight, and the recall returned revisions 1 to 4 with the current value+ absent.++ That is worse than a miss. `format_conversation_recall` tells the model that a later+ turn supersedes an earlier one, so the stale value is handed over as the authoritative+ one.++ Taking from both ends of an equal-score run is what keeps this test and the+ original-assignment guard true at the same time: preferring the newest outright fails+ that guard, which exists precisely to stop a fix that just returns the latest thing it+ can find.+ """+ values = _revisions(8)++ found = conversation_archive.recall(THREAD, f"what is the current value of {VARIABLE}", top_k = 4)++ assert found is not None+ text, _sources = found+ assert values[-1] in text, (+ "the newest revision was dropped by a tie-break that prefers whatever the index "+ "emitted first"+ )+ assert values[0] in text, "the oldest revision must not be dropped either"+++def test_an_overlapping_anchor_query_does_not_shrink_the_recall(conn):+ """Two queries must never return LESS than either of them alone.++ The anchor is a second query drawn from the same thread as the first, so overlap is+ the normal case, not the corner. Each query's slice was cut to its share BEFORE the+ dedup, so every chunk they agreed on consumed a slot and left it empty: measured on+ six turns matching both queries at top_k 4, each query alone returned 4 sources and+ the pair returned 2, with four eligible chunks sitting unread. Adding the anchor+ that exists to RESCUE a thin message made the recall smaller than not adding it.+ """+ for index in range(6):+ _archive(_turn(f"pelican note {index}", f"statement about pelican {index}"))++ alone = conversation_archive.recall(THREAD, "pelican", top_k = 4)+ merged = conversation_archive.recall(THREAD, "pelican", top_k = 4, extra_queries = ["statement"])++ assert alone is not None and merged is not None+ assert len(alone[1]) == 4+ assert (+ len(merged[1]) == 4+ ), f"the anchor cost slots to its overlap with the latest query: {len(merged[1])} of 4"+++def test_a_shouted_question_filters_as_well_as_a_typed_one(conn):+ """Capitals only mean "identifier" where there is lower case to contrast with.++ In a line with no lower case at all the rule fires on every word, so the focused pass+ ORs in "what" and "the" and filters nothing, leaving the permissive BM25 ranking to+ hand the slot to whatever filler shares a content word. Measured on the same fixture+ as `test_the_questions_filler_cannot_outrank_the_subject`, at top_k 1: typed normally+ the slot went to the variable, shouted it went to the retry-budget turn.+ """+ for index in range(6):+ _archive(_turn(f"Set {VARIABLE} to 42{index}.", f"Understood. {VARIABLE} is 42{index}."))+ _archive(+ _turn(+ "What is a good default value for a retry budget?",+ "Three attempts with backoff is a common default value.",+ )+ )+ question = f"What is the current value of {VARIABLE}?"++ assert store.conversation_match_queries(question.upper()) == (+ store.conversation_match_queries(question)+ )+ found = conversation_archive.recall(THREAD, question.upper(), top_k = 1)++ assert found is not None+ assert (+ VARIABLE.lower() in found[0].lower()+ ), "the shouted question filtered nothing and spent its only slot on filler"+++def test_a_numeric_subject_is_still_an_identifier_when_the_question_is_shouted(conn):+ """Making the capitals rule need contrast must not cost numbers their shape.++ A purely numeric subject qualified only through the capitals rule, because "9134"+ upper-cased is itself, and the shape rule demanded a letter as well. So in a shouted+ question it stopped being an identifier altogether, the focused pass was dropped, and+ measured at top_k 1 the slot went to a turn about a retry budget rather than the+ number asked about. Shape is now "contains a digit", which for any ordinary-case+ query is the answer the capitals rule already gave.+ """+ for index in range(6):+ _archive(_turn(f"Set 9134 to 42{index}.", f"Understood. 9134 is 42{index}."))+ _archive(+ _turn(+ "What is a good default value for a retry budget?",+ "Three attempts with backoff is a common default value.",+ )+ )+ question = "What is the current value of 9134?"++ assert store.conversation_match_queries(question)[0] == '"9134"'+ assert store.conversation_match_queries(question.upper())[0] == '"9134"'+ found = conversation_archive.recall(THREAD, question.upper(), top_k = 1)++ assert found is not None+ assert "9134" in found[0]+++def test_turning_the_query_focus_off_restores_the_old_order_on_a_tied_archive(conn, monkeypatch):+ """The rollback knob says the candidate set is identical to before, so it must be.++ The tie-break reorders CANDIDATES, which is selection, not presentation, so leaving it+ outside the knob meant an operator who turned the feature off still got the new+ behaviour out of an archive whose scores are tied. Measured before this gate: the+ knobs-off recall returned the both-ends set rather than the four the previous build+ returned.+ """+ from core.rag import config++ monkeypatch.setattr(config, "CONVERSATION_QUERY_FOCUS", False)+ monkeypatch.setattr(config, "CONVERSATION_RECALL_ORDER", "relevance")+ values = _revisions(8, distractors = 0)++ found = conversation_archive.recall(THREAD, f"what is the current value of {VARIABLE}", top_k = 4)++ assert found is not None+ returned = [value for value in values if value in found[0]]+ assert returned == values[:4], f"the knob did not restore the previous selection: {returned}"+++def test_a_turn_repeated_later_is_archived_again_at_its_own_position(conn):+ """Saying the same thing twice is two turns, and the second one is usually the point.++ The archive is idempotent by content hash, which is what makes re-archiving an+ eviction free, but hash alone treated a genuine repeat as a duplicate: "set X to 1",+ "set X to 2", "set X to 1" stored TWO documents for three turns, and the third turn,+ the one holding the current value, was never indexed at all, so no query could reach+ it. The recall then quoted turns 1 and 2 under a header stating that the higher turn+ number was said later and supersedes the earlier one, which told the model X was 2.+ """+ written = [+ _archive(_turn("set ZQXVARA123 to 1", "ok")),+ _archive(_turn("set ZQXVARA123 to 2", "ok")),+ _archive(_turn("set ZQXVARA123 to 1", "ok")),+ ]++ assert written == [1, 1, 1]+ scope = store.conversation_archive_scope(THREAD)+ assert len(store.list_documents(conn, scope)) == 3+ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ turns = [source.get("turn") for source in found[1]]+ # Rendered oldest first with the repeat LAST, which makes the header's rule true.+ assert turns == sorted(turns)+ assert "set ZQXVARA123 to 1" in found[1][-1]["text"]+++def test_a_repeat_still_in_the_prompt_is_not_archived_early(conn):+ """A turn said twice with only the older one evicted is ONE archived turn, for now.++ Seats come from the persisted transcript, so both occurrences count, and the same+ evicted group is handed back on every later request while the sticky boundary holds.+ The second pass then saw one stored copy against two seats, decided it was short, and+ wrote a document for the occurrence still sitting in the prompt. Both were recallable,+ so identical text took two of the four recall slots and one of them repeated what the+ model could already read.++ Bounded by what the fit KEPT instead. The copy is written when its own turn is+ evicted, at its own ordinal, which is the second half of this test.+ """+ repeat = _turn("set ZQXVARA123 to 1", "ok")+ middle = _turn("tell me about ZQXVARA123 pelicans", "sure")+ tail = _turn("and now something else about ZQXVARA123", "fine")+ conversation = repeat + middle + list(repeat) + tail+ _save_thread(THREAD, conversation)++ # Only the OLDEST copy has crossed the boundary; the newer one is still in the prompt.+ live = list(repeat) + tail+ conversation_archive.archive_turns(THREAD, repeat, live = live)+ conversation_archive.archive_turns(THREAD, repeat, live = live)++ scope = store.conversation_archive_scope(THREAD)+ assert len(store.list_documents(conn, scope)) == 1++ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ texts = [source["text"] for source in found[1]]+ assert len(texts) == len(set(texts))++ # Once the newer copy is evicted too, it is archived at the position it was said.+ conversation_archive.archive_turns(THREAD, conversation[:6], live = tail)+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),+ ).fetchall()+ ]+ assert ordinals == [0, 1, 2]+++def test_a_re_embed_does_not_swallow_a_repeat_evicted_later(conn, monkeypatch):+ """A REPLACEMENT is not an addition, and the two used to be confused.++ When the embedder identity changes between the first copy of a repeated turn being+ archived and the second occurrence being evicted, the re-embed branch swaps that one+ copy's vectors and keeps the count where it was, so the newly evicted occurrence was+ never written. With a contradicting turn in between, the chronological block then+ presents the contradiction as the conversation's last word, on the very response the+ eviction triggered.+ """+ from core.rag import embeddings++ 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"])++ repeat = _turn("set ZQXVARA123 to 1", "ok")+ middle = _turn("set ZQXVARA123 to 2", "ok")+ tail = _turn("and now something else about ZQXVARA123", "fine")+ conversation = repeat + middle + list(repeat) + tail+ _save_thread(THREAD, conversation)++ # The first copy and the contradiction are evicted while the repeat is still live.+ live = list(repeat) + tail+ conversation_archive.archive_turns(THREAD, repeat + middle, live = live)++ # The embedder changes, and only then is the repeat evicted. Handed over ALONE, as four+ # of the five call sites do: they pass the already-fitted list.+ identity["name"] = "st:model-b"+ conversation_archive.archive_turns(THREAD, list(repeat), live = tail)++ scope = store.conversation_archive_scope(THREAD)+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),+ ).fetchall()+ ]+ assert ordinals == [0, 1, 2]++ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ # The last word on the identifier is 1, rendered last under the supersedes header.+ assert "set ZQXVARA123 to 1" in found[1][-1]["text"]+++def test_two_evicted_copies_of_a_thrice_said_turn_are_both_archived(conn):+ """A set of live texts cannot count. Three identical turns with two evicted and one+ still in the prompt looked entirely live, so only one copy was ever written and the+ archive was a turn short of what was actually said."""+ repeat = _turn("set ZQXVARA123 to 1", "ok")+ mid = _turn("set ZQXVARA123 to 2", "ok")+ other = _turn("something else about ZQXVARA123", "fine")+ conversation = repeat + mid + list(repeat) + other + list(repeat)+ _save_thread(THREAD, conversation)++ # The last occurrence and `other` are still in the prompt; the first two are not.+ live = other + list(repeat)+ conversation_archive.archive_turns(THREAD, repeat + mid + list(repeat), live = live)++ scope = store.conversation_archive_scope(THREAD)+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),+ ).fetchall()+ ]+ assert ordinals == [0, 1, 2]+++def test_a_rewound_repeat_moves_the_survivor_to_the_seat_it_still_has(conn, monkeypatch):+ """Retiring a copy without restamping leaves the survivor on a seat that is gone.++ Identical turns at ordinals 0 and 2 with the FIRST rewound away left the survivor on+ 0, so a contradiction at 1 rendered after it and the header, which says the higher+ turn number was said later and supersedes, handed the model the superseded value.+ """+ from core.rag import embeddings++ 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"])++ repeat = _turn("set ZQXVARA123 to 1", "ok")+ mid = _turn("set ZQXVARA123 to 2", "ok")+ whole = repeat + mid + list(repeat)+ _save_thread(THREAD, whole)+ conversation_archive.archive_turns(THREAD, whole, live = [])++ # The user rewinds away the FIRST occurrence, and the embedder changes.+ _save_thread(THREAD, mid + list(repeat))+ identity["name"] = "st:model-b"+ conversation_archive.archive_turns(THREAD, mid + list(repeat), live = [])++ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ # Rendered oldest first, so the conversation's last word has to come last.+ assert found[0].index("set ZQXVARA123 to 2") < found[0].rindex("set ZQXVARA123 to 1")+++def test_the_write_budget_is_every_seat_when_the_caller_says_nothing(conn):+ """`live` is optional, and without it the budget is the old count. Direct callers+ (every other test here, and any caller outside the fit) must not change behaviour."""+ from core.rag import conversation_archive as archive++ group = [{"role": "user", "content": "a"}]+ one_live = [{"role": "user", "content": "a"}]++ assert archive._write_budget([["a"], ["a"]], [0, 1], None, group) == 2+ assert (+ archive._write_budget([["a"], ["a"]], [0, 1], archive._live_positions(one_live), group) == 1+ )+ assert archive._write_budget([["a"], ["a"]], [], archive._live_positions(one_live), group) == 1+ # Live occurrences are COUNTED, not tested for membership: three seats with one copy+ # still in the prompt owe two writes, not one.+ assert (+ archive._write_budget(+ [["a"], ["a"], ["a"]], [0, 1, 2], archive._live_positions(one_live), group+ )+ == 2+ )+++def test_an_out_of_order_eviction_still_numbers_turns_in_conversation_order(conn):+ """Eviction is not strictly oldest-first, so archive time is not conversation order.++ `truncate_oldest_messages` always protects the newest user group, and a pinned+ instruction is held until it stops being pinned, so a LATER turn is routinely archived+ before an EARLIER one. Numbering by arrival recorded the oldest turn as the newest,+ and `format_conversation_recall` says outright that the higher number was said later+ and supersedes the earlier one, so the block asserted the reverse of what happened.+ """+ conversation = (+ _turn("the standing instruction about pelicans", "Understood.")+ + _turn("the middle turn about pelicans", "Noted.")+ + _turn("the final turn about pelicans", "Noted again.")+ )+ _save_thread(THREAD, conversation)++ # Archived out of order: the later turns first, the instruction only afterwards.+ conversation_archive.archive_turns(THREAD, conversation[2:6])+ conversation_archive.archive_turns(THREAD, conversation[0:2])++ scope = store.conversation_archive_scope(THREAD)+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),+ ).fetchall()+ ]+ assert ordinals == [0, 1, 2]+ found = conversation_archive.recall(THREAD, "pelicans", top_k = 4)+ assert found is not None+ text = found[0]+ assert text.index("standing instruction") < text.index("middle turn") < text.index("final turn")+++def test_two_turns_that_start_the_same_do_not_take_each_others_places(conn):+ """A turn is matched by the whole turn, not by the line it opens with.++ Repeated "continue" prompts, the same question re-asked, a regenerated reply: all of+ them produce two DIFFERENT turns sharing a first message. Matched on the head alone+ both claimed both seats, so both were stamped with the same ordinal, and because each+ then believed it had a second occurrence still to fill, the next compaction wrote both+ of them again. Measured: 4 documents for 2 turns, the recall spending four slots on+ two turns' content, and the older answer quoted under the higher turn number, which+ the header presents to the model as the one that supersedes.+ """+ first = _turn("continue ZQXVARA123", "the first continuation, about ducks")+ second = _turn("continue ZQXVARA123", "the second continuation, about geese")++ written = [_archive(first), _archive(second)]+ scope = store.conversation_archive_scope(THREAD)+ ordinals = sorted(+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ )+ # And re-evicting the same two turns stays free.+ again = [_archive(first, persist = False), _archive(second, persist = False)]++ assert written == [1, 1]+ assert ordinals == [0, 1]+ assert again == [0, 0]+ assert len(store.list_documents(conn, scope)) == 2+++def test_an_archive_numbered_by_the_old_allocator_converges_on_the_next_compaction(conn):+ """The migration has to actually run, and it ran on a path that could not be reached.++ The cheap pre-check ahead of the embedding pass fires on exactly the condition the+ write-locked branch does, so re-stamping only in the latter was dead code outside a+ race. Measured before this: an archive forced back to NULL ordinals still read+ NULL, NULL after a full re-compaction, and one forced into archive-time order 1, 0+ stayed 1, 0, with the recall rendering the second turn first under a header saying the+ higher number supersedes.+ """+ conversation = _turn("alpha about pelicans", "first") + _turn("beta about pelicans", "second")+ _save_thread(THREAD, conversation)+ conversation_archive.archive_turns(THREAD, conversation)+ scope = store.conversation_archive_scope(THREAD)++ def ordinals():+ return [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY created_at",+ (scope,),+ ).fetchall()+ ]++ assert ordinals() == [0, 1]++ # An archive written before the column existed.+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE scope=?", (scope,))+ conn.commit()+ conversation_archive.archive_turns(THREAD, conversation)+ assert ordinals() == [0, 1]++ # And one numbered in the order the turns happened to be archived.+ conn.execute(+ "UPDATE documents SET archive_ordinal=(CASE WHEN archive_ordinal=0 THEN 1 ELSE 0 END) "+ "WHERE scope=?",+ (scope,),+ )+ conn.commit()+ conversation_archive.archive_turns(THREAD, conversation)+ assert ordinals() == [0, 1]+ text, _sources = conversation_archive.recall(THREAD, "pelicans", top_k = 4)+ assert text.index("alpha") < text.index("beta")+++def _persist_agent_thread():+ """A thread whose newest turn is a tool exchange, stored the way the UI stores one."""+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ rows = [+ ("user", [{"type": "text", "text": "what is the capital of peru"}]),+ ("assistant", [{"type": "text", "text": "Lima."}]),+ ("user", [{"type": "text", "text": "list the files in the repo"}]),+ (+ "assistant",+ [+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "args": {"command": "ls"},+ "result": "main.py readme.md",+ },+ {"type": "text", "text": "the repo has two files."},+ ],+ ),+ ]+ for index, (role, content) in enumerate(rows):+ studio_db.upsert_chat_message(+ {+ "id": f"{THREAD}-{index}",+ "threadId": THREAD,+ "role": role,+ "content": content,+ "createdAt": index + 2,+ }+ )+ return [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"command": "ls"}'}}+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "main.py readme.md"},+ {"role": "assistant", "content": "the repo has two files."},+ ]+++def test_an_archived_tool_exchange_is_still_reachable_by_a_query(conn):+ """The persisted shape of a tool call is not the wire shape, and both readers assumed it was.++ The store keeps a call as one `tool-call` content PART carrying its result, while the+ request carries three messages: the call, the result, the reply. `_probe_text` renders+ the stored row as call/reply/result and the archived copy as call/result/reply, and+ the branch check matches IN ORDER, so every archived agent turn failed it. Measured:+ the exchange was indexed and then filtered out of every recall, so no query could+ return it. That is archived content the model can never get back, on every tool-using+ turn.+ """+ tool_turn = _persist_agent_thread()+ conversation_archive.archive_turns(THREAD, tool_turn)++ found = conversation_archive.recall(THREAD, "terminal ls repo files", top_k = 4)++ assert found is not None+ assert any("terminal" in source["text"] for source in found[1])+++def test_a_tool_exchange_is_numbered_where_the_conversation_put_it(conn):+ """`group_turns` splits on tool_calls, which a persisted row never carries.++ So the whole exchange folded into the preceding user group, the evicted tool group+ found no seat of its own, and it fell back to MAX + 1 -- the same number its own+ opening question takes from the transcript. Measured: two documents at ordinal 1, with+ created_at breaking the tie in favour of the ANSWER, under a header telling the model+ the later turn supersedes.+ """+ tool_turn = _persist_agent_thread()+ # The order eviction really produces: the oldest turn, then the tool groups, then the+ # user turn that opened them once it stops being the newest.+ conversation_archive.archive_turns(+ THREAD,+ [+ {"role": "user", "content": "what is the capital of peru"},+ {"role": "assistant", "content": "Lima."},+ ],+ )+ conversation_archive.archive_turns(THREAD, tool_turn)+ conversation_archive.archive_turns(+ THREAD,+ [+ {"role": "user", "content": "list the files in the repo"},+ ],+ )++ scope = store.conversation_archive_scope(THREAD)+ ordinals = [+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=? ORDER BY archive_ordinal",+ (scope,),+ ).fetchall()+ ]++ assert ordinals == [0, 1, 2]+ text, _sources = conversation_archive.recall(THREAD, "repo files peru ls", top_k = 4)+ assert text.index("capital of peru") < text.index("list the files")+ assert text.index("list the files") < text.index("called terminal")+++def test_an_anchor_query_cannot_cost_the_newest_revision_its_slot(conn):+ """The refill has to keep RETRIEVAL rank, which the chronological sort throws away.++ Every candidate in a tied archive carries the same score, and the score a source+ carries is rounded for display on top of that, so sorting the refill by score alone+ left the list in the order it arrived: chronological. The refill then spent its slots+ on the oldest turns, and adding the anchor that exists to rescue a thin message made+ the recall worse than not adding it. Measured on eight revisions at top_k 4: the single+ query returned the newest, the same query plus an anchor did not.+ """+ values = _revisions(8, distractors = 0)++ alone = conversation_archive.recall(THREAD, f"{VARIABLE}", top_k = 4)+ merged = conversation_archive.recall(THREAD, f"{VARIABLE}", top_k = 4, extra_queries = ["timeout"])++ assert alone is not None and merged is not None+ assert values[-1] in alone[0]+ assert values[-1] in merged[0], "the anchor cost the newest revision its slot"+++def test_an_orphan_user_row_does_not_lend_its_seat_to_a_later_turn(conn):+ """A position SHORTER than the turn may only match the trailing one.++ `zip` stops at the shorter side, so a persisted turn missing its reply prefix-matched+ anywhere in the transcript. A thread carrying an orphan user row -- an assistant reply+ deleted from the thread, or a reload before the reply was appended -- therefore handed+ the later, answered turn two seats, and the next compaction wrote a second copy of it.+ Measured: seats [0, 1] where only [1] is real, two documents with one sha, and the+ recall quoting the same turn twice.+ """+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ rows = [+ ("user", "set ZQXVARA123 to 1"), # orphan: its reply is gone+ ("user", "set ZQXVARA123 to 1"),+ ("assistant", "done, ZQXVARA123 is 1"),+ ]+ for index, (role, text) in enumerate(rows):+ studio_db.upsert_chat_message(+ {+ "id": f"{THREAD}-{index}",+ "threadId": THREAD,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": index + 2,+ }+ )+ answered = [+ {"role": "user", "content": "set ZQXVARA123 to 1"},+ {"role": "assistant", "content": "done, ZQXVARA123 is 1"},+ ]++ positions = conversation_archive._transcript_positions(THREAD)+ assert conversation_archive._occurrences(positions, answered) == [1]++ written = [+ conversation_archive.archive_turns(THREAD, answered),+ conversation_archive.archive_turns(THREAD, answered),+ ]+ scope = store.conversation_archive_scope(THREAD)++ assert written == [1, 0]+ assert len(store.list_documents(conn, scope)) == 1+++def test_a_retried_turn_is_numbered_on_the_branch_the_user_is_on(conn):+ """The stored rows are a tree, and reading them as a list numbers an abandoned sibling.++ Retry leaves the replaced reply in place, so a flat read drops it between two live+ turns and the grouper glues it onto whichever turn precedes it. The regenerated turn+ then matches no position and takes MAX + 1, which the cumulative archive has already+ pushed past every live turn: measured, a regenerated turn 2 came back numbered 5 out of+ 4 live turns, colliding with live turn 3 under the header that says the higher number+ supersedes.+ """+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ rows = [+ ("m0", None, "user", "turn 1 about ZQXVARA123"),+ ("m1", "m0", "assistant", "answer 1"),+ ("m2", "m1", "user", "turn 2 about ZQXVARA123"),+ ("m3", "m2", "assistant", "answer 2 attempt one"), # abandoned sibling+ ("m4", "m2", "assistant", "answer 2 attempt two"), # the live reply+ ("m5", "m4", "user", "turn 3 about ZQXVARA123"),+ ("m6", "m5", "assistant", "answer 3"),+ ]+ for index, (identifier, parent, role, text) in enumerate(rows):+ studio_db.upsert_chat_message(+ {+ "id": identifier,+ "threadId": THREAD,+ "parentId": parent,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": index + 2,+ }+ )++ live = [+ {"role": "user", "content": "turn 1 about ZQXVARA123"},+ {"role": "assistant", "content": "answer 1"},+ {"role": "user", "content": "turn 2 about ZQXVARA123"},+ {"role": "assistant", "content": "answer 2 attempt two"},+ {"role": "user", "content": "turn 3 about ZQXVARA123"},+ {"role": "assistant", "content": "answer 3"},+ ]+ positions = conversation_archive._transcript_positions(THREAD)++ assert len(positions) == 3, positions+ assert conversation_archive._occurrences(positions, live[2:4]) == [1]++ conversation_archive.archive_turns(THREAD, live)+ scope = store.conversation_archive_scope(THREAD)+ ordinals = sorted(+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ )+ assert ordinals == [0, 1, 2]+++def test_a_rewind_retires_the_copy_the_conversation_no_longer_holds(conn):+ """A repeat that is rewound away leaves more copies than occurrences.++ Both copies are byte-identical, so the branch filter validates each against the single+ surviving occurrence and `recall` dedups on chunk id, which differs. Measured: a recall+ slot went on quoting one turn twice, and the surplus kept an ordinal that a genuinely+ later turn had since taken.+ """+ first = _turn("set ZQXVARA123 to 1", "ok")+ second = _turn("set ZQXVARA123 to 2", "ok")+ repeat = _turn("set ZQXVARA123 to 1", "ok")+ for group in (first, second, repeat):+ _archive(group)+ scope = store.conversation_archive_scope(THREAD)+ assert len(store.list_documents(conn, scope)) == 3++ # Rewind past the repeat, through the same sync the PUT route uses.+ _save_thread(THREAD, first + second)+ conversation_archive.archive_turns(THREAD, first)++ ordinals = sorted(+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ )+ assert ordinals == [0, 1]+ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ assert len(found[1]) == len({source["text"] for source in found[1]})+++def test_an_incidental_number_does_not_take_over_the_filter(conn):+ """A bare number needs length to be a name, which is the bar the capitals rule had.++ Treating any digit-bearing token as an identifier made "answer in 2 sentences" filter+ the archive on "2". Measured on an archive whose filler mentions small numbers in+ ordinary prose, at top_k 1, the focused pass returned the staging-environments turn+ where both the previous build and the rollback knob returned the billing turn.+ """+ assert store.conversation_match_queries("answer in 2 sentences") == [+ '"answer" OR "2" OR "sentences"'+ ]+ assert store.conversation_match_queries("which python, 3.11 or 3.12") == [+ '"python" OR "3" OR "11" OR "12"'+ ]+ # A name is still a name, at any length, and a long number still qualifies.+ assert store.conversation_match_queries("what about v2 of the plan")[0] == '"v2"'+ assert store.conversation_match_queries("we talked about 2024 revenue")[0] == '"2024"'+ assert store.conversation_match_queries("What is the current value of 9134?")[0] == '"9134"'+++def test_a_re_embed_after_a_rewind_retires_the_surplus_copy_too(conn, monkeypatch):+ """The re-embed path never reaches the branch where surplus copies are retired.++ A repeated turn archived twice and then rewound leaves one copy more than the+ conversation holds. Replacing one copy's vectors under a new embedder writes a fresh+ document and returns, so the surplus is never looked at: measured, three documents for+ two turns after the rewind, with the recall quoting the repeated turn twice and the+ surplus still holding a position a later turn had taken.+ """+ from core.rag import embeddings++ 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"])++ first = _turn("set ZQXVARA123 to 1", "ok")+ second = _turn("set ZQXVARA123 to 2", "ok")+ repeat = _turn("set ZQXVARA123 to 1", "ok")+ for group in (first, second, repeat):+ _archive(group)+ scope = store.conversation_archive_scope(THREAD)+ assert len(store.list_documents(conn, scope)) == 3++ # Rewind past the repeat, and the embedder changes underneath the thread.+ _save_thread(THREAD, first + second)+ identity["name"] = "st:model-b"+ conversation_archive.archive_turns(THREAD, first)++ ordinals = sorted(+ row["archive_ordinal"]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ )+ assert ordinals == [0, 1]+ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ assert len(found[1]) == len({source["text"] for source in found[1]})+++def test_text_said_before_a_tool_call_rides_on_the_call_message():+ """A persisted assistant row holds the whole turn, in generation order.++ Text BEFORE the first `tool-call` part is what the model said on its way to calling,+ and the live wire form carries that on the call message itself. Emitting it after the+ synthesized results instead gave the archived copy three messages reading+ call/result/text against the live two reading call+text/result, so `_occurrences`+ matched nothing and the turn took a fallback ordinal. Text AFTER the calls is the+ reply that followed the result and still belongs last, which is why this splits by+ POSITION and not by part type.+ """+ call = {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "args": {"command": "ls"},+ "result": "main.py readme.md",+ }+ before = conversation_archive._as_wire(+ [{"role": "assistant", "content": [{"type": "text", "text": "Let me check."}, call]}]+ )+ after = conversation_archive._as_wire(+ [{"role": "assistant", "content": [call, {"type": "text", "text": "Two files."}]}]+ )++ assert [message["role"] for message in before] == ["assistant", "tool"]+ assert "Let me check." in conversation_archive._normalise(+ conversation_archive._probe_text(before[0])+ )+ assert [message["role"] for message in after] == ["assistant", "tool", "assistant"]+ assert (+ conversation_archive._normalise(conversation_archive._probe_text(after[2])) == "Two files."+ )+++def test_turns_differing_only_in_case_do_not_share_a_seat(conn):+ """`Set key Foo` and `Set key FOO` hash differently, so each keeps its own document.++ Folding case when matching the transcript handed BOTH seats to BOTH of them, and a+ turn that believes it has two occurrences to fill is written twice at the next+ compaction: four documents for two turns, each stamped at both ordinals, and no way+ to tell which spelling was said later.+ """+ lower = _turn("set key Foo", "done")+ upper = _turn("set key FOO", "done")+ _save_thread(THREAD, lower + upper)++ positions = conversation_archive._transcript_positions(THREAD)+ assert conversation_archive._occurrences(positions, lower) == [0]+ assert conversation_archive._occurrences(positions, upper) == [1]+++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 _branch_switch_thread():+ """Branch A, a later sibling branch B, and the user back on A. Returns A's messages."""+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ rows = [+ ("m0", None, "user", "turn 1 about ZQXVARA123", 2),+ ("m1", "m0", "assistant", "answer 1", 3),+ ("m2", "m1", "user", "turn 2 on A about ZQXVARA123", 4),+ ("m3", "m2", "assistant", "answer 2 on A", 5),+ ("m4", "m3", "user", "turn 3 on A about ZQXVARA123", 6),+ ("m5", "m4", "assistant", "answer 3 on A", 7),+ # The user rewinds to m1 and continues on branch B, so B's rows are the newest in+ # the thread. Then the branch picker takes them back to A.+ ("m6", "m1", "user", "turn 2 on B about ZQXVARA123", 8),+ ("m7", "m6", "assistant", "answer 2 on B", 9),+ ]+ for identifier, parent, role, text, created in rows:+ studio_db.upsert_chat_message(+ {+ "id": identifier,+ "threadId": THREAD,+ "parentId": parent,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": created,+ }+ )+ return [+ {"role": "user", "content": "turn 1 about ZQXVARA123"},+ {"role": "assistant", "content": "answer 1"},+ {"role": "user", "content": "turn 2 on A about ZQXVARA123"},+ {"role": "assistant", "content": "answer 2 on A"},+ {"role": "user", "content": "turn 3 on A about ZQXVARA123"},+ {"role": "assistant", "content": "answer 3 on A"},+ ]+++def test_positions_follow_the_request_branch_not_the_newest_stored_row(conn):+ """The newest stored row is not the branch the request is on.++ Switching to a sibling branch, continuing there, and then switching BACK leaves the+ abandoned branch holding the greatest created_at. Seeding the ancestry walk from the+ last stored row therefore read the branch the user had left: turns being evicted from+ the request's own branch matched no position, took MAX + 1 over a cumulative archive+ the other branch had already pushed up, and `format_conversation_recall` presented an+ older statement as the one that supersedes.+ """+ live = _branch_switch_thread()++ positions = conversation_archive._transcript_positions(THREAD, branch = live)++ assert len(positions) == 3, positions+ assert conversation_archive._occurrences(positions, live[2:4]) == [1]+ assert conversation_archive._occurrences(positions, live[4:6]) == [2]+++def test_the_branch_seed_falls_back_when_nothing_matches(conn):+ """No branch, or a branch that matches nothing, has to leave today's behaviour alone.++ An API-only caller passes none, and a zero-match seed must not collapse `positions`:+ an empty chain empties every seat and sends every turn to MAX + 1, which is strictly+ worse than reading the newest row.+ """+ _branch_switch_thread()++ seeded = conversation_archive._transcript_positions(THREAD)+ unmatched = conversation_archive._transcript_positions(+ THREAD, branch = [{"role": "user", "content": "nothing in this thread says this"}]+ )++ # Branch B is the newest stored row, so both fall back to it: two turns, not three.+ assert len(seeded) == 2, seeded+ assert unmatched == seeded+++def test_two_sequential_tool_rounds_replay_as_two_exchanges():+ """One persisted row can hold a whole agent turn, rounds and all.++ `chat-adapter.ts` flushes the pending calls whenever text arrives, so a row reading+ call, text, call goes out as call/result, then text riding on the second call+ message, then its result. Collecting every call into one message and appending every+ result after it rebuilt a different order: `group_turns` glued exchanges that were+ separate on the wire, and the later calls matched no position and took an invented+ ordinal.+ """++ def _call(index, command, result):+ return {+ "type": "tool-call",+ "toolCallId": f"c{index}",+ "toolName": "terminal",+ "args": {"command": command},+ "result": result,+ }++ wire = conversation_archive._as_wire(+ [+ {+ "role": "assistant",+ "content": [+ _call(1, "ls", "a.py"),+ {"type": "text", "text": "Now the tests."},+ _call(2, "pytest", "2 passed"),+ {"type": "text", "text": "All green."},+ ],+ }+ ]+ )++ assert [message["role"] for message in wire] == [+ "assistant",+ "tool",+ "assistant",+ "tool",+ "assistant",+ ]+ assert [message.get("tool_call_id") for message in wire if message["role"] == "tool"] == [+ "c1",+ "c2",+ ]+ # The text before the second call rides ON it, exactly as the flush builds it.+ second = conversation_archive._normalise(conversation_archive._probe_text(wire[2]))+ assert "pytest" in second and "Now the tests." in second+ assert (+ conversation_archive._normalise(conversation_archive._probe_text(wire[4])) == "All green."+ )+++def test_an_in_flight_tool_group_does_not_take_the_live_user_turn_s_number(conn):+ """Seats count TRANSCRIPT positions; the archive counter counts what was archived.++ The newest user group is protected from eviction, so during a long tool loop it sits+ in the transcript and not in the archive. A tool group evicted before its assistant+ row is persisted matches no seat and took the archive's next number, which the user+ turn later claimed from the transcript: both documents landed on the same ordinal,+ and since created_at breaks the tie the tool answer rendered ahead of the prompt that+ caused it, under the header saying a higher number was said later.+ """+ user_turn = _turn("run the deploy", "deploying now")+ _save_thread(THREAD, user_turn, append = True)++ in_flight = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"command": "deploy"}'}}+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "deploy failed: port in use"},+ ]+ conversation_archive.archive_turns(THREAD, in_flight)+ conversation_archive.archive_turns(THREAD, user_turn)++ scope = store.conversation_archive_scope(THREAD)+ numbered = {+ row["filename"]: row["archive_ordinal"]+ for row in conn.execute(+ "SELECT filename, archive_ordinal FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ }++ assert len(set(numbered.values())) == len(numbered), numbered+ assert numbered["earlier turn (user + assistant)"] < numbered["earlier turn (assistant + tool)"]+++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_an_empty_tool_result_still_produces_a_tool_message():+ """Only an ABSENT result is absent.++ `serializeToolResultPart` skips exactly `undefined` and `null`, and emits a `tool`+ message for everything else: a `{"result": ""}` sentinel for an empty string, since+ the ChatMessage validator rejects an empty `tool` content, and JSON for containers.+ Treating "" / {} / [] as nothing dropped a message the wire carries, so the+ reconstructed run was shorter than the archived one and branch validation could filter+ the turn out of every recall.+ """++ def _row(result, *, present = True):+ call = {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "args": {"command": "true"},+ }+ if present:+ call["result"] = result+ return [{"role": "assistant", "content": [call]}]++ emitted = {+ result: [+ message["content"]+ for message in conversation_archive._as_wire(_row(result))+ if message["role"] == "tool"+ ]+ for result in ("", "ok")+ }+ # Byte for byte what `JSON.stringify({ result: "" })` produces: no space after the+ # colon, which `json.dumps` adds, and every comparison downstream is exact.+ assert emitted[""] == ['{"result":""}']+ assert emitted["ok"] == ["ok"]++ for container, expected in (({}, "{}"), ([], "[]"), ({"a": 1}, '{"a":1}')):+ wire = conversation_archive._as_wire(_row(container))+ assert [message["content"] for message in wire if message["role"] == "tool"] == [expected]++ # A result that is genuinely not there stays not there, matching the serializer.+ for row in (_row(None), _row(None, present = False)):+ assert [+ message for message in conversation_archive._as_wire(row) if message["role"] == "tool"+ ] == []++ # And the reconstructed row matches the document archived from the request, which is+ # the point: emitting the message and still failing the match only looks fixed.+ wire = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"command":"true"}'}}+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "content": '{"result":""}'},+ ]+ rendered = conversation_archive.render_turn(wire)+ document = rendered[1] if isinstance(rendered, tuple) else rendered+ reconstructed = conversation_archive.branch_message_texts(+ conversation_archive._as_wire(_row(""))+ )++ assert conversation_archive._on_live_branch(document, reconstructed) is True+++def test_a_bare_identifier_query_also_reaches_past_the_cap(conn):+ """A query that is ONLY an identifier shapes to ONE expression.++ Its focused and permissive spellings coincide, and the single-expression path returned+ the plain one-ended fetch, so the query most likely to tie on the IDF floor got the+ oldest rows and the newest assignment was never a candidate. The two-expression case+ was already covered, which is why this went unnoticed.+ """+ count = conversation_archive._BRANCH_FILTER_MAX_CANDIDATES + 40+ for index in range(count - 1):+ _archive(_turn(f"note {index:03d} about ZQXVARA123", "noted"))+ _archive(_turn("set ZQXVARA123 to 9999", "done"))++ assert len(store.conversation_match_queries("ZQXVARA123")) == 1+ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)++ assert found is not None+ assert "9999" in found[0]+ # The oldest end stays reachable, the invariant the ends-first ordering exists for.+ assert "note 000" in conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 256)[0]+++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_provider_side_builtin_is_replayed_the_way_the_frontend_replays_it():+ """The frontend drops a builtin card from the history it sends.++ A `web_search` card with the server marker and no native part is omitted entirely,+ call and result, and one WITH a native part replays as a call carrying no `tool`+ message, since its result travels in the provider's own part. Reconstructing either as+ an ordinary local call inserted an exchange the request never carried, so the turn+ matched nothing and took a fallback ordinal.+ """+ marked = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "s1",+ "toolName": "web_search",+ "args": {"query": "ZQX rate", "_server_tool": True},+ "result": "search hits",+ },+ {"type": "text", "text": "The ZQX rate is 5150."},+ ],+ }+ ]+ native = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "s2",+ "toolName": "code_execution",+ "args": {"google": {"native_part": {"code": "print(1)"}}},+ "result": "1",+ },+ {"type": "text", "text": "Done."},+ ],+ }+ ]+ # A USER function that merely shares the name is untouched: the name never decides.+ homonym = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "u1",+ "toolName": "web_search",+ "args": {"query": "ZQX rate"},+ "result": "hits",+ }+ ],+ }+ ]++ assert [m["role"] for m in conversation_archive._as_wire(marked)] == ["assistant"]+ assert [m["role"] for m in conversation_archive._as_wire(native)] == [+ "assistant",+ "assistant",+ ]+ assert [m["role"] for m in conversation_archive._as_wire(homonym)] == ["assistant", "tool"]+++def test_a_sandbox_result_is_replayed_as_the_text_the_model_saw():+ """`python` and `terminal` results are wrapped on every call.++ The replay adapter sends `result.text` alone rather than feeding the model a session+ id and file metadata, so serialising the whole wrapper reconstructed a tool message+ that can never equal the archived one.+ """++ def _row(tool_name, result):+ return [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": tool_name,+ "args": {"command": "ls"},+ "result": result,+ }+ ],+ }+ ]++ def _tool_content(rows):+ return [m["content"] for m in conversation_archive._as_wire(rows) if m["role"] == "tool"]++ sandbox = {+ "text": "token ZQX-5150",+ "images": [],+ "sessionId": "project-7",+ "files": [{"name": "out.csv", "size": 12}],+ }+ mcp_image = {+ "text": "chart rendered",+ "images": [{"data": "AAAA", "mimeType": "image/png"}],+ }++ assert _tool_content(_row("terminal", sandbox)) == ["token ZQX-5150"]+ assert _tool_content(_row("python", mcp_image)) == ["chart rendered"]+ # An empty wrapper text still takes the sentinel, as the adapter does.+ assert _tool_content(_row("terminal", {**sandbox, "text": ""})) == ['{"result":""}']+ # Someone else's result with text and a session is NOT unwrapped, or its other fields+ # would be dropped. The name gates it, as on the frontend.+ assert _tool_content(_row("lookup", sandbox)) == [+ '{"text":"token ZQX-5150","images":[],"sessionId":"project-7",'+ '"files":[{"name":"out.csv","size":12}]}'+ ]+++def test_the_branch_seed_scores_an_in_order_run_not_a_set(conn):+ """Sets lose repetition and ordering, and leaves are tried newest-first.++ A newer abandoned sibling holding the same distinct texts scored identically to the+ request's own branch and won the tie, so a turn was handed the seat belonging to its+ earlier twin and two distinct turns claimed one seat. A multiset would fix the repeat+ case and not the reordered one.+ """+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ rows = [+ ("m0", None, "user", "A", 2),+ ("m1", "m0", "assistant", "a1", 3),+ ("m2", "m1", "user", "B", 4),+ ("m3", "m2", "assistant", "b1", 5),+ ("m4", "m3", "user", "B", 6),+ ("m5", "m4", "assistant", "b1", 7),+ # The abandoned sibling is NEWER and holds the same distinct texts, once each.+ ("n0", "m1", "user", "B", 8),+ ("n1", "n0", "assistant", "b1", 9),+ ]+ for identifier, parent, role, text, created in rows:+ studio_db.upsert_chat_message(+ {+ "id": identifier,+ "threadId": THREAD,+ "parentId": parent,+ "role": role,+ "content": [{"type": "text", "text": text}],+ "createdAt": created,+ }+ )++ branch = [+ {"role": "user", "content": "A"},+ {"role": "assistant", "content": "a1"},+ {"role": "user", "content": "B"},+ {"role": "assistant", "content": "b1"},+ {"role": "user", "content": "B"},+ {"role": "assistant", "content": "b1"},+ ]+ positions = conversation_archive._transcript_positions(THREAD, branch = branch)++ assert len(positions) == 3, positions+ # Both repeats keep their own seat instead of collapsing onto the first.+ assert conversation_archive._occurrences(positions, branch[2:4]) == [1, 2]+++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_a_system_prompt_does_not_stall_the_branch_seed(conn):+ """Studio prepends chat and project instructions to every outbound request.++ That synthetic `system` message is not part of the stored chain, so a strict cursor+ stalled on it: no leaf could advance past `wanted[0]`, every one scored zero, and the+ seed fell back to the newest row -- the abandoned branch it exists to avoid. Measured+ with an ordinary system prompt in front, the seed picked branch B over the request's+ own A on a thread it had just got right.+ """+ live = _branch_switch_thread()+ with_system = [{"role": "system", "content": "You are a helpful assistant."}] + live++ plain = conversation_archive._transcript_positions(THREAD, branch = live)+ seeded = conversation_archive._transcript_positions(THREAD, branch = with_system)++ assert len(plain) == 3, plain+ assert seeded == plain+++def test_the_branch_seed_reaches_a_leaf_older_than_the_retry_pile(conn):+ """The branch a user goes BACK to is older than every retry made since.++ Capping the candidate leaves at a small number therefore excluded the one branch this+ exists to find: past that many retries the request's own branch could not be selected+ however well it matched, and the walk fell back to the newest abandoned leaf.+ """+ from storage import studio_db++ live = _branch_switch_thread()+ # A pile of newer abandoned retries, each its own leaf off the very first reply.+ for index in range(40):+ studio_db.upsert_chat_message(+ {+ "id": f"r{index}",+ "threadId": THREAD,+ "parentId": "m1",+ "role": "user",+ "content": [{"type": "text", "text": f"abandoned retry {index}"}],+ "createdAt": 100 + index,+ }+ )++ positions = conversation_archive._transcript_positions(THREAD, branch = live)++ assert len(positions) == 3, positions+ assert conversation_archive._occurrences(positions, live[4:6]) == [2]+++def test_an_unfinished_local_tool_call_is_not_replayed_at_all():+ """A cancelled card is not a call with a missing result, it is not a call.++ `chat-adapter.ts` drops the whole thing (`if (!toolResult &&+ !canReplayToolCallWithoutRoleTool(part)) continue`), so keeping the call and merely+ omitting its `tool` message reconstructs an assistant `tool_calls` message the request+ never carried. That shifts every group after it, which is what decides ordinals and+ whether an archived turn passes the live-branch check.+ """+ row = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "provenance": {"source": "local"},+ },+ {"type": "text", "text": "cancelled, moving on"},+ ],+ }++ wire = conversation_archive._as_wire([row])++ assert [message.get("role") for message in wire] == ["assistant"]+ assert "tool_calls" not in wire[0]+ assert not any(+ isinstance(part, dict) and part.get("type") == "tool-call" for part in wire[0]["content"]+ ), "an unreplayable call was rebuilt into the wire form"+++def test_two_completed_local_tool_calls_replay_as_two_rounds():+ """`shouldFlushCompletedLocalToolPair` makes each completed local pair its own group.++ Batched into one parallel call message, `group_turns` sees one exchange where the+ request sent two, so the second call matches no position and takes an invented+ ordinal.+ """+ row = {+ "role": "assistant",+ "content": [+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "provenance": {"source": "local"},+ "result": "one",+ },+ {+ "type": "tool-call",+ "toolCallId": "c2",+ "toolName": "terminal",+ "provenance": {"source": "local"},+ "result": "two",+ },+ ],+ }++ wire = conversation_archive._as_wire([row])++ assert [message.get("role") for message in wire] == [+ "assistant",+ "tool",+ "assistant",+ "tool",+ ]+ assert [message.get("tool_call_id") for message in wire if message["role"] == "tool"] == [+ "c1",+ "c2",+ ]+++def test_a_new_local_tool_round_starts_a_new_group():+ """`startsNewCodexToolRound`: same round batches, a different round flushes."""++ def _call(identifier, round_id):+ return {+ "type": "tool-call",+ "toolCallId": identifier,+ "toolName": "terminal",+ "provenance": {"source": "local", "round_id": round_id},+ "result": identifier,+ }++ wire = conversation_archive._as_wire(+ [{"role": "assistant", "content": [_call("c1", 1), _call("c2", 1), _call("c3", 2)]}]+ )++ assert [message.get("role") for message in wire] == [+ "assistant",+ "tool",+ "tool",+ "assistant",+ "tool",+ ]+ assert [call["id"] for call in wire[0]["tool_calls"]] == ["c1", "c2"]+ assert [call["id"] for call in wire[3]["tool_calls"]] == ["c3"]+++def test_a_topped_up_copy_keeps_the_transcript_span(conn):+ """The top-up path writes the same document, so it needs the same span.++ `_archivable` strips a retrieval call and its result, so a group of three can cover+ four transcript messages. The primary write records the transcript figure; the+ re-embed top-up recorded `len(group)`, and a copy written short is bounded by the+ smaller run in `_document_matches_one_run` and filtered out of every recall.+ """+ 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++ _archive(group)+ scope = store.conversation_archive_scope(THREAD)+ digest = [+ row["sha256"]+ for row in conn.execute("SELECT sha256 FROM documents WHERE scope=?", (scope,)).fetchall()+ ][0]++ assert (+ conversation_archive._write_copy(+ conn,+ scope = scope,+ thread_id = THREAD,+ roles = "assistant",+ digest = digest,+ identity = "test-embedder",+ group = archivable,+ span = len(group),+ chunks = [],+ vectors = [],+ seats = [0, 1],+ )+ is True+ )+ conn.commit()++ spans = [+ row["archive_messages"]+ for row in conn.execute(+ "SELECT archive_messages FROM documents WHERE scope=?", (scope,)+ ).fetchall()+ ]+ assert spans == [4, 4], spans+++def test_a_tool_turn_with_a_preamble_still_gets_its_seat():+ """ "Let me check" ahead of a tool call is the ordinary agent turn, not an edge case.++ `_probe_text` offers BOTH JSON spellings of the stored arguments, and that second+ spelling lands between the arguments and whatever followed them, so the live render+ (name/args/text) is no longer contiguous inside the stored one (name/args/args/text).+ The turn matched no transcript position and took a fallback ordinal past the whole+ transcript, where the recall header presents it as superseding genuinely later+ instructions.+ """+ user = {"role": "user", "content": "what files are here"}+ row = {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "Let me check"},+ {+ "type": "tool-call",+ "toolCallId": "c1",+ "toolName": "terminal",+ "args": {"command": "ls"},+ "result": "main.py",+ },+ ],+ }+ positions = [+ [+ conversation_archive._normalise_cased(conversation_archive._probe_text(message))+ for message in conversation_archive._as_wire([record])+ ]+ for record in (user, row)+ ]+ live = [+ {+ "role": "assistant",+ "content": "Let me check",+ "tool_calls": [+ {"id": "c1", "function": {"name": "terminal", "arguments": '{"command": "ls"}'}}+ ],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "main.py"},+ ]++ assert conversation_archive._occurrences(positions, live) == [1]+++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_reasoning_turn_is_reconstructed_without_its_thinking():+ """Reasoning is not content, and the wire form never carries it as content.++ The serializer puts it in `reasoning_content` or drops it, so forwarding the stored+ part list rendered a reasoning model's thinking inline where the request sends only+ the answer. That turn matched no transcript seat and took an ordinal past genuinely+ later turns, under a header that calls the higher number the latest word.+ """+ row = {+ "role": "assistant",+ "content": [+ {"type": "reasoning", "text": "The user wants the file list. I should run ls."},+ {"type": "text", "text": "There are two files."},+ ],+ }+ live = [+ {+ "role": "assistant",+ "content": "There are two files.",+ "reasoning_content": "The user wants the file list. I should run ls.",+ }+ ]++ stored = [conversation_archive._probe_text(m) for m in conversation_archive._as_wire([row])]++ assert stored == [conversation_archive._probe_text(live[0])] == ["There are two files."]+ assert conversation_archive._occurrences([stored], live) == [0]+++def test_a_unicode_tool_result_is_serialised_the_way_javascript_serialises_it():+ """`JSON.stringify` leaves non-ASCII alone; `json.dumps` escapes it by default.++ The reconstructed `tool` message then reads `Montr\\u00e9al` where the archived wire+ text carries the character itself, and every comparison downstream is exact, so a+ multilingual tool exchange loses its seat and is filtered out of recall.+ """+ assert (+ conversation_archive._tool_result_content({"ville": "Montréal"}, "terminal")+ == '{"ville":"Montréal"}'+ )+++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 configfrom core.rag.chunking import chunk_pagesfrom core.rag.parsers import Page@@ -1923,3 +4154,38 @@ def test_one_pass_holding_both_spans_widens_the_window_too(conn):).fetchall()]assert spans == [4], spans+++def test_a_repeat_that_came_back_into_the_prompt_keeps_one_copy(conn):+ """A rewind, or a bigger window, can put an evicted occurrence back in the prompt.++ The already-archived path then re-stamped a copy per transcript SEAT while the+ live-aware budget had dropped to one, so two byte-identical documents survived. Both+ pass the branch filter and `recall` dedups on chunk id, which differs, so a recall slot+ went on text the model could already read: measured, three passages of which two were+ distinct.+ """+ import hashlib++ repeat = _turn("set ZQXVARA123 to 1", "ok")+ middle = _turn("tell me about ZQXVARA123 pelicans", "sure")+ tail = _turn("and now something else about ZQXVARA123", "fine")+ conversation = repeat + middle + list(repeat) + tail+ _save_thread(THREAD, conversation)+ scope = store.conversation_archive_scope(THREAD)+ digest = hashlib.sha256(+ conversation_archive.render_turn(repeat).encode("utf-8", "ignore")+ ).hexdigest()++ # Both occurrences evicted: two copies, one per seat.+ conversation_archive.archive_turns(THREAD, conversation[:6], live = tail)+ assert len(store.documents_by_hash(conn, scope, digest)) == 2++ # The newer occurrence is live again, so only one of them is still evicted.+ conversation_archive.archive_turns(THREAD, repeat, live = list(repeat) + tail)++ assert len(store.documents_by_hash(conn, scope, digest)) == 1+ found = conversation_archive.recall(THREAD, "ZQXVARA123", top_k = 4)+ assert found is not None+ texts = [source["text"] for source in found[1]]+ assert len(texts) == len(set(texts)), textsdiff --git a/studio/backend/tests/test_conversation_recall_injection.py b/studio/backend/tests/test_conversation_recall_injection.pyindex 5aa60fdec6b..566ea0d765b 100644--- a/studio/backend/tests/test_conversation_recall_injection.py+++ b/studio/backend/tests/test_conversation_recall_injection.py@@ -828,7 +828,7 @@ def test_the_sticky_boundary_is_applied_once_per_request():from pathlib import Pathsource = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"- text = source.read_text()+ text = source.read_text(encoding = "utf-8")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())@@ -844,6 +844,7 @@ def test_conversation_search_top_k_is_clamped(archived, monkeypatch):*,top_k = None,branch_messages = None,+ extra_queries = None,):seen["top_k"] = top_kseen["branch_messages"] = branch_messages@@ -874,6 +875,7 @@ def test_conversation_search_top_k_is_clamped_by_the_live_budget(archived, monke*,top_k = None,branch_messages = None,+ extra_queries = None,):seen["top_k"] = top_kreturn ("earlier turn", [{"id": "1"}])@@ -1046,7 +1048,7 @@ def test_both_retrieval_tools_share_the_per_turn_search_cap():# 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()+ text = (backend / module).read_text(encoding = "utf-8")# 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, moduleassert 'decision.tool_name == "search_knowledge_base"' not in text, module@@ -1066,6 +1068,7 @@ def test_an_omitted_top_k_falls_through_to_the_configured_default(archived, monk*,top_k = None,branch_messages = None,+ extra_queries = None,):seen["top_k"] = top_kseen["branch_messages"] = branch_messages@@ -1112,6 +1115,7 @@ def test_the_forced_recall_searches_for_the_USERS_question(archived, monkeypatch*,top_k = None,branch_messages = None,+ extra_queries = None,):seen["query"] = queryreturn ("earlier turn", [{"id": "1"}])@@ -1386,7 +1390,7 @@ def test_a_tool_exchange_this_request_created_stays_on_the_branch(monkeypatch):from pathlib import Pathsource = Path(__file__).resolve().parent.parent / "core/inference/llama_cpp.py"- text = " ".join(source.read_text().split())+ text = " ".join(source.read_text(encoding = "utf-8").split())# The branch handed to both the forced recall and a model-initiated search is the# accumulated one, never the request's own messages.@@ -1399,6 +1403,204 @@ def test_a_tool_exchange_this_request_created_stays_on_the_branch(monkeypatch):assert "_branch_boundary(conversation, _request_branch)" in text+# --- The instruction the user gave, and the follow-up that says nothing ---++INSTRUCTION = (+ "Standing instruction for the rest of this task: always report results as a markdown "+ "table, and finish every reply with the line STATUS::ZQXVARA123-ALPHA."+)+++def _instructed_thread(thread_id = THREAD):+ """A thread whose instruction is archived and whose newest message is filler."""+ from storage import studio_db++ turns = [+ {"role": "user", "content": INSTRUCTION},+ {"role": "assistant", "content": "Understood."},+ ] + [+ message+ for index in range(6)+ for message in (+ {"role": "user", "content": f"Here is section {index} of the report to review."},+ {"role": "assistant", "content": f"Section {index} looks fine."},+ )+ ]+ studio_db.upsert_chat_thread(+ {+ "id": thread_id,+ "title": "t",+ "modelType": "base",+ "modelId": "local-model",+ "createdAt": 1,+ }+ )+ for index, message in enumerate(turns):+ studio_db.upsert_chat_message(+ {+ "id": f"{thread_id}-ins-{index}",+ "threadId": thread_id,+ "role": message["role"],+ "content": [{"type": "text", "text": message["content"]}],+ "createdAt": index + 2,+ }+ )+ conversation_archive.archive_turns(thread_id, turns)+ return turns+++def test_an_anaphoric_latest_message_recalls_the_governing_instruction(+ rag_home, rag_conn, stub_embeddings+):+ """ "continue" is what the user types, and what the archive gets searched for.++ Pre-fix the query is the word "continue", which appears in no archived turn, so the+ recall returns nothing at all on precisely the turn that needed it. That is not a+ contrived follow-up: OpenCode and Zed both GENERATE one after every auto compaction.+ """+ turns = _instructed_thread()+ branch = turns + [{"role": "user", "content": "continue"}]++ built = tools_mod.build_conversation_recall(+ branch, THREAD, style = "inline", top_k = 4, branch_messages = branch+ )++ assert built is not None+ assert "markdown table" in built["prefix"]+++def test_a_short_self_contained_request_keeps_the_only_recall_slot(+ rag_home, rag_conn, stub_embeddings+):+ """The anchor is a rescue for a message that names nothing, not a tax on short ones.++ `recall` spends the anchor's share of the budget FIRST, so at a limit of one it takes+ the only slot. A top_k of 1 is not a corner: `_recall_top_k` is+ `budget_tokens // CHUNK_TOKENS`, and the over-budget retry walks 4 -> 2 -> 1. So a+ two-word request that names its own subject must not be classed thin, or the recall+ block comes back holding an unrelated older instruction and NOT the turn that answers+ what was asked.+ """+ turns = _instructed_thread()+ branch = turns + [{"role": "user", "content": "section 3"}]++ built = tools_mod.build_conversation_recall(+ branch, THREAD, style = "inline", top_k = 1, branch_messages = branch+ )++ assert built is not None+ assert "section 3" in built["prefix"].lower()+++def test_a_substantive_latest_message_still_drives_the_query_alone(+ rag_home, rag_conn, stub_embeddings, monkeypatch+):+ """The common path must be untouched: a real question is its own best query."""+ turns = _instructed_thread()+ branch = turns + [{"role": "user", "content": "What did section 3 of the report say?"}]+ seen = {}++ real = conversation_archive.recall++ def recording(thread_id, query, **kwargs):+ seen["extra"] = kwargs.get("extra_queries")+ return real(thread_id, query, **kwargs)++ monkeypatch.setattr(conversation_archive, "recall", recording)+ tools_mod.build_conversation_recall(+ branch, THREAD, style = "inline", top_k = 4, branch_messages = branch+ )++ assert seen["extra"] is None+++def test_no_earlier_instruction_means_no_second_query(+ rag_home, rag_conn, stub_embeddings, monkeypatch+):+ """A thread of nothing but filler must behave exactly as it does today."""+ from storage import studio_db++ studio_db.upsert_chat_thread(+ {"id": THREAD, "title": "t", "modelType": "base", "modelId": "local-model", "createdAt": 1}+ )+ turns = [{"role": "user", "content": "ok"}, {"role": "assistant", "content": "sure"}]+ for index, message in enumerate(turns):+ studio_db.upsert_chat_message(+ {+ "id": f"{THREAD}-f{index}",+ "threadId": THREAD,+ "role": message["role"],+ "content": [{"type": "text", "text": message["content"]}],+ "createdAt": index + 2,+ }+ )+ conversation_archive.archive_turns(THREAD, turns)+ seen = {}++ real = conversation_archive.recall++ def recording(thread_id, query, **kwargs):+ seen["extra"] = kwargs.get("extra_queries")+ return real(thread_id, query, **kwargs)++ monkeypatch.setattr(conversation_archive, "recall", recording)+ tools_mod.build_conversation_recall(+ turns + [{"role": "user", "content": "continue"}],+ THREAD,+ style = "inline",+ top_k = 4,+ branch_messages = turns + [{"role": "user", "content": "continue"}],+ )++ assert seen["extra"] is None+++def test_both_recall_styles_state_that_a_later_turn_supersedes_an_earlier_one(archived):+ """The rule has to reach all three consumers, so it lives in the recalled text.++ Putting it in `_RECALL_BLOCK` would cover the plain path only: the tool style routes+ through a forged tool exchange and the model's own `search_conversation` sees neither.+ """+ from storage import studio_db++ extra = [+ {"role": "user", "content": "and one about otters"},+ {"role": "assistant", "content": "There once was an otter with tools"},+ ]+ # Saved as well as archived: the branch filter checks recalled turns against the stored+ # transcript, so an archived turn nobody saved is filtered right back out.+ for index, message in enumerate(extra):+ studio_db.upsert_chat_message(+ {+ "id": f"{THREAD}-otter-{index}",+ "threadId": THREAD,+ "role": message["role"],+ "content": [{"type": "text", "text": message["content"]}],+ "createdAt": index + 20,+ }+ )+ conversation_archive.archive_turns(THREAD, extra)+ conversation = _conversation()++ inline = tools_mod.build_conversation_recall(conversation, THREAD, style = "inline", top_k = 4)+ tool_style = tools_mod.build_conversation_recall(conversation, THREAD, style = "tool", top_k = 4)++ assert "supersedes" in inline["prefix"] and "oldest first" in inline["prefix"]+ tool_result = [m for m in tool_style["messages"] if m.get("role") == "tool"][0]+ assert "supersedes" in tool_result["content"]+ # And the sentence that claimed an ordering the block no longer has is gone.+ assert "most relevant earlier turns" not in inline["prefix"]+++def test_a_single_recalled_turn_makes_no_ordering_claim(archived):+ """One passage cannot be in an order, and the backoff's last rung is where room is+ tightest -- so the header must not be spent there."""+ built = tools_mod.build_conversation_recall(_conversation(), THREAD, style = "inline", top_k = 1)++ assert built is not None+ assert "supersedes" not in built["prefix"]++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.diff --git a/studio/backend/tests/test_rag_retrieval.py b/studio/backend/tests/test_rag_retrieval.pyindex 057eaed7c4d..d302848df9b 100644--- a/studio/backend/tests/test_rag_retrieval.py+++ b/studio/backend/tests/test_rag_retrieval.py@@ -426,7 +426,9 @@ def test_retrieve_hybrid_mode_selects_backend(monkeypatch):monkeypatch.setattr(retrieval,"retrieve_lexical",- lambda c, s, q, k = None: calls.append(("lex", k)) or [],+ # The archive's shaped FTS query, accepted and ignored: this test is about which+ # backends run.+ lambda c, s, q, k = None, *, match_query = None: calls.append(("lex", k)) or [],)monkeypatch.setattr(retrieval,diff --git a/studio/backend/tests/test_rag_store.py b/studio/backend/tests/test_rag_store.pyindex 07abfb835ec..19c21930355 100644--- a/studio/backend/tests/test_rag_store.py+++ b/studio/backend/tests/test_rag_store.py@@ -324,3 +324,140 @@ def test_gate_counts_a_folder_document_that_outlived_its_folder(rag_conn):rag_conn.commit()assert store.linked_folder_rows_exist(rag_conn) is Trueassert store.search_lexical(rag_conn, "kb_a", "alpha", 10) == []+++def _pasted_prose(words: int) -> str:+ """Distinct ordinary words, as a pasted log or source file supplies them.++ Purely alphabetic on purpose: a token mixing letters and digits short-circuits the+ identifier test on its first clause and never reaches the scan being measured, so a+ synthetic `tok1 tok2 ...` paste hides the cost that real prose pays.+ """+ letters = "abcdefghijklmnopqrstuvwxyz"+ return " ".join(+ letters[index % 26]+ + letters[(index // 26) % 26]+ + letters[(index // 676) % 26]+ + letters[(index // 17576) % 26]+ + "qz"+ for index in range(words)+ )+++def test_a_pasted_log_does_not_make_the_archive_query_quadratic(monkeypatch):+ """Shaping the archive query must not re-tokenize the question once per token.++ `conversation_match_queries` runs on the LATEST USER MESSAGE, and the message that+ forces a compaction is very often a pasted log or source file. Re-scanning the whole+ question inside the per-token identifier test made the shaping cost grow with the+ square of the question's length: 48 KB of pasted prose measured at 4.6s and 96 KB at+ 17.7s of pure CPU, against 2.3ms for the same text through `_match_query`. The recall+ path can run the shaping several times per request -- once per widening iteration in+ `conversation_archive.recall`, and again for each rung of the over-budget top_k+ backoff -- so the multiplier lands on the one turn that compacts the thread.++ Counted rather than timed, so the guard is deterministic: the number of full scans of+ the question is what has to stay bounded, not the wall clock on one machine.+ """+ scans = {"n": 0}+ real = store._TOKEN++ class CountingToken:+ def findall(self, text):+ scans["n"] += 1+ return real.findall(text)++ monkeypatch.setattr(store, "_TOKEN", CountingToken())++ question = f"what is the current value of ZQXVARA123 {_pasted_prose(2000)}"+ expressions = store.conversation_match_queries(question)++ assert expressions and expressions[0].startswith('"zqxvara123"')+ # Once for the lower-cased tokens, once for the raw ones. Anything that grows with the+ # token count is the quadratic coming back.+ assert scans["n"] <= 2, f"tokenized the question {scans['n']} times"+++def test_query_shaping_stays_cheap_on_a_pasted_log():+ """The wall-clock companion to the scan count, with a wide margin.++ 6000 pasted words is roughly a 48 KB paste, which is one source file. Unfixed this+ takes about 4.6s of CPU; linear it takes about 6ms. A 1.0s ceiling is unreachable by+ a linear implementation on any machine that can run this suite at all.+ """+ import time++ question = f"what is the current value of ZQXVARA123\n{_pasted_prose(6000)}"+ started = time.perf_counter()+ expressions = store.conversation_match_queries(question)+ elapsed = time.perf_counter() - started+ assert expressions and expressions[0] == '"zqxvara123"'+ assert elapsed < 1.0, f"shaping a 6000-word paste took {elapsed:.2f}s"+++def test_a_quoted_function_word_survives_the_stopword_filter():+ """Quotes are how a user names a word instead of using it.++ `What did I say about "this"?` reduced to '"say"' once the stopword list had it, and+ an archived `Use this endpoint` was then unreachable: it never contains "say", and if+ unrelated chunks fill the fetch window `_candidates` never reaches its hybrid+ fallback. Unquoted, the same word stays a stopword.+ """+ quoted = store.conversation_match_queries('What did I say about "this"?')+ plain = store.conversation_match_queries("What did I say about this?")++ assert quoted == ['"say" OR "this"']+ assert plain == ['"say"']+ # A quoted function word is not an identifier, so only the permissive pass widens.+ assert len(quoted) == 1+++def test_a_legacy_archive_still_gets_two_different_ends(rag_home, rag_conn):+ """Every ordinal NULL made both halves of the two-ended fetch the same query.++ FTS5 floors the IDF of a term the whole index shares, so a per-thread archive's own+ subject scores identically on every hit, and on an archive written before+ `archive_ordinal` existed every later ordering term was constant too. Both windows+ then returned the same arbitrary rows, `_both_ends` deduplicated them, and the later+ legacy revisions were unreachable at any candidate count.+ """+ import types++ from core.rag import store++ conn = rag_conn+ scope = "convarchive_legacy"+ for index in range(8):+ document = store.create_document(+ conn,+ scope = scope,+ thread_id = "t",+ filename = f"earlier turn {index}",+ sha256 = f"h{index}",+ status = "completed",+ embedding_model = "m",+ archive_messages = 2,+ archive_ordinal = None,+ commit = False,+ )+ chunk = types.SimpleNamespace(+ chunk_index = 0,+ text = f"ZQXLEGACY token number {index}",+ page_number = None,+ source_page_index = None,+ token_count = 5,+ char_count = 20,+ )+ store.add_chunks(conn, scope, document, [chunk], [[0.0, 0.0, 0.0, 0.0]])+ conn.commit()++ oldest = [+ chunk for chunk, _ in store.search_lexical(conn, scope, "ZQXLEGACY", 3, oldest_first = True)+ ]+ newest = [+ chunk for chunk, _ in store.search_lexical(conn, scope, "ZQXLEGACY", 3, newest_first = True)+ ]++ assert oldest and newest+ assert oldest != newest, "both ends of the fetch returned the same rows"+ assert not set(oldest) & set(newest), (oldest, newest)