fix(session): bound retained history search results across pages

Discard raw replay pages after filtering, retaining only the requested latest matches while counting pages for stable global message indexes. Cover raw-page release and durable-source precedence across index rebuilds and restart.
This commit is contained in:
Xubin Ren committed 2026-09-15 14:11:59 +08:00
1 parent 151173c8ba
commit 8c4eb2c807
2 files changed
+124 -18

No files matched your search

+29 -18
View File
@@ -117,7 +117,7 @@ class WebuiSessionAccess:
return None
return self._sessions.read_session_metadata(session_key)
def _messages(self, session_key: str) -> list[SessionMessage]:
def _messages(self, session_key: str, *, needle: str, limit: int) -> list[SessionMessage]:
@cache
def load_session_messages() -> list[dict[str, Any]] | None:
payload = self._sessions.read_session_file(session_key)
@@ -130,10 +130,17 @@ class WebuiSessionAccess:
if isinstance(message, dict)
]
def matching(raw_messages: object) -> list[SessionMessage]:
return [
message for message in _visible_messages(raw_messages)
if not needle or needle in message["content"].casefold()
]
# The WebUI replay API returns one page, even when no limit is given.
# Session tools need the older pages too, including turns no longer in
# the compacted model history. Keep the UI's per-page replay budgets.
pages: list[list[object]] = []
matches: list[SessionMessage] = []
message_count = 0
before: str | None = None
while True:
thread = build_webui_thread_response(
@@ -143,11 +150,20 @@ class WebuiSessionAccess:
)
if thread is None:
if before is None:
return _visible_messages(load_session_messages())
return matching(load_session_messages())[-limit:]
break
raw_messages = thread.get("messages")
if isinstance(raw_messages, list):
pages.append(cast(list[object], raw_messages))
page_messages = cast(list[object], raw_messages)
message_count += len(page_messages)
remaining = limit - len(matches)
if remaining > 0:
page_matches = matching(page_messages)[-remaining:]
for message in page_matches:
# Index relative to the conversation's end until we
# know the total number of raw messages across pages.
message["message_index"] -= message_count
matches = page_matches + matches
raw_page = thread.get("page")
if not isinstance(raw_page, dict):
break
@@ -157,9 +173,11 @@ class WebuiSessionAccess:
break
before = cursor
# Page traversal is newest-first; filter after restoring chronological
# order so message indexes and the latest-match limits stay consistent.
return _visible_messages([message for page in reversed(pages) for message in page])
# Global indexes still require counting older pages, but retain only
# the requested matches, never the full conversation's raw traces.
for message in matches:
message["message_index"] += message_count
return matches
def search(
self,
@@ -202,11 +220,7 @@ class WebuiSessionAccess:
if needed <= 0:
break
key = cast(str, row["key"])
matches = [
message
for message in self._messages(key)
if needle in message["content"].casefold()
]
matches = self._messages(key, needle=needle, limit=2)
if not matches:
continue
updated = row.get("updated_at")
@@ -214,7 +228,7 @@ class WebuiSessionAccess:
"session_key": key,
"title": _row_title(row),
"updated_at": updated if isinstance(updated, str) else None,
"messages": matches[-2:],
"messages": matches,
}))
needed -= 1
return [item[1] for item in ranked[:limit]]
@@ -230,16 +244,13 @@ class WebuiSessionAccess:
payload = self._metadata(session_key, exclude_session_key=exclude_session_key)
if payload is None:
return None
messages = self._messages(session_key)
needle = query.casefold()
if needle:
messages = [message for message in messages if needle in message["content"].casefold()]
messages = self._messages(session_key, needle=query.casefold(), limit=limit)
updated = payload.get("updated_at")
return {
"session_key": session_key,
"title": _text(_session_metadata(payload).get("title")),
"updated_at": updated if isinstance(updated, str) else None,
"messages": messages[-limit:],
"messages": messages,
}
def normalize_mentions(
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
import weakref
import pytest
@@ -64,3 +65,97 @@ async def test_session_tools_find_old_matches_beyond_the_latest_page(
assert [item["content"] for item in matches] == [f"launch decision {i}" for i in expected]
assert [item["message_index"] for item in matches] == [i * 2 for i in expected]
@pytest.mark.asyncio
@pytest.mark.parametrize("query", ["", "visible"])
async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path, monkeypatch, query):
"""Tool results are tiny; do not retain every page's raw trace payloads."""
class TrackedMessage(dict):
pass
manager = SessionManager(tmp_path)
key = "websocket:history"
manager.save(manager.get_or_create(key))
refs = []
calls = []
def page(_key, *, before=None, **_kwargs):
# The immediately previous response can still be live while requesting
# the next one. Older raw messages must already have been released.
assert sum(ref() is not None for ref in refs) <= 5
index = int(before) if before is not None else 0
calls.append(index)
start = (9 - index) * 5
messages = [
TrackedMessage(role="user", content=f"visible {start}"),
TrackedMessage(role="tool", content="private tool result"),
TrackedMessage(role="assistant", content=f"visible {start + 2}"),
TrackedMessage(role="user", content="hidden", _hidden_history=True),
TrackedMessage(role="assistant", content=""),
]
refs.extend(weakref.ref(message) for message in messages)
return {"messages": messages, "page": {
"has_more_before": index < 9,
"before_cursor": str(index + 1) if index < 9 else None,
}}
monkeypatch.setattr("nanobot.webui.session_access.build_webui_thread_response", page)
with request_context(RequestContext(
channel="websocket", chat_id="current", session_key="websocket:current",
)):
result = json.loads(await ReadSessionTool(manager).execute(session_key=key, query=query))
expected = [30, 32, 35, 37, 40, 42, 45, 47]
assert [item["message_index"] for item in result["messages"]] == expected
assert [item["content"] for item in result["messages"]] == [f"visible {i}" for i in expected]
assert calls == list(range(10))
assert not any(ref() is not None for ref in refs)
@pytest.mark.asyncio
@pytest.mark.parametrize("state", ["canonical", "transcript", "mixed"])
async def test_session_tools_preserve_durable_sources_after_index_rebuild_and_restart(
tmp_path, monkeypatch, state,
):
webui_dir = tmp_path / "webui"
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: webui_dir)
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: webui_dir)
manager = SessionManager(tmp_path)
key = "websocket:history"
if state != "transcript":
session = manager.get_or_create(key)
session.metadata.update({"title": "Project notes", "title_user_edited": True})
session.add_message("user", "canonical needle")
manager.save(session)
if state != "canonical":
append_transcript_object(key, {
"event": "user", "chat_id": "history", "text": "display needle",
})
append_transcript_object(key, {"event": "turn_end", "chat_id": "history"})
def durable_files():
return {
path: path.read_bytes()
for root in (manager.sessions_dir, webui_dir)
for path in root.rglob("*.jsonl")
}
original = durable_files()
for _ in range(2):
# Read-only tools may rebuild derived indexes, not canonical records.
manager = SessionManager(tmp_path)
with request_context(RequestContext(
channel="websocket", chat_id="current", session_key="websocket:current",
)):
search = json.loads(await SearchSessionsTool(manager).execute(query="needle"))
read = await ReadSessionTool(manager).execute(session_key=key, query="needle")
assert [row["session_key"] for row in search["results"]] == [key]
if state == "transcript":
# Existing read/mention validation requires canonical metadata.
assert "session not found" in str(read)
assert manager.read_session_metadata(key) is None
else:
expected = "canonical needle" if state == "canonical" else "display needle"
assert [item["content"] for item in json.loads(read)["messages"]] == [expected]
assert durable_files() == original
(manager.sessions_dir / ".webui_session_index.json").unlink(missing_ok=True)