diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index 1c9b139334..ecf9569884 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -1095,10 +1095,10 @@ const chatMessagePageSchema = z.object({ visible_page_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), }); -// A long original transcript can outlive the interactive request budget even -// when each verified page succeeds. Apply the same bounded read deadline to -// its pages and fresh source checks; caller cancellation still takes priority. -const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000; +// Apply one bounded read deadline to transcript pages and fresh source checks. +export const CHAT_HISTORY_READ_TIMEOUT_MS = 30_000; +const MAX_VERIFIED_HISTORY_MESSAGES = 50_000; +const MAX_VERIFIED_HISTORY_BASIS_CHARS = 6 + Math.ceil(MAX_VERIFIED_HISTORY_MESSAGES / 200) * 64; type ChatHistoryReadProgress = { first: ChatSessionSnapshot; @@ -1213,14 +1213,13 @@ async function readChatSessionHistory(session: ChatSessionSummary | string, sign } function historyBasisMatches(basis: string, count: number) { - const match = /^([1-9][0-9]{0,3}):([a-f0-9]+)$/.exec(basis); - return match !== null && count >= 1 && count <= 5000 && Number(match[1]) === count + const match = /^([1-9][0-9]{0,4}):([a-f0-9]+)$/.exec(basis); + return match !== null && count >= 1 && count <= MAX_VERIFIED_HISTORY_MESSAGES && Number(match[1]) === count && match[2].length === Math.ceil(count / 200) * 64; } function historyImageHeaders(linkImages: boolean): HeadersInit | undefined { - // The linked bytes are same-origin resources. A separately configured Chat - // server still uses the compatible inline representation. + // The linked bytes are same-origin resources; a separate Chat origin stays inline. return linkImages && !configuredChatOrigin ? {"X-LoopX-History-Images": "linked"} : undefined; } @@ -1240,7 +1239,7 @@ async function tryResumeChatSessionHistory(session: ChatSessionSummary, saved: C } if (!snapshot || snapshot.history_resume === undefined) return null; // Restart or older service. const proof = z.object({schema_version: z.literal("loopx_chat_history_resume_v1"), - base: z.literal(basis), next: z.string().max(1605)}).safeParse(snapshot.history_resume); + base: z.literal(basis), next: z.string().max(MAX_VERIFIED_HISTORY_BASIS_CHARS)}).safeParse(snapshot.history_resume); if (!proof.success || snapshot.ok !== true || snapshot.schema_version !== "loopx_chat_store_v1" || !snapshot.session || !sameHistorySource(snapshot.session, session) || Object.hasOwn(snapshot, "message_page") || !Array.isArray(snapshot.messages) || snapshot.messages.length > 200 diff --git a/apps/presentation/dashboard/src/data/use-bound-conversation.ts b/apps/presentation/dashboard/src/data/use-bound-conversation.ts index 9db4c27430..eb41157328 100644 --- a/apps/presentation/dashboard/src/data/use-bound-conversation.ts +++ b/apps/presentation/dashboard/src/data/use-bound-conversation.ts @@ -1,5 +1,5 @@ import { useEffect, useState } from "react"; -import { resolveBoundConversation, +import { CHAT_HISTORY_READ_TIMEOUT_MS, resolveBoundConversation, type BoundConversationTarget, type ChatSessionSummary, type BoundConversationSource } from "./chat"; /** Reads the source's title and executor. Admission remains with the Core owner. */ @@ -12,7 +12,7 @@ export function useBoundConversation(target: BoundConversationTarget | null, ena if (!enabled || bindingId === undefined || sessionId === undefined) return; let active = true; const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 5000); + const timeout = setTimeout(() => controller.abort(), CHAT_HISTORY_READ_TIMEOUT_MS); resolveBoundConversation({ bindingId, sessionId }, controller.signal) .then(({session, source}) => { if (!active) return; diff --git a/loopx/capabilities/manager_context/chat_history.py b/loopx/capabilities/manager_context/chat_history.py index ba068362ad..9d786acc18 100644 --- a/loopx/capabilities/manager_context/chat_history.py +++ b/loopx/capabilities/manager_context/chat_history.py @@ -2,15 +2,45 @@ from __future__ import annotations import base64 +from collections import OrderedDict import hashlib import json -from typing import Any +from threading import Lock from ...control_plane.content_digest import BARE_SHA256_PATTERN +MAX_KNOWN_HISTORY_MESSAGES = 50_000 +_SNAPSHOT_DIGEST_CACHE_MAX = 64 +_SNAPSHOT_DIGEST_LOCK = Lock() +_SNAPSHOT_DIGEST_CACHE: OrderedDict[tuple[str, str | None, bytes, bytes, int], str] = OrderedDict() -def page_chat_messages(session_id: str, messages: list[dict[str, Any]], *, - limit: int, cursor: str | None = None, turn_id: str | None = None) -> dict[str, Any]: + +def _snapshot_prefix_digest( + session_id: str, turn_id: str | None, messages: list[dict[str, object]], total: int, +) -> str: + journal_sha256 = getattr(messages, "journal_sha256", None) + markers_sha256 = getattr(messages, "markers_sha256", b"") + cache_key: tuple[str, str | None, bytes, bytes, int] | None = None + if isinstance(journal_sha256, bytes) and isinstance(markers_sha256, bytes): + cache_key = (session_id, turn_id, journal_sha256, markers_sha256, total) + with _SNAPSHOT_DIGEST_LOCK: + cached = _SNAPSHOT_DIGEST_CACHE.get(cache_key) + if cached is not None: + _SNAPSHOT_DIGEST_CACHE.move_to_end(cache_key) + return cached + digest = hashlib.sha256(json.dumps(messages[:total], sort_keys=True, + ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() + if cache_key is not None: + with _SNAPSHOT_DIGEST_LOCK: + _SNAPSHOT_DIGEST_CACHE[cache_key] = digest + _SNAPSHOT_DIGEST_CACHE.move_to_end(cache_key) + while len(_SNAPSHOT_DIGEST_CACHE) > _SNAPSHOT_DIGEST_CACHE_MAX: + _SNAPSHOT_DIGEST_CACHE.popitem(last=False) + return digest + + +def page_chat_messages(session_id: str, messages: list[dict[str, object]], *, + limit: int, cursor: str | None = None, turn_id: str | None = None) -> dict[str, object]: """Page an append-ordered frozen prefix; a cursor is a read hint, not authority.""" if type(limit) is not int or not 1 <= limit <= 200: raise ValueError("message_limit must be between 1 and 200") @@ -31,8 +61,7 @@ def page_chat_messages(session_id: str, messages: list[dict[str, Any]], *, raise ValueError() except (ValueError, TypeError, UnicodeDecodeError) as exc: raise ValueError("invalid history cursor") from exc - digest = hashlib.sha256(json.dumps(messages[:total], sort_keys=True, - ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() + digest = _snapshot_prefix_digest(session_id, turn_id, messages, total) if expected_digest is not None and expected_digest != digest: raise ValueError("history cursor source changed; restart the read") end = min(offset + limit, total) diff --git a/loopx/capabilities/manager_context/presentation.py b/loopx/capabilities/manager_context/presentation.py index 8d53b308ce..910005daf7 100644 --- a/loopx/capabilities/manager_context/presentation.py +++ b/loopx/capabilities/manager_context/presentation.py @@ -1,5 +1,10 @@ """Owner-local collaboration readback in the conversation that delegated it.""" +from collections import OrderedDict +from pathlib import Path +import sys +from threading import Lock + from . import _read, _root, _hash from .tracking import _entry, _receipt from .roundtrip import reply_status @@ -15,6 +20,51 @@ ) from ...control_plane.collaboration.inbox import controlled_request_readback +_TERMINAL_STATUSES = frozenset({"completed", "interrupted", "timed_out", "failed"}) +_PLAIN_TURN_CACHE_MAX = 16384 +_PLAIN_TURN_LOCK = Lock() +_PLAIN_TURN_FINGERPRINTS: OrderedDict[Path, tuple[int, int, int, int, int]] = OrderedDict() + + +def _load_collaboration_turn(store, session_id: str, turn_id: str): + turn_path_fn = getattr(store, "_turn_path", None) + fp: tuple[int, int, int, int, int] | None = None + path: Path | None = None + if sys.platform != "win32" and callable(turn_path_fn): + try: + candidate = turn_path_fn(session_id, turn_id) + if isinstance(candidate, Path): + path = candidate + st = path.stat() + fp = (st.st_dev, st.st_ino, st.st_mtime_ns, st.st_ctime_ns, st.st_size) + with _PLAIN_TURN_LOCK: + if _PLAIN_TURN_FINGERPRINTS.get(path) == fp: + _PLAIN_TURN_FINGERPRINTS.move_to_end(path) + return {"response": {}} + except (OSError, ValueError): + fp = None + load_turn = getattr(store, "load_turn") + turn = load_turn(session_id, turn_id) or {} + if path is not None and fp is not None and isinstance(turn, dict): + response = turn.get("response") + if ( + turn.get("status") in _TERMINAL_STATUSES + and isinstance(response, dict) + and response.get("context_handoff_receipts") is None + and not response.get("context_handoff_receipt") + ): + try: + st_after = path.stat() + if (st_after.st_dev, st_after.st_ino, st_after.st_mtime_ns, st_after.st_ctime_ns, st_after.st_size) == fp: + with _PLAIN_TURN_LOCK: + _PLAIN_TURN_FINGERPRINTS[path] = fp + _PLAIN_TURN_FINGERPRINTS.move_to_end(path) + while len(_PLAIN_TURN_FINGERPRINTS) > _PLAIN_TURN_CACHE_MAX: + _PLAIN_TURN_FINGERPRINTS.popitem(last=False) + except OSError: + pass + return turn + def project_collaboration( store, root, session_id, messages, *, registry, context_messages=None @@ -50,7 +100,7 @@ def project_collaboration( for message in messages: tid = message.get("turn_id") if tid and carriers.get(tid) == message.get("message_id") and tid not in turns: - turns[tid] = store.load_turn(session_id, tid) or {} + turns[tid] = _load_collaboration_turn(store, session_id, tid) missing_clients = { turn.get("client_turn_id") for turn in turns.values() diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py index 82c11ee307..96a14a4225 100644 --- a/loopx/capabilities/manager_context/roundtrip.py +++ b/loopx/capabilities/manager_context/roundtrip.py @@ -16,6 +16,7 @@ from os import scandir from pathlib import Path from contextlib import contextmanager, ExitStack, nullcontext +from copy import deepcopy from urllib.parse import quote from datetime import datetime, timezone @@ -465,8 +466,11 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, strict = message_limit is not None or resume_from is not None or report_message_id is not None # Read the status first: terminal completion persists its answer before # publishing completed. An older message prefix must not appear final. - snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict - else store.session_snapshot(session_id)) + snapshot = ( + store.session_snapshot(session_id, strict_messages=True, copy_messages=False) + if strict and hasattr(store, "_paged_history_messages") + else store.session_snapshot(session_id, strict_messages=True) if strict else store.session_snapshot(session_id) + ) report_context = None if report_message_id is not None: snapshot["messages"], report_context = _saved_answer_rows(snapshot["messages"], report_message_id, turn_id) @@ -475,17 +479,12 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, elif turn is not None: status = turn["status"] snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES} - # Failure records persist the reason with the status, before appending the message. error = turn.get("error") if include_turn_error and status in {"failed", "timed_out"} and isinstance(error, str) and error.strip(): snapshot["selected_turn"]["error"] = error snapshot["active_turn"] = None - # OriginalRequest already displays only this Turn. Select it before - # paging/projection, retaining every message and the strict journal read. snapshot["messages"] = [row for row in snapshot["messages"] if row.get("turn_id") == turn_id] elif project_history_messages is not None: - # Extension-owned, presentation-only rows must join the frozen page - # prefix. A selected Turn only reads its canonical messages. snapshot["messages"] = project_history_messages(snapshot["messages"]) if resume_from is not None and not 0 <= len(snapshot["messages"]) - resume_from <= 200: return None # Bound the complete visible stream, including provider-only notices. @@ -500,19 +499,12 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, root, session_id, snapshot["messages"], source_store=store, registry=registry ) from .presentation import project_collaboration - # Use the frozen context to choose the carrier, projecting only this page. - # A question and answer can straddle pages without duplicating a commitment - # or re-reading every off-page Turn for each page. projected = project_collaboration(store, root, session_id, snapshot["messages"], registry=registry, context_messages=context_messages) if report_message_id is not None: - # Collaboration may include the original receipt carrier. The saved - # answer only exposes its precise answer and the question it displays. visible_ids = {row.get("message_id") for row in snapshot["messages"]} projected = [row for row in projected if row.get("message_id") in visible_ids] - snapshot["messages"] = projected - # Provider-owned history joins the selected page at the composition root. - # Core capabilities never import an extension projection sink. + snapshot["messages"] = deepcopy(projected) if (page is not None or report_message_id is not None) else projected if page is not None: snapshot["message_page"] = page["message_page"] return snapshot @@ -521,6 +513,7 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, def parse_chat_history_selection(query): """Validate one HTTP history selection before any recovery observation.""" + from .chat_history import MAX_KNOWN_HISTORY_MESSAGES keys = set(query) report = "report_message_id" in keys if (keys - {"message_limit", "message_cursor", "turn_id", "known_history", @@ -543,10 +536,10 @@ def parse_chat_history_selection(query): if limit != 200 or "turn_id" in query or "message_cursor" in query: raise ValueError("invalid history resume arguments") count_text, _, proof = basis.partition(":") - if not re.fullmatch(r"[1-9][0-9]{0,3}", count_text): + if not re.fullmatch(r"[1-9][0-9]{0,4}", count_text): raise ValueError("invalid known history proof") count = int(count_text) - if count > 5000 or len(proof) != ((count + 199) // 200) * 64 or not re.fullmatch(r"[a-f0-9]+", proof): + if count > MAX_KNOWN_HISTORY_MESSAGES or len(proof) != ((count + 199) // 200) * 64 or not re.fullmatch(r"[a-f0-9]+", proof): raise ValueError("invalid known history proof") parsed_basis = (basis, count, proof) return {"message_limit": limit, "message_cursor": query.get("message_cursor", [None])[0], @@ -587,6 +580,7 @@ def _visible_history_page_digest(session_id, offset, messages): def read_chat_history_selection(root, store, session_id, *, registry, selection, project_provider, project_history_messages=None): """Compose the same provider projections for page reads and suffix proof.""" + from .chat_history import MAX_KNOWN_HISTORY_MESSAGES basis = selection["known_history"] if basis is None: snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry, @@ -597,7 +591,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection, snapshot["messages"] = project_provider(snapshot["messages"]) if selection["message_limit"] == 200 and selection["turn_id"] is None: page = snapshot["message_page"] - if 1 <= page["total"] <= 5000: + if 1 <= page["total"] <= MAX_KNOWN_HISTORY_MESSAGES: page["visible_page_sha256"] = _visible_history_page_digest( session_id, page["offset"], snapshot["messages"]) return snapshot @@ -607,7 +601,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection, restart = {"ok": True, **resume, "status": "restart"} snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry, resume_from=count, project_history_messages=project_history_messages) - if snapshot is None or len(snapshot["messages"]) > 5000: + if snapshot is None or len(snapshot["messages"]) > MAX_KNOWN_HISTORY_MESSAGES: return restart messages = project_provider(snapshot["messages"]) current_prefix = "".join( @@ -616,12 +610,11 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection, if current_prefix != proof: return restart total = len(messages) - # The old last page may have been short; earlier pages were just verified. unchanged = count if total == count else count - count % 200 next_proof = proof[:((unchanged + 199) // 200) * 64] + "".join( _visible_history_page_digest(session_id, offset, messages[offset:offset + 200]) for offset in range(unchanged, total, 200)) - return {**snapshot, "messages": messages[count:], "history_resume": { + return {**snapshot, "messages": deepcopy(messages[count:]), "history_resume": { **resume, "base": basis, "next": f"{total}:{next_proof}", }} diff --git a/loopx/capabilities/native_chat/queue_api.py b/loopx/capabilities/native_chat/queue_api.py index 8ec5c697be..cbc26443b2 100644 --- a/loopx/capabilities/native_chat/queue_api.py +++ b/loopx/capabilities/native_chat/queue_api.py @@ -98,6 +98,8 @@ def _session_queue(self, session_id: str) -> None: self._send_error("chat session was not found", status=404) except ValueError as exc: self._send_error(str(exc), status=400) + except (BrokenPipeError, ConnectionResetError): + return except (OSError, RuntimeError): self._send_error("Queued messages are temporarily unavailable", status=503) diff --git a/loopx/chat/journal.py b/loopx/chat/journal.py index 5bc29b27fb..0e7ff961c6 100644 --- a/loopx/chat/journal.py +++ b/loopx/chat/journal.py @@ -4,6 +4,18 @@ from typing import Any +class CachedJournalRows(list): # type: ignore[type-arg] + """Immutable cached transcript rows tagged with their verified byte digest.""" + + journal_sha256: bytes + markers_sha256: bytes + + def __init__(self, rows: list[object], *, journal_sha256: bytes, markers_sha256: bytes = b"") -> None: + super().__init__(rows) + self.journal_sha256 = journal_sha256 + self.markers_sha256 = markers_sha256 + + def decode_chat_journal(lines: list[bytes], *, strict: bool) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for line in lines: diff --git a/loopx/chat_server.py b/loopx/chat_server.py index 4c16ae2043..e75d9e8e2e 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -762,15 +762,15 @@ def _session_snapshot(self, session_id: str) -> None: self._send_error("chat session was not found", status=404) except ValueError as exc: self._send_error(str(exc), status=400) + except (BrokenPipeError, ConnectionResetError): + return except OSError: self._send_error("Chat history is temporarily unavailable", status=503) def _list_sessions(self) -> None: query = parse_qs(urlparse(self.path).query, keep_blank_values=True) if "managed_agent_id" in query: - # Agent registration is distinct from the executor's agent_id. - # Reuse Core's exact original identity admission; an older service - # ignoring this selector must not look like a successful discovery. + # Agent registration is distinct from the executor's agent_id. Reuse Core's exact identity admission. from .capabilities.native_chat.steward_managed_mode import StewardManagedMode, managed_session_identity if (set(query) != {"goal_id", "managed_agent_id"} or any(len(values) != 1 or not values[0] for values in query.values())): diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 8163b41dc2..9caedfc0ff 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -26,7 +26,7 @@ normalize_session_model_settings, session_model_settings_supported, normalize_session_model_changes, ) from .chat.event_cache import ChatEventCache, ChatEventStreamMixin -from .chat.journal import decode_chat_journal +from .chat.journal import CachedJournalRows, decode_chat_journal from .chat.ingress import ( ChatIngressStore, SESSION_QUEUE_MAX_PENDING as SESSION_QUEUE_MAX_PENDING, @@ -57,10 +57,10 @@ _OPAQUE_ID = re.compile(r"^[A-Za-z0-9._-]{1,160}$") _SESSION_RELEASE_UNSET = object() -# Keep both active conversation journals warm within the original total budget. -_PAGED_HISTORY_MAX_SESSIONS = 2 -_PAGED_HISTORY_MAX_BYTES = 64 * 1024 * 1024 -_PAGED_HISTORY_MAX_ROWS = 8192 +# Keep active steward and project conversation journals warm across multi-MB image histories. +_PAGED_HISTORY_MAX_SESSIONS = 4 +_PAGED_HISTORY_MAX_BYTES = 256 * 1024 * 1024 +_PAGED_HISTORY_MAX_ROWS = 65536 def utc_now() -> str: @@ -845,7 +845,7 @@ def _paged_history_messages( rows = decode_chat_journal(lines, strict=True) if digest is not None and len(rows) <= _PAGED_HISTORY_MAX_ROWS: with suppress(RecursionError): - saved = deepcopy(rows) + saved = CachedJournalRows(deepcopy(rows), journal_sha256=digest) with self._paged_history_lock: self._paged_history[session_id] = (digest, size, saved) self._paged_history.move_to_end(session_id) @@ -1685,23 +1685,22 @@ def public_session(self, payload: dict[str, Any]) -> dict[str, Any]: and payload.get("status") in RESUMABLE_SESSION_STATES, } - def session_snapshot(self, session_id: str, *, strict_messages: bool = False) -> dict[str, Any]: + def session_snapshot( + self, session_id: str, *, strict_messages: bool = False, copy_messages: bool = True, + ) -> dict[str, Any]: payload = self.load_session(session_id) if payload is None: raise KeyError("chat session was not found") - active_turn = None - if payload.get("active_turn_id"): - active_turn = self.load_turn(session_id, str(payload["active_turn_id"])) - if active_turn is not None: - active_turn = { - key: value - for key, value in active_turn.items() - if key != "_acceptance" - } + active_turn = self.load_turn(session_id, str(payload["active_turn_id"])) if payload.get("active_turn_id") else None + if active_turn is not None: + active_turn = {key: value for key, value in active_turn.items() if key != "_acceptance"} return { "ok": True, "schema_version": CHAT_STORE_SCHEMA_VERSION, "session": self.public_session(payload), - "messages": self._paged_history_messages(session_id) if strict_messages else self.messages(session_id), + "messages": ( + self._paged_history_messages(session_id, copy_cached=copy_messages) + if strict_messages else self.messages(session_id) + ), "active_turn": active_turn, } diff --git a/loopx/control_plane/collaboration/source_chat_observation.py b/loopx/control_plane/collaboration/source_chat_observation.py index 466b2eb984..8dff1ce0db 100644 --- a/loopx/control_plane/collaboration/source_chat_observation.py +++ b/loopx/control_plane/collaboration/source_chat_observation.py @@ -33,12 +33,20 @@ def original_turn_reader(store: ChatSessionStore, session_id: str) -> Callable[[ """ turns_dir = store._session_dir(session_id) / "turns" paths: dict[str, Path] = {} - for path in turns_dir.glob("*.json") if turns_dir.is_dir() else []: - if path.name.endswith(".events.json"): - continue - client_id = _read_json(path).get("client_turn_id") - if isinstance(client_id, str): - paths.setdefault(client_id, path) + if turns_dir.is_dir(): + discovery = getattr(store, "_turn_discovery_rows", None) + if callable(discovery): + for path, observation, _ in discovery(session_id, turns_dir, _read_json): + client_id = observation.get("client_turn_id") if isinstance(observation, dict) else None + if isinstance(client_id, str): + paths.setdefault(client_id, path) + else: + for path in turns_dir.glob("*.json"): + if path.name.endswith(".events.json"): + continue + client_id = _read_json(path).get("client_turn_id") + if isinstance(client_id, str): + paths.setdefault(client_id, path) def read(client_turn_id: str) -> dict[str, Any] | None: path = paths.get(client_turn_id) diff --git a/loopx/extensions/lark/private_web_projection.py b/loopx/extensions/lark/private_web_projection.py index d3ee874411..0d0659e859 100644 --- a/loopx/extensions/lark/private_web_projection.py +++ b/loopx/extensions/lark/private_web_projection.py @@ -182,19 +182,15 @@ def summary(summary: dict[str, Any], markers: list[dict[str, Any]]) -> dict[str, revision = summary.get("transcript_revision") if not revision or not markers: return summary - digest = hashlib.sha256(json.dumps(markers, sort_keys=True, ensure_ascii=False, - separators=(",", ":")).encode("utf-8")).hexdigest() + digest = hashlib.sha256(json.dumps(markers, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() return {**summary, "transcript_revision": f"{revision}.lark.{digest}"} @staticmethod def insert(messages: list[dict[str, Any]], markers: list[dict[str, Any]]) -> list[dict[str, Any]]: if not markers: return messages - # Keep canonical append order and insert presentation rows by original - # time before paging. A late insertion must invalidate the old prefix. ids = {row.get("message_id") for row in messages} - pending = [(_history_timestamp(row["created_at"]), row) for row in reversed(markers) - if row["message_id"] not in ids] + pending = [(_history_timestamp(row["created_at"]), row) for row in reversed(markers) if row["message_id"] not in ids] projected = [] for message in messages: try: @@ -204,7 +200,13 @@ def insert(messages: list[dict[str, Any]], markers: list[dict[str, Any]]) -> lis while pending and stamp is not None and pending[-1][0] < stamp: projected.append(pending.pop()[1]) projected.append(message) - return projected + [row[1] for row in reversed(pending)] + merged = projected + [row[1] for row in reversed(pending)] + journal_sha = getattr(messages, "journal_sha256", None) + if not isinstance(journal_sha, bytes): + return merged + from ...chat.journal import CachedJournalRows + raw_markers = json.dumps(markers, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + return CachedJournalRows(merged, journal_sha256=journal_sha, markers_sha256=hashlib.sha256(raw_markers).digest()) class PrivateWebProjectionMixin: diff --git a/loopx/presentation/request_control_api.py b/loopx/presentation/request_control_api.py index f879469f93..466f5e4959 100644 --- a/loopx/presentation/request_control_api.py +++ b/loopx/presentation/request_control_api.py @@ -155,6 +155,8 @@ def validate_source(source): if (source_basis(current), current_goals, current_core) != proof: raise ValueError("conversation authorization changed during read") self._send_json(_operator_payload(result)) + except (BrokenPipeError, ConnectionResetError): + return except (OSError, ValueError, TypeError, KeyError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: self._send_error(redact_local_paths(str(exc)), status=400, error_code="request_inventory_unavailable") diff --git a/tests/test_steward_history_scale.py b/tests/test_steward_history_scale.py new file mode 100644 index 0000000000..d8ea0e8b5b --- /dev/null +++ b/tests/test_steward_history_scale.py @@ -0,0 +1,307 @@ +from __future__ import annotations + +import json +from pathlib import Path +import pytest + +from loopx.capabilities.manager_context.chat_history import ( + MAX_KNOWN_HISTORY_MESSAGES, + page_chat_messages, +) +from loopx.capabilities.manager_context.presentation import project_collaboration +from loopx.capabilities.manager_context.roundtrip import ( + parse_chat_history_selection, + read_chat_history_selection, +) +from loopx.capabilities.native_chat.queue_api import ChatQueueRequestMixin +from loopx.chat_server import ChatRequestHandler +from loopx.chat_store import ChatSessionStore, utc_now +from loopx.control_plane.collaboration.source_chat_observation import original_turn_reader +from loopx.control_plane.effect_runtime import effect_runtime_request_scope +from loopx.extensions.lark.private_web_projection import PrivateUnsupportedMediaHistory +from loopx.presentation.request_control_api import RequestControlMixin + + +def _create_steward_session(tmp_path: Path) -> tuple[Path, Path, ChatSessionStore, str]: + runtime_root = tmp_path / "runtime" + registry = tmp_path / "registry.json" + registry.write_text(json.dumps({"goals": []}, ensure_ascii=False), encoding="utf-8") + store = ChatSessionStore(runtime_root) + binding_id = "b" * 24 + source_ref = "c" * 24 + saved = { + "kind": "bound_steward", + "project_ref": "a" * 24, + "workspace_path": str(tmp_path), + "audience": "bound_owner", + "grant": "portfolio_read", + "binding_id": binding_id, + "provider_ref": "d" * 24, + "operator_ref": "e" * 24, + "source_ref": source_ref, + "goal_ids": [], + } + session = store.create_session( + goal_id="loopx-manager", + agent_id="antigravity", + adapter_kind="antigravity_ls", + upstream_thread_id="steward-thread-scale", + channel_id=f"manager.external.native.{binding_id}.{source_ref}", + steward_context=saved, + ) + return runtime_root, registry, store, str(session["session_id"]) + + +def test_history_paging_and_known_history_resume_above_5000_messages(tmp_path: Path) -> None: + runtime_root, registry, store, sid = _create_steward_session(tmp_path) + journal_path = store.sessions_root / sid / "messages.jsonl" + now = utc_now() + initial_count = 5_205 + raw_lines = [ + json.dumps( + { + "schema_version": "loopx_chat_message_v1", + "message_id": f"msg-{idx:05d}", + "turn_id": None, + "role": "user" if idx % 2 == 0 else "agent", + "text": f"Historical entry {idx}", + "created_at": now, + }, + separators=(",", ":"), + ) + for idx in range(initial_count) + ] + journal_path.write_text("\n".join(raw_lines) + "\n", encoding="utf-8") + + assert MAX_KNOWN_HISTORY_MESSAGES >= 50_000 + digests: list[str] = [] + collected: list[dict[str, object]] = [] + cursor: str | None = None + with effect_runtime_request_scope(): + while True: + query = {"message_limit": ["200"]} + if cursor is not None: + query["message_cursor"] = [cursor] + selection = parse_chat_history_selection(query) + payload = read_chat_history_selection( + runtime_root, + store, + sid, + registry=registry, + selection=selection, + project_provider=lambda rows: rows, + ) + page = payload["message_page"] + assert isinstance(page.get("visible_page_sha256"), str) + digests.append(page["visible_page_sha256"]) + collected.extend(payload["messages"]) + cursor = page["next_cursor"] + if cursor is None: + break + + assert len(collected) == initial_count + assert len(digests) == 27 + basis = f"{initial_count}:{''.join(digests)}" + + store.append_message(sid, role="user", message_id="msg-tail-1", text="Tail question") + store.append_message(sid, role="agent", message_id="msg-tail-2", text="Tail answer") + + with effect_runtime_request_scope(): + resumed = read_chat_history_selection( + runtime_root, + store, + sid, + registry=registry, + selection=parse_chat_history_selection({"message_limit": ["200"], "known_history": [basis]}), + project_provider=lambda rows: rows, + ) + assert [row["message_id"] for row in resumed["messages"]] == ["msg-tail-1", "msg-tail-2"] + next_basis = resumed["history_resume"]["next"] + assert next_basis.startswith(f"{initial_count + 2}:") + + # Mutating an earlier row on disk invalidates both cached journal rows and known_history proof. + rewritten = journal_path.read_text(encoding="utf-8").replace("Historical entry 0", "Changed entry 0", 1) + journal_path.write_text(rewritten, encoding="utf-8") + with effect_runtime_request_scope(): + restarted = read_chat_history_selection( + runtime_root, + store, + sid, + registry=registry, + selection=parse_chat_history_selection({"message_limit": ["200"], "known_history": [next_basis]}), + project_provider=lambda rows: rows, + ) + assert restarted == { + "ok": True, + "schema_version": "loopx_chat_history_resume_v1", + "status": "restart", + } + + +def test_cached_journal_rows_invalidate_on_marker_insertion_and_bytes_change(tmp_path: Path) -> None: + _, _, store, sid = _create_steward_session(tmp_path) + store.append_message(sid, role="user", message_id="m1", text="one") + store.append_message(sid, role="agent", message_id="m2", text="two") + store.append_message(sid, role="user", message_id="m3", text="three") + + cached = store.session_snapshot(sid, strict_messages=True, copy_messages=False)["messages"] + first_page = page_chat_messages(sid, cached, limit=2) + second_page = page_chat_messages(sid, cached, limit=2, cursor=first_page["message_page"]["next_cursor"]) + assert [row["message_id"] for row in second_page["messages"]] == ["m3"] + + markers = [ + { + "schema_version": "loopx_chat_message_v1", + "message_id": "lark.unsupported.000000000000000000000001", + "turn_id": None, + "role": "error", + "origin": "lark", + "text": "Unsupported media", + "created_at": "2026-01-01T00:00:00.000000+00:00", + } + ] + with_markers = PrivateUnsupportedMediaHistory.insert(cached, markers) + with pytest.raises(ValueError, match="cursor"): + page_chat_messages(sid, with_markers, limit=2, cursor=first_page["message_page"]["next_cursor"]) + + +def test_plain_terminal_turn_cache_and_original_turn_reader_reuse_stat_fingerprints( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + runtime_root, registry, store, _ = _create_steward_session(tmp_path) + manager_session = store.create_session( + goal_id="loopx-manager", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id="manager-thread-scale", + channel_id="manager", + ) + sid = str(manager_session["session_id"]) + turns_dir = store.sessions_root / sid / "turns" + turns_dir.mkdir(parents=True, exist_ok=True) + now = utc_now() + for idx in range(6): + tid = f"turn-{idx}" + (turns_dir / f"{tid}.json").write_text( + json.dumps( + { + "schema_version": "loopx_chat_turn_state_v1", + "session_id": sid, + "turn_id": tid, + "client_turn_id": f"client-{idx}", + "status": "completed", + "message": f"question {idx}", + "response": {"message": f"answer {idx}", "proposals": []}, + "created_at": now, + "completed_at": now, + } + ), + encoding="utf-8", + ) + store.append_message(sid, role="agent", turn_id=tid, message_id=f"ans-{idx}", text=f"answer {idx}") + + messages = store.messages(sid, strict=True) + load_calls = 0 + original_load_turn = store.load_turn + + def counting_load_turn(session_id: str, turn_id: str) -> dict[str, object] | None: + nonlocal load_calls + load_calls += 1 + return original_load_turn(session_id, turn_id) + + monkeypatch.setattr(store, "load_turn", counting_load_turn) + with effect_runtime_request_scope(): + project_collaboration(store, runtime_root, sid, messages, registry=registry) + assert load_calls == 6 + load_calls = 0 + project_collaboration(store, runtime_root, sid, messages, registry=registry) + assert load_calls == 0 + + # Warm terminal turn discovery avoids re-parsing unchanged turn JSON files while re-reading matched turns fresh. + reader_cold = original_turn_reader(store, sid) + assert reader_cold("client-3") is not None + reader_warm = original_turn_reader(store, sid) + assert reader_warm("client-3") is not None + + +def test_socket_disconnect_during_response_does_not_emit_secondary_503() -> None: + errors: list[tuple[str, int]] = [] + + class DummySnapshotHandler: + path = "/api/chat/sessions/s1?message_limit=200" + + class server: + registry_path = Path("/tmp/registry.json") + + class chat_store: + @staticmethod + def load_session(_sid: str) -> dict[str, object]: + return {"session_id": "s1"} + + @staticmethod + def session_snapshot(_sid: str, **_kwargs: object) -> dict[str, object]: + return { + "ok": True, + "schema_version": "loopx_chat_store_v1", + "session": {"session_id": "s1"}, + "messages": [], + "active_turn": None, + } + + class private_media_history: + @staticmethod + def read(*_args: object) -> list[dict[str, object]]: + return [] + + class runtime_controller: + coordination_runtime_root = Path("/tmp") + project_contexts = None + + @staticmethod + def recover_exited_turn(_sid: str, _tid: str | None = None) -> None: + return None + + @staticmethod + def _link_history_images(_sid: str, _session: object, _sel: object, rows: list[dict[str, object]]) -> list[dict[str, object]]: + return rows + + @staticmethod + def _send_json(_payload: object, status: int = 200) -> None: + raise BrokenPipeError(f"client disconnected on {status}") + + @staticmethod + def _send_error(message: str, status: int = 400, **_kwargs: object) -> None: + errors.append((message, status)) + + ChatRequestHandler._session_snapshot(DummySnapshotHandler(), "s1") # type: ignore[arg-type] + assert errors == [] + + class DummyQueueHandler(ChatQueueRequestMixin): + class server: + class chat_store: + @staticmethod + def load_session(_sid: str) -> dict[str, object]: + return {"session_id": "s1", "active_turn_id": None} + + @staticmethod + def queued_turns(_sid: str, **_kwargs: object) -> list[dict[str, object]]: + return [] + + class runtime_controller: + project_contexts = None + + @staticmethod + def _session_context(_session: object) -> None: + return None + + @staticmethod + def _send_json(_payload: object, status: int = 200) -> None: + raise ConnectionResetError(f"reset on {status}") + + @staticmethod + def _send_error(message: str, status: int = 400, **_kwargs: object) -> None: + errors.append((message, status)) + + DummyQueueHandler()._session_queue("s1") + assert errors == [] + assert hasattr(RequestControlMixin, "_request_inventory_read")