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: give the conversation archive's order a final tiebreaker (#10572)
Daniel Han34120fb43271
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.pyindex d6b77215fa9..73c27c7ee2a 100644--- a/studio/backend/core/rag/conversation_archive.py+++ b/studio/backend/core/rag/conversation_archive.py@@ -451,6 +451,7 @@ def archive_turns(continueordinal = Nonearchived_at = None+ archived_rowid = Noneif stale is not None:# Same turn, vectors from an embedder the query side no longer asks for.# The copy is replaced rather than deduplicated, as ingestion does, since@@ -461,9 +462,13 @@ def archive_turns(# 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 {}+ # And its ROWID: turns archived in one clock tick share a `created_at`, so+ # insertion order is all that separates them. Reusable because the row is+ # deleted below in this same transaction.+ previous = store.document_rewrite_identity(conn, stale) or {}ordinal = previous.get("archive_ordinal")archived_at = previous.get("created_at")+ archived_rowid = previous.get("rowid")store.delete_document(conn, stale, commit = False)else:# The nth copy of a repeated turn takes the nth occurrence's position, so a@@ -495,6 +500,8 @@ def archive_turns(# 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,+ # Likewise None for a first sighting: SQLite then assigns the next rowid.+ rowid = archived_rowid,commit = False,)try:@@ -2108,25 +2115,46 @@ def _document_matches_one_run(return any(_one_run_from(start) for start in range(len(transcript)))+def _order_key(ordinal, created_at, document_rowid, chunk_index) -> tuple:+ """The recall order, spelling-independent: the single-query path passes a row's+ snake_case columns and the merge passes a source's camelCase keys, and a second copy of+ the key agrees only until someone edits one of them.+ """+ created = created_at or ""+ rowid = document_rowid or 0+ index = chunk_index or 0+ if ordinal is None:+ return (0, 0, created, rowid, index)+ return (1, int(ordinal), created, rowid, index)++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 werewritten 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.+ turn in the same scope. `created_at` breaks ties below that, 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.++ Then the document's rowid, because `created_at` ties whenever the clock is coarser than+ the write: Windows advances it about every 15.6 ms, so a compaction stamps a whole+ conversation identically and the sort falls back to relevance order under a header+ saying oldest first. Insertion order is what the archive recorded, and the rewrite path+ preserves it (`create_document`'s `rowid`) so a re-embed cannot move a turn.++ `chunk_index` comes LAST because it is a position WITHIN a document: above the rowid it+ interleaves two tied documents (A0, B0, A1, B1, ...) rather than ordering them,+ shredding the long message it exists to keep contiguous."""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)+ return (2, 0, "", 0, 0)+ return _order_key(+ tool._row_value(row, "archive_ordinal"),+ tool._row_value(row, "created_at"),+ tool._row_value(row, "document_rowid"),+ tool._row_value(row, "chunk_index"),+ )def _above_floor(hits: list, min_dense_score: float) -> list:@@ -2460,16 +2488,15 @@ def recall(if not merged:return Noneif 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.+ # Literally the key `_conversation_order` uses, not a second copy that agrees+ # today: component order included, or the merged block contradicts the unmerged+ # one on the same archive.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,+ key = lambda source: _order_key(+ source.get("turn"),+ source.get("createdAt"),+ source.get("documentRowid"),+ source.get("chunkIndex"),))kept = merged[:limit]diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex c26e0160807..5c5c604b2e9 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -272,24 +272,31 @@ def create_document(archive_messages: int | None = None,archive_ordinal: int | None = None,created_at: str | None = None,+ rowid: int | None = None,commit: bool = True,) -> str:- """``created_at`` is for a REWRITE of a row that already exists, and nothing else.+ """``created_at`` and ``rowid`` are for a REWRITE of a row that already exists.A re-embed deletes the old row and inserts a new one for the same content, so stampingit with the current time would say the turn was archived when its vectors wererebuilt. That is not a cosmetic difference for an archived turn: an archive writtenbefore `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.+ takes a fresh timestamp moves that turn to the end of its own conversation.++ ``rowid`` carries over one level down: rows archived in the same clock tick share a+ `created_at` (routine on Windows, ~15.6 ms tick), so insertion order is all that+ separates them and a fresh rowid sorts the rewritten turns behind the untouched ones.+ Omitted, both arguments leave this byte for byte what every other caller has always+ got: a NULL rowid is assigned exactly as if the column were not named."""document_id = document_id or str(uuid.uuid4())conn.execute(- "INSERT INTO documents(id, scope, kb_id, thread_id, project_id, filename, sha256, "+ "INSERT INTO documents(rowid, 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, archive_ordinal) "- "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",(+ rowid,document_id,scope,kb_id,@@ -387,6 +394,17 @@ def get_document(conn: sqlite3.Connection, document_id: str) -> dict | None:return dict(row) if row else None+def document_rewrite_identity(conn: sqlite3.Connection, document_id: str) -> dict | None:+ """What a re-embed carries over from the row it replaces. Separate from `get_document`+ because `SELECT *` omits the implicit rowid and widening it would add the key to every+ caller's dict.+ """+ row = conn.execute(+ "SELECT rowid, archive_ordinal, created_at FROM documents WHERE id=?", (document_id,)+ ).fetchone()+ return dict(row) if row else None++def get_visible_document(conn: sqlite3.Connection, document_id: str) -> dict | None:"""Return a document only while its owning scope is available to readers."""row = conn.execute(@@ -547,9 +565,14 @@ def search_lexical(`newest_first` breaks TIES the other way round. FTS5 floors the IDF of a term thewhole index shares, so every hit on a per-thread archive's own subject scores thesame, 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.+ subject the newest assignment is unreachable at any k.++ Both ordered forms SELECT rather than arrange: under the `LIMIT` they decide which rows+ the caller is offered at all. So the tiebreak has to be+ `conversation_archive._conversation_order` component for component, and ending it on a+ chunk id ends it on a uuid4 -- which on a legacy archive, every ordinal NULL and one+ clock tick over every row, IS the whole cut.+ `test_the_candidate_window_is_cut_in_conversation_order` pins the two orders together."""mq = match_query if match_query is not None else _match_query(query)if not mq:@@ -568,25 +591,26 @@ def search_lexical(# The filtered form runs both subqueries for every matched row BEFORE the LIMIT, and with nothing# linked that work is provably wasted (linked_folder_rows_exist).if oldest_first:- # Order by archive ordinal, not rowid, which a re-embed scrambles; NULLs first as oldest, then- # created_at and chunk id, else on a legacy archive both halves return the same subset.+ # `_conversation_order` component for component. The DOCUMENT rowid, not the+ # chunk one: a re-embed rewrites the chunk rows and only the document's own+ # rowid survives it (`create_document`'s `rowid`).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 ?"+ f"d.created_at ASC, d.rowid ASC, c.chunk_index ASC LIMIT ?")elif newest_first:- # rowid is insertion order and a re-embed reinserts a chunk, so a rowid DESC window missed the newest turn.+ # The mirror of the clause above, so the two halves cut the run at opposite ends.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 ?"+ f"d.created_at DESC, d.rowid DESC, c.chunk_index DESC LIMIT ?")elif linked_folder_rows_exist(conn):sql = (@@ -737,7 +761,8 @@ 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, d.archive_ordinal, d.created_at "+ f"c.source_page_index, d.filename, d.archive_ordinal, d.created_at, "+ f"d.rowid AS document_rowid "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 ff614285780..b4c2ed3f509 100644--- a/studio/backend/core/rag/tool.py+++ b/studio/backend/core/rag/tool.py@@ -151,6 +151,9 @@ def format_conversation_recall(rows, hits) -> tuple[str, list[dict]]:# ordinals are not UNIQUE."chunkIndex": _row_value(r, "chunk_index"),"createdAt": _row_value(r, "created_at"),+ # And insertion order under that, for archives whose rows share a timestamp+ # the clock was too coarse to separate; without it the merge key runs out.+ "documentRowid": _row_value(r, "document_rowid"),"score": round(float(h.score), 4) if h.score is not None else None,})diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.pyindex c6609ed09dd..72d8bf77181 100644--- a/studio/backend/tests/test_conversation_archive.py+++ b/studio/backend/tests/test_conversation_archive.py@@ -2063,6 +2063,258 @@ def test_a_re_embed_that_stops_partway_does_not_reorder_a_legacy_archive(conn, massert quoted == ["1", "2", "3", "4", "5"], quoted+def test_a_legacy_archive_written_in_one_clock_tick_is_still_ordered(conn, monkeypatch):+ """The same reorder as the test above, with the clock tie forced instead of hoped for.++ That test only reaches the bug when the rows carry DISTINCT timestamps, a property of+ the host clock: Windows advances it about every 15.6 ms, so a compaction there stamps+ the whole conversation alike and the failure lands on one CI leg as a different+ permutation every run. With the ordinal NULL and `created_at` equal the key is spent,+ and a stable `sorted` quotes the turns in RELEVANCE order under an oldest-first header.+ """+ from core.rag import embeddings++ # One tick for every row, which is what a coarse system clock does to the archive.+ monkeypatch.setattr(store, "_now", lambda: "2026-01-01T00:00:00+00:00")++ 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)+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE scope=?", (scope,))+ conn.commit()+ # The premise: nothing above insertion order can separate these rows any more.+ stamps = {+ row["created_at"]+ for row in conn.execute("SELECT created_at FROM documents WHERE scope=?", (scope,))+ }+ assert stamps == {"2026-01-01T00:00:00+00:00"}, stamps++ 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)++ _text, sources = conversation_archive.recall(THREAD, "pelicans", top_k = 5)+ quoted = [source["text"].split("STATEMENT")[1][0] for source in sources]+ assert quoted == ["1", "2", "3", "4", "5"], quoted+++def test_two_turns_stamped_alike_are_quoted_whole_and_not_interleaved(conn, monkeypatch):+ """Tied documents must GROUP, because `chunk_index` is a position inside one of them.++ Same clock tie as the test above, but with turns long enough to span several chunks.+ Ranked above the document, `chunk_index` sorts every document's chunk 0 ahead of any+ document's chunk 1, so two three-chunk turns come back A0, B0, A1, B1, A2, B2 and each+ is quoted through the middle of the other.+ """+ monkeypatch.setattr(config, "CHUNK_TOKENS", 30)+ monkeypatch.setattr(config, "CHUNK_OVERLAP", 0)+ monkeypatch.setattr(store, "_now", lambda: "2026-01-01T00:00:00+00:00")++ def _long_turn(tag):+ return _turn(+ f"turn {tag} about pelicans",+ f"{tag}HEAD pelicans at the opening "+ + " ".join(f"w{index}" for index in range(25))+ + f" {tag}TAIL pelicans at the closing "+ + " ".join(f"z{index}" for index in range(25)),+ )++ history = [dict(message) for tag in ("AAA", "BBB") for message in _long_turn(tag)]+ _save_thread(THREAD, history, append = True)+ assert conversation_archive.archive_turns(THREAD, [dict(m) for m in history]) == 2+ scope = store.conversation_archive_scope(THREAD)+ conn.execute("UPDATE documents SET archive_ordinal=NULL WHERE scope=?", (scope,))+ conn.commit()+ # The premise takes both halves: one timestamp for both documents, more than one chunk+ # each, or the interleave has nothing to interleave.+ assert {+ row["created_at"]+ for row in conn.execute("SELECT created_at FROM documents WHERE scope=?", (scope,))+ } == {"2026-01-01T00:00:00+00:00"}+ per_document = [+ row["n"]+ for row in conn.execute(+ "SELECT COUNT(*) AS n FROM chunks WHERE scope=? GROUP BY document_id", (scope,)+ )+ ]+ assert min(per_document) > 1, per_document++ _text, sources = conversation_archive.recall(THREAD, "pelicans", top_k = 8)++ # Each turn is quoted in one unbroken run, and the run that was archived first leads.+ documents = [source["documentId"] for source in sources]+ runs = [+ document+ for index, document in enumerate(documents)+ if index == 0 or documents[index - 1] != document+ ]+ assert len(runs) == len(set(documents)) == 2, documents+ # And inside a run the pieces are still in writing order.+ for document in runs:+ indexes = [s["chunkIndex"] for s in sources if s["documentId"] == document]+ assert indexes == sorted(indexes), (document, indexes)+ assert "AAAHEAD" in sources[0]["text"], sources[0]["text"]+++def test_the_sql_candidate_order_agrees_with_the_python_recall_order(conn):+ """The two orderings are written twice, in two languages, so pin them to each other.++ `store.search_lexical`'s ordered clauses and `_conversation_order` cannot share an+ implementation across the SQL boundary, and drift is not cosmetic: the SQL runs under a+ LIMIT and CHOOSES the candidates, so a disagreement silently deletes the turns the two+ ends disagree about.++ Asserted WITHIN each BM25 score, since the SQL sorts by relevance first and the recall+ key deliberately has no relevance component: relevance decides which turns are eligible,+ the archive decides the order among them. Document ids are assigned so that sorting by+ them REVERSES conversation order, or the test would pass on the draw. The archive is+ mixed on purpose (numbered and legacy turns, a shared timestamp and a distinct one,+ single- and multi-chunk documents) so every component of the key is exercised.+ """+ import types++ scope = store.conversation_archive_scope(THREAD)+ plan = [+ # (ordinal, created_at, chunk count). Two legacy rows tied on one clock tick, then+ # a legacy row the clock could separate, then two numbered rows tied to each other.+ (None, "2026-01-01T00:00:00+00:00", 3),+ (None, "2026-01-01T00:00:00+00:00", 2),+ (None, "2026-01-02T00:00:00+00:00", 1),+ (7, "2026-01-03T00:00:00+00:00", 2),+ (8, "2026-01-03T00:00:00+00:00", 2),+ ]+ for position, (ordinal, created, count) in enumerate(plan):+ # Descending ids against ascending conversation order: id order is exactly wrong.+ document_id = f"{len(plan) - position:04d}-turn"+ store.create_document(+ conn,+ scope = scope,+ thread_id = THREAD,+ filename = "earlier turn",+ sha256 = f"h{position}",+ status = "completed",+ embedding_model = "m",+ archive_messages = 2,+ archive_ordinal = ordinal,+ document_id = document_id,+ created_at = created,+ commit = False,+ )+ store.add_chunks(+ conn,+ scope,+ document_id,+ [+ types.SimpleNamespace(+ chunk_index = index,+ text = "ZQXAGREE statement " + "word " * (index + position),+ page_number = None,+ source_page_index = None,+ token_count = 5,+ char_count = 20,+ )+ for index in range(count)+ ],+ [[0.0] * 4] * count,+ )+ conn.commit()++ def _tiers(**direction):+ hits = store.search_lexical(conn, scope, "ZQXAGREE", 500, **direction)+ grouped: list = []+ for chunk_id, score in hits:+ if grouped and grouped[-1][0] == score:+ grouped[-1][1].append(chunk_id)+ else:+ grouped.append((score, [chunk_id]))+ return grouped++ oldest = _tiers(oldest_first = True)+ newest = _tiers(newest_first = True)+ every_id = [chunk_id for _score, tier in oldest for chunk_id in tier]+ assert len(every_id) == sum(count for _o, _c, count in plan)+ rows = store.chunks_by_id(conn, every_id)+ # Non-vacuous: some score really is shared, or none of the above is being tested.+ assert max(len(tier) for _score, tier in oldest) > 1, oldest++ for score, tier in oldest:+ expected = sorted(+ tier, key = lambda chunk_id: conversation_archive._conversation_order(rows[chunk_id])+ )+ assert tier == expected, (score, tier, expected)+ # And the other end is the exact mirror within each tier, or the two windows would not+ # be cutting one run from its two ends.+ assert [score for score, _ in newest] == [score for score, _ in oldest]+ for (_score, forward), (_same, backward) in zip(oldest, newest):+ assert backward == list(reversed(forward)), (forward, backward)+++def test_a_rewritten_turn_keeps_the_insertion_order_it_was_archived_in(conn, monkeypatch):+ """A re-embed replaces a row, and the replacement has to sit where the original sat.++ Carrying `created_at` over is enough only on a clock that separates the turns; on one+ that does not, a fresh rowid moves every turn the rewrite reached to the end. Asserted+ on the stored rows, so a regression is named as the write-side defect it is.+ """+ from core.rag import embeddings++ monkeypatch.setattr(store, "_now", lambda: "2026-01-01T00:00:00+00:00")+ 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, 4)]+ 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]) == 3+ scope = store.conversation_archive_scope(THREAD)+ before = [+ (row["rowid"], row["id"])+ for row in conn.execute(+ "SELECT rowid, id FROM documents WHERE scope=? ORDER BY rowid", (scope,)+ )+ ]++ identity["name"] = "st:model-b"+ conversation_archive.archive_turns(THREAD, [dict(m) for m in history])++ after = [+ (row["rowid"], row["id"])+ for row in conn.execute(+ "SELECT rowid, id FROM documents WHERE scope=? ORDER BY rowid", (scope,)+ )+ ]+ # Every row really was rewritten, and every one of them landed back where it was.+ assert [rowid for rowid, _ in after] == [rowid for rowid, _ in before]+ assert [document_id for _, document_id in after] != [document_id for _, document_id in before]++def test_merging_two_recall_queries_still_lists_legacy_turns_first(conn):"""The merge key has to agree with `_conversation_order`, or the merged blockcontradicts its own "oldest first" header on an upgraded archive."""@@ -2109,7 +2361,8 @@ def test_merging_two_recall_queries_keeps_legacy_turns_in_the_order_they_were_sathem in whatever order the two queries happened to return them: the anchor's hitsfirst, 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."""+ oldest-first header on an upgraded database. Sorted through `_order_key` itself, since+ a copy of the key written out here passes until somebody edits one side of it."""from core.rag import conversation_archivemerged = [@@ -2118,21 +2371,53 @@ def test_merging_two_recall_queries_keeps_legacy_turns_in_the_order_they_were_sa{"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,+ key = lambda source: conversation_archive._order_key(+ source.get("turn"),+ source.get("createdAt"),+ source.get("documentRowid"),+ source.get("chunkIndex"),))assert [m["text"] for m in merged] == ["earlier", "later", "numbered"]+def test_both_recall_paths_order_by_the_same_key():+ """The single-query path reads snake_case columns and the merge reads camelCase keys;+ they are only the same key while both call `_order_key`.+ """+ from core.rag import conversation_archive+ for ordinal in (None, 0, 4):+ for created in ("", "2026-01-01T00:00:00Z"):+ for rowid in (None, 0, 12):+ for index in (None, 0, 3):+ row = {+ "archive_ordinal": ordinal,+ "created_at": created,+ "document_rowid": rowid,+ "chunk_index": index,+ }+ source = {+ "turn": ordinal,+ "createdAt": created,+ "documentRowid": rowid,+ "chunkIndex": index,+ }+ assert conversation_archive._conversation_order(row) == (+ conversation_archive._order_key(+ source.get("turn"),+ source.get("createdAt"),+ source.get("documentRowid"),+ source.get("chunkIndex"),+ )+ ), row++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."""+ `createdAt`, `documentRowid` or `chunkIndex`, so an unused-looking key is exactly the+ sort of thing a later cleanup deletes. This pins the producer. `documentRowid` most of+ all: it decides the order once the clock has stopped separating rows."""from types import SimpleNamespacefrom core.rag import tool@@ -2145,6 +2430,7 @@ def test_recall_sources_carry_the_fields_the_merge_orders_by():"archive_ordinal": None,"chunk_index": 2,"created_at": "2026-01-01T00:00:00Z",+ "document_rowid": 41,},}hits = [SimpleNamespace(chunk_id = "c1", score = 0.5)]@@ -2153,6 +2439,7 @@ def test_recall_sources_carry_the_fields_the_merge_orders_by():assert sources[0]["createdAt"] == "2026-01-01T00:00:00Z"assert sources[0]["chunkIndex"] == 2+ assert sources[0]["documentRowid"] == 41assert sources[0]["turn"] is Nonediff --git a/studio/backend/tests/test_rag_store.py b/studio/backend/tests/test_rag_store.pyindex 19c21930355..760c6eb91fc 100644--- a/studio/backend/tests/test_rag_store.py+++ b/studio/backend/tests/test_rag_store.py@@ -412,6 +412,191 @@ def test_a_quoted_function_word_survives_the_stopword_filter():assert len(quoted) == 1+def test_the_candidate_window_is_cut_in_conversation_order(rag_home, rag_conn):+ """Ordering the candidates cannot rescue a candidate the SELECT never returned.++ Past `_BRANCH_FILTER_MAX_CANDIDATES` the archive takes two windows, one from each end+ of the tied run, and the LIMIT that cuts them runs in SQL: this ORDER BY chooses which+ rows exist for the rest of recall. On a legacy archive the run is one flat tie (FTS5+ floors the IDF of the scope's shared term, every ordinal NULL, one clock tick over every+ `created_at`), so cutting at the chunk id cut at a `uuid4` and both true ends could go.++ The ids are rotated half a turn against conversation order, putting the conversation's+ ends dead centre of the id space: cut by id neither end survives, cut in conversation+ order both must. Cut by id the windows held conversation positions 50-92 and 7-49.+ """+ import types++ from core.rag import store++ conn = rag_conn+ scope = "convarchive_legacy"+ documents, per_document = 100, 3+ position_of = {}+ for position in range(documents):+ document_id = f"{(position + documents // 2) % documents:04d}-turn"+ position_of[document_id] = position+ store.create_document(+ conn,+ scope = scope,+ thread_id = "t",+ filename = "earlier turn",+ sha256 = f"h{position}",+ status = "completed",+ embedding_model = "m",+ archive_messages = 2,+ archive_ordinal = None,+ document_id = document_id,+ # One tick for the whole archive, the way a Windows host stamps a compaction.+ created_at = "2026-01-01T00:00:00+00:00",+ commit = False,+ )+ chunks = [+ types.SimpleNamespace(+ chunk_index = index,+ text = "ZQXTIEBREAK legacy turn statement",+ page_number = None,+ source_page_index = None,+ token_count = 5,+ char_count = 20,+ )+ for index in range(per_document)+ ]+ store.add_chunks(conn, scope, document_id, chunks, [[0.0] * 4] * per_document)+ conn.commit()++ # The premise: one score across the whole run, and more of it than the cap allows.+ everything = store.search_lexical(conn, scope, "ZQXTIEBREAK", documents * per_document + 10)+ assert len(everything) == documents * per_document+ assert len({score for _, score in everything}) == 1++ half = 128+ oldest = [+ c for c, _ in store.search_lexical(conn, scope, "ZQXTIEBREAK", half, oldest_first = True)+ ]+ newest = [+ c for c, _ in store.search_lexical(conn, scope, "ZQXTIEBREAK", half, newest_first = True)+ ]+ in_oldest = sorted({position_of[chunk.rsplit(":", 1)[0]] for chunk in oldest})+ in_newest = sorted({position_of[chunk.rsplit(":", 1)[0]] for chunk in newest})++ # Both true ends survive the cut, which is the whole point of taking two windows.+ assert 0 in in_oldest, in_oldest+ assert documents - 1 in in_newest, in_newest+ # And each window really is an END of the conversation, not a slice out of its middle.+ assert in_oldest[0] == 0 and in_oldest == list(range(len(in_oldest))), in_oldest+ assert in_newest[-1] == documents - 1, in_newest+ assert in_newest == list(range(documents - len(in_newest), documents)), in_newest+ # The two windows are disjoint, so the pair spans strictly more than either alone.+ assert not set(in_oldest) & set(in_newest)+++def test_the_candidate_order_survives_a_re_embed(rag_home, rag_conn):+ """The rowid this ORDER BY sorts on has to outlive a re-embed, so hold one and check.++ A re-embed deletes and re-inserts, the one operation that scrambles insertion order,+ and it survives only because `create_document` takes a `rowid` and the archive hands+ back the one it just deleted. A property of another module, asserted here because this+ query is what breaks if it stops holding.++ Rewritten in REVERSE, positions 4 then 3 then 2, so a fresh rowid would be wrongly+ ordered rather than merely different; rewriting in conversation order would renumber+ ascending and pass even with the carry deleted. Document ids descend as the+ conversation advances, so an id-space answer is the exact reverse of the right one.+ """+ import types++ from core.rag import store++ conn = rag_conn+ scope = "convarchive_reembed"+ turns = 5++ def _document_id(position):+ return f"{turns - position:04d}-turn"++ def _write(+ position,+ model,+ *,+ rowid = None,+ created = None,+ ordinal = None,+ ):+ store.create_document(+ conn,+ scope = scope,+ thread_id = "t",+ filename = "earlier turn",+ sha256 = f"h{position}",+ status = "completed",+ embedding_model = model,+ archive_messages = 2,+ archive_ordinal = ordinal,+ document_id = _document_id(position),+ # One tick for every turn, so `created_at` cannot separate them and the rowid+ # is the only record left of which was said first.+ created_at = created or "2026-01-01T00:00:00+00:00",+ rowid = rowid,+ commit = False,+ )+ store.add_chunks(+ conn,+ scope,+ _document_id(position),+ [+ types.SimpleNamespace(+ chunk_index = 0,+ text = "ZQXREEMBED legacy turn statement",+ page_number = None,+ source_page_index = None,+ token_count = 5,+ char_count = 20,+ )+ ],+ [[0.0] * 4],+ )++ for position in range(turns):+ _write(position, "old-model")+ conn.commit()++ def _positions(**direction):+ hits = store.search_lexical(conn, scope, "ZQXREEMBED", turns + 10, **direction)+ return [turns - int(chunk.rsplit(":", 1)[0].split("-")[0]) for chunk, _s in hits]++ assert _positions(oldest_first = True) == list(range(turns))+ rowids_before = dict(+ conn.execute("SELECT id, rowid FROM documents WHERE scope=?", (scope,)).fetchall()+ )++ for position in [4, 3, 2]:+ identity = store.document_rewrite_identity(conn, _document_id(position)) or {}+ store.delete_document(conn, _document_id(position), commit = False)+ _write(+ position,+ "new-model",+ rowid = identity.get("rowid"),+ created = identity.get("created_at"),+ ordinal = identity.get("archive_ordinal"),+ )+ conn.commit()++ # The premise, and the test is vacuous without it: the rows really were replaced.+ assert {+ row[0]+ for row in conn.execute("SELECT embedding_model FROM documents WHERE scope=?", (scope,))+ } == {"old-model", "new-model"}+ # The rowid the ORDER BY sorts on came across the rewrite unchanged.+ assert (+ dict(conn.execute("SELECT id, rowid FROM documents WHERE scope=?", (scope,)).fetchall())+ == rowids_before+ )+ # And so the window is still cut in conversation order, from either end.+ assert _positions(oldest_first = True) == list(range(turns))+ assert _positions(newest_first = True) == list(reversed(range(turns)))++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.