diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 66d9708a8..d708b136a 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -597,6 +597,10 @@ class SessionManager: """Load a detached session snapshot without populating the runtime cache.""" return self._store.load(key) + def read_session_version(self, key: str) -> tuple[str, int] | None: + """Return a cheap committed version, including delete/recreate identity.""" + return self._store.read_version(key) + def read_session_metadata(self, key: str) -> dict[str, Any] | None: """Read session metadata without loading the transcript.""" return cast(dict[str, Any] | None, self._store.read_metadata(key)) diff --git a/nanobot/session/sqlite_store.py b/nanobot/session/sqlite_store.py index 66866e038..3a489e77a 100644 --- a/nanobot/session/sqlite_store.py +++ b/nanobot/session/sqlite_store.py @@ -369,6 +369,12 @@ class SqliteSessionStore: if updated_at is not None: db.execute("UPDATE sessions SET updated_at=? WHERE key=?", (updated_at.isoformat(), key)) + def read_version(self, key: str) -> tuple[str, int] | None: + """Read the committed lifecycle and revision without decoding history or metadata.""" + with self.transaction(write=False) as db: + row = db.execute("SELECT generation, revision FROM sessions WHERE key=?", (key,)).fetchone() + return (str(row[0]), int(row[1])) if row is not None else None + def read_metadata(self, key: str) -> SessionMetadataPayload | None: with self.transaction(write=False) as db: row = db.execute("SELECT created_at, updated_at, metadata FROM sessions WHERE key=?", (key,)).fetchone() diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 90a1636de..9d3c54ced 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -12,6 +12,7 @@ import shutil import threading import time import uuid +from bisect import bisect_left from collections import OrderedDict from dataclasses import dataclass from datetime import datetime @@ -283,7 +284,6 @@ class TranscriptReplayStats: capped_by_bytes: bool = False capped_by_records: bool = False truncated_oversized_turn: bool = False - canonical_backfill_revision: str | None = None def _record_json_line(record: dict[str, Any]) -> str: @@ -1765,23 +1765,6 @@ def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...] return tuple(texts) -def _find_unique_session_turn( - session_signatures: list[str], - signature: str, - start: int, -) -> int | None: - if not signature: - return None - found: int | None = None - for index in range(start, len(session_signatures)): - if session_signatures[index] != signature: - continue - if found is not None: - return None - found = index - return found - - def _user_recovery_signature(event: dict[str, Any]) -> str: fields = { key: event[key] @@ -2520,6 +2503,7 @@ def build_webui_thread_response( augment_assistant_text: Callable[[str], str] | None = None, session_messages: list[dict[str, Any]] | None = None, session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None, + session_version_loader: Callable[[], tuple[str, int] | None] | None = None, active_turn_started_at: float | None = None, active_turn_id: str | None = None, active_turn_transcript_persistence_failed: bool = False, @@ -2540,13 +2524,21 @@ def build_webui_thread_response( ) if not lines and active_turn_started_at is None: return None - view = None + session_turns: list[_SessionBackfillTurn] | None = None + + def load_session_turns() -> list[_SessionBackfillTurn]: + nonlocal session_messages, session_turns + if session_turns is None: + if session_messages is None and session_messages_loader is not None: + session_messages = session_messages_loader() + session_turns = _session_backfill_turns(session_key, session_messages or []) + return session_turns + if _needs_user_event_backfill(lines): - view = _build_prompt_view( - session_key, session_messages=session_messages, - session_messages_loader=session_messages_loader, + view, _ = _prompt_view_snapshot( + session_key, session_turns_loader=load_session_turns, + session_version_loader=session_version_loader, ) - replay_stats.canonical_backfill_revision = view.canonical_revision recovered_lines: list[dict[str, Any]] = [] selected_turns = _split_transcript_turns(lines) for turn in selected_turns: @@ -2556,13 +2548,7 @@ def build_webui_thread_response( recovered_lines.extend(_with_backfilled_user(turn, user) if user is not None else turn) lines = recovered_lines if _needs_incomplete_turn_recovery(lines): - session_turns = view.session_turns if view is not None else None - if session_turns is None: - if session_messages is None and session_messages_loader is not None: - session_messages = session_messages_loader() - session_turns = _session_backfill_turns(session_key, session_messages or []) - replay_stats.canonical_backfill_revision = _canonical_backfill_revision(session_turns) - lines = _recover_incomplete_turns(lines, session_turns) + lines = _recover_incomplete_turns(lines, load_session_turns()) lines = _ensure_replay_identities(lines) payload: dict[str, Any] = { "schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, @@ -2617,10 +2603,9 @@ class _ChunkPromptView(NamedTuple): class _PromptView(NamedTuple): - prompts: list[PromptSummary] + prompts: tuple[PromptSummary, ...] backfilled_users: dict[int, dict[str, Any]] - session_turns: list[_SessionBackfillTurn] | None - canonical_revision: str | None + needs_canonical: bool def _assistant_signature_identity(signature: tuple[str, ...]) -> str: @@ -2629,15 +2614,9 @@ def _assistant_signature_identity(signature: tuple[str, ...]) -> str: return hashlib.sha256(json.dumps(signature, ensure_ascii=False).encode("utf-8")).hexdigest() -def _canonical_backfill_revision(turns: list[_SessionBackfillTurn]) -> str: - return hashlib.sha256(json.dumps(turns, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()[:32] - - -def webui_display_revision(revision: str | None, canonical_revision: str | None) -> str | None: - """Bind recovered display validators to the canonical snapshot actually used.""" - if revision is None or canonical_revision is None: - return revision - return hashlib.sha256(f"{revision}\0{canonical_revision}".encode("ascii")).hexdigest()[:32] +def prompt_index_revision(session_key: str, session_version: tuple[str, int] | None = None) -> str | None: + """Validate display inputs without reading canonical history or constructing a view.""" + return webui_transcript_revision(session_key, variant={"session_version": session_version}) def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> PromptSummary: @@ -2703,8 +2682,7 @@ def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: i def _build_prompt_view( session_key: str, *, - session_messages: list[dict[str, Any]] | None = None, - session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None, + session_turns_loader: Callable[[], list[_SessionBackfillTurn]] | None = None, ) -> _PromptView: raw_prompts: list[PromptSummary] = [] candidates: list[_BackfillCandidate] = [] @@ -2724,23 +2702,28 @@ def _build_prompt_view( candidates.extend(chunk.candidates) start += count session_turns = None - canonical_revision = None - if any(not candidate.has_user and candidate.signature for candidate in candidates): - if session_messages is None and session_messages_loader is not None: - session_messages = session_messages_loader() - session_turns = _session_backfill_turns(session_key, session_messages or []) - canonical_revision = _canonical_backfill_revision(session_turns) + needs_canonical = any(not candidate.has_user and candidate.signature for candidate in candidates) + if needs_canonical and session_turns_loader is not None: + session_turns = session_turns_loader() entries: list[tuple[int, PromptSummary, dict[str, Any] | None]] = [ (decode_transcript_cursor(prompt["cursor"]) or 0, prompt, None) for prompt in raw_prompts ] session_cursor = 0 - session_signatures = [_assistant_signature_identity(turn.assistant_signature) for turn in session_turns or []] + signature_positions: dict[str, list[int]] = {} + for position, turn in enumerate(session_turns or []): + signature_positions.setdefault(_assistant_signature_identity(turn.assistant_signature), []).append(position) for candidate in candidates: if not session_turns: break - match = _find_unique_session_turn(session_signatures, candidate.signature, session_cursor) - if match is None: + positions = signature_positions.get(candidate.signature) + if not candidate.signature or not positions: continue + # Preserve unique-in-suffix matching without rescanning canonical history + # for each transcript turn. Ambiguous answers still cannot backfill a user. + offset = bisect_left(positions, session_cursor) + if offset != len(positions) - 1: + continue + match = positions[offset] session_cursor = match + 1 if candidate.has_user: continue @@ -2753,7 +2736,7 @@ def _build_prompt_view( prompts.append(prompt) if user is not None: backfilled_users[ordinal] = user - return _PromptView(prompts, backfilled_users, session_turns, canonical_revision) + return _PromptView(tuple(prompts), backfilled_users, needs_canonical) def build_prompt_index( @@ -2762,15 +2745,55 @@ def build_prompt_index( session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None, ) -> list[PromptSummary]: """Read the display prompt directory; only missing-user turns load canonical history.""" - return _build_prompt_view(session_key, session_messages_loader=session_messages_loader).prompts + view, _ = _prompt_view_snapshot( + session_key, + session_turns_loader=lambda: _session_backfill_turns( + session_key, (session_messages_loader() if session_messages_loader else None) or [], + ), + ) + return list(view.prompts) -# Short-lived response snapshots share the chunk summaries; they do not retain -# full transcripts or write another durable representation of the conversation. -_PROMPT_SNAPSHOTS: OrderedDict[tuple[Path, str], tuple[PromptSummary, ...]] = OrderedDict() +# Bounded navigation snapshots retain summaries and recovered users, never full +# canonical answers, transcripts, or a second durable conversation representation. +_PROMPT_SNAPSHOTS: OrderedDict[tuple[Path, str], _PromptView] = OrderedDict() _PROMPT_SNAPSHOT_LOCK = threading.Lock() +def _prompt_view_snapshot( + session_key: str, + *, + session_turns_loader: Callable[[], list[_SessionBackfillTurn]] | None = None, + session_version_loader: Callable[[], tuple[str, int] | None] | None = None, +) -> tuple[_PromptView, str | None]: + path = webui_transcript_path(session_key) + + def read_revision() -> str | None: + version = session_version_loader() if session_version_loader is not None else None + return prompt_index_revision(session_key, version) + + revision = read_revision() + cache_key = (path, revision) if revision else None + if cache_key: + with _PROMPT_SNAPSHOT_LOCK: + cached = _PROMPT_SNAPSHOTS.get(cache_key) + if cached is not None and (not cached.needs_canonical or session_version_loader is not None): + _PROMPT_SNAPSHOTS.move_to_end(cache_key) + return cached, revision + view = _build_prompt_view(session_key, session_turns_loader=session_turns_loader) + # A caller supplying only messages cannot validate canonical changes. It may + # still use transcript chunk caches, but must not cache recovered snapshots. + if (view.needs_canonical and session_version_loader is None) or revision != read_revision(): + return view, None + if cache_key: + with _PROMPT_SNAPSHOT_LOCK: + _PROMPT_SNAPSHOTS[cache_key] = view + _PROMPT_SNAPSHOTS.move_to_end(cache_key) + while len(_PROMPT_SNAPSHOTS) > 8: + _PROMPT_SNAPSHOTS.popitem(last=False) + return view, revision + + class PromptIndexResponse(TypedDict): prompts: Sequence[PromptSummary] replaceFrom: int @@ -2782,26 +2805,26 @@ def prompt_index_response( previous_revision: str | None, *, session_messages_loader: Callable[[], list[dict[str, Any]] | None] | None = None, + session_version_loader: Callable[[], tuple[str, int] | None] | None = None, ) -> PromptIndexResponse: path = webui_transcript_path(session_key) - transcript_revision = webui_transcript_revision(session_key) - view = _build_prompt_view(session_key, session_messages_loader=session_messages_loader) - revision = webui_display_revision(transcript_revision, view.canonical_revision) - current = tuple(view.prompts) with _PROMPT_SNAPSHOT_LOCK: previous = _PROMPT_SNAPSHOTS.get((path, previous_revision)) if previous_revision else None - # Do not label a read made across an append/rotation as one stable revision. - if transcript_revision != webui_transcript_revision(session_key): + view, revision = _prompt_view_snapshot( + session_key, + session_turns_loader=lambda: _session_backfill_turns( + session_key, (session_messages_loader() if session_messages_loader else None) or [], + ), + session_version_loader=session_version_loader, + ) + current = view.prompts + if revision is None: return {"prompts": current, "replaceFrom": 0} - if revision: - with _PROMPT_SNAPSHOT_LOCK: - _PROMPT_SNAPSHOTS[path, revision] = current - _PROMPT_SNAPSHOTS.move_to_end((path, revision)) - while len(_PROMPT_SNAPSHOTS) > 8: - _PROMPT_SNAPSHOTS.popitem(last=False) + if previous is not None and previous_revision == revision: + return {"prompts": (), "replaceFrom": len(current), "revision": revision} replace_from = 0 if previous is not None: - for old, new in zip(previous, current): + for old, new in zip(previous.prompts, current): if old != new: break replace_from += 1 diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 9cc80fb42..11d34cbd2 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -134,7 +134,6 @@ from nanobot.webui.transcript import ( build_session_thread_response, build_webui_thread_response, build_webui_trace_detail_response, - webui_display_revision, webui_transcript_revision, ) from nanobot.webui.workspace_browser import browse_workspace_directories @@ -1055,8 +1054,11 @@ class GatewayHTTPHandler: if isinstance(message, dict) ] + def _read_session_version(self, key: str) -> tuple[str, int] | None: + return self.session_manager.read_session_version(key) if self.session_manager is not None else None + def _handle_prompt_index_get(self, request: WsRequest, key: str) -> Response: - from nanobot.webui.transcript import prompt_index_response + from nanobot.webui.transcript import prompt_index_response, prompt_index_revision if not self.check_api_token(request): return _http_error(401, "Unauthorized") @@ -1065,15 +1067,16 @@ class GatewayHTTPHandler: return _http_error(400, "invalid session key") if not _is_websocket_channel_session_key(decoded_key): return _http_error(404, "session not found") + revision = prompt_index_revision(decoded_key, self._read_session_version(decoded_key)) + etag = _quoted_etag(revision) if revision else None + if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag): + return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)]) query = _parse_query(request.path) data = prompt_index_response( decoded_key, _query_first(query, "since"), session_messages_loader=lambda: self._read_session_messages(decoded_key), + session_version_loader=lambda: self._read_session_version(decoded_key), ) - revision = data.get("revision") - etag = _quoted_etag(revision) if revision else None - if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag): - return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)]) headers = list(_NO_STORE_HEADERS) response_revision = data.get("revision") if response_revision: @@ -1207,11 +1210,6 @@ class GatewayHTTPHandler: active_turn_transcript_persistence_failed = ( websocket_turn_transcript_persistence_failed(chat_id) ) - session_metadata = ( - self.session_manager.read_session_metadata(decoded_key) - if self.session_manager is not None - else None - ) revision_variant = { "active_turn_id": active_turn_id, "active_turn_started_at": active_turn_started_at, @@ -1223,12 +1221,14 @@ class GatewayHTTPHandler: "direction": direction, "gateway_instance": self.tokens.instance_id, "limit": limit, - "session_updated_at": ( - session_metadata.get("updated_at") if session_metadata is not None else None - ), + "session_version": self._read_session_version(decoded_key), "workspace_scope": scope.payload(), } initial_revision = webui_transcript_revision(decoded_key, variant=revision_variant) + if initial_revision is not None: + etag = _quoted_etag(initial_revision) + if _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag): + return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)]) build_started = time.perf_counter() replay_stats = diagnostics.transcript if diagnostics is not None else TranscriptReplayStats() data = build_webui_thread_response( @@ -1240,6 +1240,7 @@ class GatewayHTTPHandler: workspace_path=scope.project_path, ), session_messages_loader=lambda: self._read_session_messages(decoded_key), + session_version_loader=lambda: self._read_session_version(decoded_key), active_turn_started_at=active_turn_started_at, active_turn_id=active_turn_id, active_turn_transcript_persistence_failed=( @@ -1256,26 +1257,12 @@ class GatewayHTTPHandler: if data is None: return _http_error(404, "webui thread not found") data["workspace_scope"] = scope.payload() - latest_session_metadata = ( - self.session_manager.read_session_metadata(decoded_key) - if self.session_manager is not None - else None - ) - revision_variant["session_updated_at"] = ( - latest_session_metadata.get("updated_at") - if latest_session_metadata is not None - else None - ) + revision_variant["session_version"] = self._read_session_version(decoded_key) final_revision = webui_transcript_revision(decoded_key, variant=revision_variant) response_headers = list(_NO_STORE_HEADERS) if final_revision is not None and final_revision == initial_revision: - display_revision = webui_display_revision(final_revision, replay_stats.canonical_backfill_revision) - assert display_revision is not None - etag = _quoted_etag(display_revision) - response_headers.append(("ETag", etag)) - if _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag): - return _http_response(b"", status=304, extra_headers=response_headers) - data["revision"] = display_revision + response_headers.append(("ETag", _quoted_etag(final_revision))) + data["revision"] = final_revision return _http_json_response( data, accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"), diff --git a/tests/session/test_sqlite_storage.py b/tests/session/test_sqlite_storage.py index 3748f83e2..f6c849272 100644 --- a/tests/session/test_sqlite_storage.py +++ b/tests/session/test_sqlite_storage.py @@ -760,3 +760,32 @@ async def test_delivery_requires_explicit_nonempty_generation(tmp_path): "current", ] await state.aclose() + + +def test_committed_version_tracks_history_and_session_replacement(tmp_path, monkeypatch): + manager = SessionManager(tmp_path) + key = "websocket:version" + assert manager.read_session_version(key) is None + session = manager.get_or_create(key) + session.messages = [{"role": "user", "content": "first"}] + manager.save(session) + first = manager.read_session_version(key) + assert first == (session.generation, session.revision) + # Administrative edits may preserve updated_at, so it is not a version token. + session.messages[0]["content"] = "edited" + manager.save(session) + second = manager.read_session_version(key) + assert second == (first[0], first[1] + 1) + assert manager.read_session_metadata(key)["updated_at"] == session.updated_at.isoformat() + manager.delete_session(key) + assert manager.read_session_version(key) is None + replacement = manager.get_or_create(key) + manager.save(replacement) + assert manager.read_session_version(key) == (replacement.generation, first[1]) + assert replacement.generation != first[0] + + def unexpected_decode(*args, **kwargs): + pytest.fail("version read decoded history or metadata") + + monkeypatch.setattr("nanobot.session.sqlite_store._object", unexpected_decode) + assert manager.read_session_version(key) == (replacement.generation, replacement.revision) diff --git a/tests/webui/test_prompt_index.py b/tests/webui/test_prompt_index.py index 7e7f6193c..06b38c8f5 100644 --- a/tests/webui/test_prompt_index.py +++ b/tests/webui/test_prompt_index.py @@ -192,8 +192,9 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time manager.save(session) changed = {} for path, previous in initial.items(): + request_path = path + "?since=" + json.loads(previous.body)["revision"] response = await gateway.http._dispatch_session_routes( - Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path, + Request(request_path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path, ) assert response.status_code == 200 assert response.headers["ETag"] != previous.headers["ETag"] @@ -203,3 +204,138 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time assert user["created_at_ms"] == prompt["createdAt"] == 1780394460000 assert user["projection_id"] == prompt["id"] assert prompt["id"] == json.loads(initial[base + "/prompts"].body)["prompts"][0]["id"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("missing_user", [False, True]) +async def test_cached_history_routes_skip_replay_and_canonical_reads(tmp_path, monkeypatch, missing_user): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:cached-history" + manager = SessionManager(tmp_path) + session = manager.get_or_create(key) + for i in range(3): + session.messages.extend([ + {"role": "user", "content": f"question {i}", "webui_turn_id": f"input-{i}"}, + {"role": "assistant", "content": f"answer {i}"}, + ]) + if not missing_user or i < 2: + transcript.append_transcript_object(key, {"event": "user", "text": f"question {i}", "turn_id": f"input-{i}"}) + transcript.append_transcript_object(key, {"event": "message", "text": f"answer {i}"}) + transcript.append_transcript_object(key, {"event": "turn_end"}) + manager.save(session) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=manager, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + auth = [("Authorization", "Bearer test-token")] + base = "/api/sessions/websocket%3Acached-history/webui-thread" + initial = {} + for path in (base + "?direction=latest&limit=2", base + "/prompts"): + response = await gateway.http._dispatch_session_routes(Request(path, Headers(auth)), path.split("?")[0]) + assert response.status_code == 200 + initial[path] = response + prompts = json.loads(initial[base + "/prompts"].body) + assert len(prompts["prompts"]) == 3 + + def unexpected_work(*args, **kwargs): + pytest.fail("unchanged history was rebuilt") + + monkeypatch.setattr(transcript, "_build_prompt_view", unexpected_work) + monkeypatch.setattr(transcript, "_read_transcript_file", unexpected_work) + monkeypatch.setattr(manager, "read_session_file", unexpected_work) + monkeypatch.setattr("nanobot.webui.ws_http.build_webui_thread_response", unexpected_work) + for path, previous in initial.items(): + conditional = path + ("&" if "?" in path else "?") + "since=" + json.loads(previous.body)["revision"] + response = await gateway.http._dispatch_session_routes( + Request(conditional, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path.split("?")[0], + ) + assert response.status_code == 304 and not response.body + # An ordinary directory read also reuses the view, with or without `since`. + for suffix in ("", "?since=" + prompts["revision"]): + response = await gateway.http._dispatch_session_routes(Request(base + "/prompts" + suffix, Headers(auth)), base + "/prompts") + assert response.status_code == 200 + data = json.loads(response.body) + assert data["prompts"] == ([] if suffix else prompts["prompts"]) + assert data["replaceFrom"] == (3 if suffix else 0) + # Eviction must not turn a valid conditional request into a replay either. + transcript._PROMPT_SNAPSHOTS.clear() + for path, previous in initial.items(): + response = await gateway.http._dispatch_session_routes( + Request(path, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path.split("?")[0], + ) + assert response.status_code == 304 and not response.body + + +@pytest.mark.asyncio +@pytest.mark.parametrize("endpoint", ["", "/prompts"]) +async def test_canonical_change_during_recovery_is_not_cached(tmp_path, monkeypatch, endpoint): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:racing-history" + manager = SessionManager(tmp_path) + session = manager.get_or_create(key) + session.messages = [ + {"role": "user", "content": "question", "timestamp": "2026-06-02T10:00:00+00:00"}, + {"role": "assistant", "content": "answer"}, + ] + manager.save(session) + for event in ({"event": "message", "text": "answer"}, {"event": "turn_end"}): + transcript.append_transcript_object(key, event) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=manager, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + auth = Headers([("Authorization", "Bearer test-token")]) + original_read = manager.read_session_file + changed = False + + def read_and_commit(key): + nonlocal changed + data = original_read(key) + if not changed: + changed = True + session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00" + manager.save(session) + return data + + monkeypatch.setattr(manager, "read_session_file", read_and_commit) + path = "/api/sessions/websocket%3Aracing-history/webui-thread" + endpoint + mixed = await gateway.http._dispatch_session_routes(Request(path, auth), path) + assert changed and mixed.status_code == 200 + assert "ETag" not in mixed.headers and "revision" not in json.loads(mixed.body) + current = await gateway.http._dispatch_session_routes(Request(path, auth), path) + assert current.status_code == 200 and current.headers["ETag"] + data = json.loads(current.body) + if endpoint: + assert data["prompts"][0]["createdAt"] == 1780394460000 + else: + user = next(event for event in data["events"] if event["event"] == "user_message") + assert user["created_at_ms"] == 1780394460000 + + +@pytest.mark.parametrize("with_anchor", [False, True]) +def test_indexed_backfill_preserves_unique_in_suffix_matching(tmp_path, monkeypatch, with_anchor): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:repeated-answers" + answers = ["same answer", "anchor answer", "same answer"] if with_anchor else ["same answer"] * 2 + messages = [] + for position, answer in enumerate(answers): + user = {"role": "user", "content": f"question {position}", "webui_turn_id": f"input-{position}"} + messages.extend([user, {"role": "assistant", "content": answer}]) + if position < len(answers) - 1: + transcript.append_transcript_object(key, {"event": "user", "text": user["content"], "turn_id": user["webui_turn_id"]}) + transcript.append_transcript_object(key, {"event": "message", "text": answer}) + transcript.append_transcript_object(key, {"event": "turn_end"}) + prompts = transcript.build_prompt_index(key, session_messages_loader=lambda: messages) + # A unique intervening answer advances the alignment past the first duplicate. + assert len(prompts) == (len(answers) if with_anchor else 1) + page = transcript.build_webui_thread_response(key, limit=1, session_messages=messages) + users = [event for event in page["events"] if event["event"] == "user_message"] + assert [user["text"] for user in users] == (["question 2"] if with_anchor else []) + if with_anchor: + assert users[0]["projection_id"] == prompts[-1]["id"]