From 339086ac62732559015b71201af3a5351e32fea7 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:33:06 +0800 Subject: [PATCH] refactor(chat): modularize chat ingress into zero-Any sub-550-LOC facade Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/external_conversations.py | 19 +- loopx/chat/ingress.py | 888 +++++------------- loopx/chat/ingress_admission.py | 188 ++++ loopx/chat/ingress_common.py | 233 +++++ loopx/chat/ingress_queue.py | 679 +++++++++++++ loopx/chat/ingress_receipts.py | 173 ++++ tests/test_chat_ingress_contract.py | 375 ++++++++ 7 files changed, 1914 insertions(+), 641 deletions(-) create mode 100644 loopx/chat/ingress_admission.py create mode 100644 loopx/chat/ingress_common.py create mode 100644 loopx/chat/ingress_queue.py create mode 100644 loopx/chat/ingress_receipts.py create mode 100644 tests/test_chat_ingress_contract.py diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py index 8ce41ce73f..d224c85011 100644 --- a/loopx/capabilities/native_chat/external_conversations.py +++ b/loopx/capabilities/native_chat/external_conversations.py @@ -24,6 +24,7 @@ ensure_external_admission_scope, resolve_external_admission_source, ) +from ...chat.ingress_common import as_mapping as _as_mapping from ...chat_store import ( ChatSessionStore, _atomic_write_json as _atomic_write_json, @@ -1593,6 +1594,7 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A controller = self.controller selected = ensure_external_admission_scope(self.bindings, selected, path, row, source_preflight=None if row.get("native_mention") else source_preflight) + binding = _as_mapping(selected["binding"]) held_for_binding = row.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING if held_for_binding: row.pop("response_code") @@ -1610,8 +1612,8 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A # Observation must retain failed/closed originals. Admission still # uses the resumable selector and never resumes from this snapshot. candidates = (controller.store.list_sessions(channel_id=selected["channel_id"]) - if selected["binding"]["context_kind"] == "steward" else controller.store.session_candidates(goal_id=None, - agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"])) + if binding["context_kind"] == "steward" else controller.store.session_candidates(goal_id=None, + agent_id=binding["executor_endpoint_id"], channel_id=selected["channel_id"])) snapshot = max(candidates, key=lambda candidate: str(candidate.get("updated_at") or ""), default=None) current = controller.store.load_session(snapshot["session_id"]) if snapshot else None if row.get("native_mention") and (row.get("mention_capture") or {}).get("session_id"): @@ -1635,9 +1637,9 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A if held_for_binding and current.get("status") == "closed": raise ValueError("the original steward Session is unavailable for admission") steward_candidate = current - observations = {} - if (row["command"] is None and steward_candidate and selected["binding"]["context_kind"] == "steward" - and steward_candidate.get("executor_endpoint_id") != selected["binding"]["executor_endpoint_id"]): + observations: dict[str, object] = {} + if (row["command"] is None and steward_candidate and binding["context_kind"] == "steward" + and steward_candidate.get("executor_endpoint_id") != binding["executor_endpoint_id"]): observations.update(steward_adoption_session=steward_candidate, context=selected["context"]) if (row["command"] == "stop" and current and not current.get("active_turn_id") and not row.get("target_recorded") and not target): @@ -1669,9 +1671,10 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A _atomic_write_json(path, row) return row if operation == "select_recipient": - if selected["binding"]["context_kind"] != "project": + if binding["context_kind"] != "project": raise ValueError("Agent selection requires the project assistant") - granted = selected["binding"].get("agent_targets", []) + raw_targets = binding.get("agent_targets", []) + granted = [item for item in raw_targets if isinstance(item, dict)] if isinstance(raw_targets, list) else [] choices = [] for candidate in granted: try: @@ -1731,7 +1734,7 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A # adapter. It never creates a Goal or waits for a terminal answer. if current is None: current, _ = controller.open_session(goal_id=None, - agent_id=selected["binding"]["executor_endpoint_id"], work_dir=Path("."), objective="", + agent_id=binding["executor_endpoint_id"], work_dir=Path("."), objective="", mode="resume_latest", conversation_binding_id=row["binding_id"], source_context=row["source"]) row["session_id"] = current["session_id"] _atomic_write_json(path, row) diff --git a/loopx/chat/ingress.py b/loopx/chat/ingress.py index 4d1540691d..c06ad08830 100644 --- a/loopx/chat/ingress.py +++ b/loopx/chat/ingress.py @@ -1,22 +1,40 @@ """Durable queued inputs and ingress receipts for the existing Chat store.""" from __future__ import annotations -from collections.abc import Callable, Iterator -from copy import deepcopy -from datetime import datetime, timedelta, timezone +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager from functools import cached_property -import os -import json +import json as json from pathlib import Path -import uuid -from typing import TYPE_CHECKING, Any -from ..chat import require_matching_message_replay, require_matching_replay -from ..file_lock import exclusive_file_lock -from ..capabilities.native_chat.file_discovery import FileChatDiscovery - -if TYPE_CHECKING: - from ..capabilities.native_chat.conversation_bindings import ChatConversationBindings +from typing import TYPE_CHECKING +from ..capabilities.native_chat.file_discovery import FileChatDiscovery +from ..file_lock import exclusive_file_lock +from .ingress_admission import ( + chat_runtime_activation_state as _chat_runtime_activation_state, + ensure_external_admission_scope as _ensure_external_admission_scope, + resolve_external_admission_source as _resolve_external_admission_source, +) +from .ingress_common import ConversationBindingsProtocol, as_int +from .ingress_queue import ( + complete_recovered_terminalization as _complete_recovered_terminalization, + create_queued_turn as _create_queued_turn, + matched_discovered_turn as _matched_discovered_turn, + mutate_queued_input as _mutate_queued_input, + queue_steering_lock as _queue_steering_lock, + queued_turns as _queued_turns, + recover_queued_turn_input as _recover_queued_turn_input, + turn_discovery_rows as _turn_discovery_rows, + turn_for_client as _turn_for_client, + write_queue_steering as _write_queue_steering, +) +from .ingress_receipts import ( + create_ingress_receipt as _create_ingress_receipt, + loopx_ingress as _loopx_ingress, + steering_delivery_lock as _steering_delivery_lock, + strict_ingress_receipt as _strict_ingress_receipt, + update_ingress_receipt as _update_ingress_receipt, +) SESSION_QUEUE_MAX_PENDING = 20 SESSION_QUEUE_TTL_SECONDS: int | None = None @@ -24,72 +42,48 @@ def resolve_external_admission_source( - bindings: ChatConversationBindings, binding_id: str, source: dict[str, Any], - source_preflight: Callable[[dict[str, Any]], None] | None, *, - session: dict[str, Any] | None = None, -) -> dict[str, Any]: - observation_args = {**source} - if source_preflight is not None: - observation_args["include_observation"] = True - if session is not None: - observation_args.update(session=session, session_context=session["steward_context"]) - selected = bindings.resolve(binding_id=binding_id, **observation_args) - if source_preflight is not None and source_preflight(deepcopy(selected)) is not None: - raise ValueError("source preflight must complete verification or raise") - return selected + bindings: ConversationBindingsProtocol, + binding_id: str, + source: Mapping[str, object], + source_preflight: Callable[[dict[str, object]], None] | None, + *, + session: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Resolve and optionally preflight-verify the binding for an inbound source.""" + return _resolve_external_admission_source( + bindings, + binding_id, + source, + source_preflight, + session=session, + ) def ensure_external_admission_scope( - bindings: ChatConversationBindings, selected: dict[str, Any], path: Path, request: dict[str, Any], *, - source_preflight: Callable[[dict[str, Any]], None] | None, -) -> dict[str, Any]: - source = request["source"] - previous = selected["binding"] - if (request["command"] is not None or request.get("agent_target") is not None - or source.get("private_human_message") is not True - or previous["context_kind"] != "steward" or previous.get("audience", "owner") != "owner" - or previous.get("goal_scope") not in {"all_registered", "selected"} or bindings.controller is None): - bindings.ensure_delivery_scope(selected) - return selected - - with exclusive_file_lock(bindings.path, operation="configure_bound_delivery_scope"): - current = next((binding for binding in bindings.read()["bindings"] - if binding["binding_id"] == previous["binding_id"]), None) - if current == previous: - bindings._ensure_delivery_scope(selected) # This caller retains the binding fence. - return selected - if (current is None - or {previous.get("executor_endpoint_id"), current.get("executor_endpoint_id")} != {"antigravity", "codex"} - or current != {**previous, "executor_endpoint_id": current["executor_endpoint_id"]}): - raise ValueError("conversation binding is no longer authorized") - endpoint = current["executor_endpoint_id"] - candidates = bindings.controller.store.resumable_session_candidates( - goal_id="loopx-manager", agent_id=endpoint, channel_id=selected["channel_id"]) - if len(candidates) != 1: - raise ValueError("the original steward Session is unavailable for admission") - original = candidates[0] - session_id = original["session_id"] - if (original.get("executor_endpoint_id") != endpoint - or not isinstance(original.get("steward_context"), dict) - or request.get("session_id") not in (None, session_id)): - raise ValueError("the original steward Session changed during admission") - # Preserve the original Session across provider IO, service interruption - # or Close. The existing prepared-request path owns subsequent admission. - from ..chat_store import _atomic_write_json - request.update(session_id=session_id, response_code=STEWARD_BINDING_ADOPTION_PENDING) - _atomic_write_json(path, request) - - # No delivery effect has run. Reverify the same original source outside - # the binding fence, then require the exact refreshed binding at the fence. - fresh = resolve_external_admission_source(bindings, previous["binding_id"], source, source_preflight, session=original) - if (fresh["binding"] != current or fresh["context"] != selected["context"] - or fresh["channel_id"] != selected["channel_id"]): - raise ValueError("conversation binding changed during identity verification") - bindings.ensure_delivery_scope(fresh) - return fresh - - -def chat_runtime_activation_lock(runtime_root: Path, *, timeout_seconds: float | None = None): + bindings: ConversationBindingsProtocol, + selected: dict[str, object], + path: Path, + request: dict[str, object], + *, + source_preflight: Callable[[dict[str, object]], None] | None, +) -> dict[str, object]: + """Revalidate delivery scope and execute atomic steward binding adoption.""" + return _ensure_external_admission_scope( + bindings, + selected, + path, + request, + source_preflight=source_preflight, + adoption_pending_code=STEWARD_BINDING_ADOPTION_PENDING, + lock_fn=exclusive_file_lock, + ) + + +def chat_runtime_activation_lock( + runtime_root: Path, + *, + timeout_seconds: float | None = None, +) -> AbstractContextManager[Path]: """Fence new durable input against a managed-service runtime switch.""" return exclusive_file_lock( runtime_root.expanduser().resolve() / "chat" / "runtime-activation", @@ -100,57 +94,77 @@ def chat_runtime_activation_lock(runtime_root: Path, *, timeout_seconds: float | def chat_runtime_activation_state( - runtime_root: Path, *, active_session_ids: list[str] | None = None, + runtime_root: Path, + *, + active_session_ids: list[str] | None = None, ) -> dict[str, int]: - """Strict read of all accepted work; never initialize or recover a store. - - The caller holds ``chat_runtime_activation_lock`` through the service switch. - Session summaries alone omit queued input and are insufficient for this check. - Unknown or unreadable records must not authorize stopping their consumer. - When requested, collect Sessions with active pointers during this same scan. - Their pointers only select recovery candidates. Turn records decide admission. - """ - from ..chat_store import CHAT_SESSION_SCHEMA_VERSION, CHAT_TURN_SCHEMA_VERSION, TERMINAL_TURN_STATES - - sessions = runtime_root.expanduser().resolve() / "chat" / "sessions" - counts = {"sessions": 0, "nonterminal_turns": 0} - if not sessions.exists(): - return counts - for directory in sessions.iterdir(): - if not directory.is_dir(): - continue - session = json.loads((directory / "session.json").read_text(encoding="utf-8")) - if not isinstance(session, dict) or session.get("schema_version") != CHAT_SESSION_SCHEMA_VERSION: - raise ValueError("unreadable Chat Session state") - counts["sessions"] += 1 - active_id = session.get("active_turn_id") - active_found = not active_id - turns = directory / "turns" - for path in turns.iterdir() if turns.exists() else (): - if path.suffix != ".json": - continue - turn = json.loads(path.read_text(encoding="utf-8")) - if (not isinstance(turn, dict) - or turn.get("schema_version") != CHAT_TURN_SCHEMA_VERSION - or not isinstance(turn.get("status"), str) - or turn.get("status") not in TERMINAL_TURN_STATES | { - "queued", "starting", "running", "completing", "interrupting", - }): - raise ValueError("unreadable Chat Turn state") - if turn.get("turn_id") == active_id: - active_found = True - if turn["status"] not in TERMINAL_TURN_STATES: - counts["nonterminal_turns"] += 1 - if not active_found: - raise ValueError("active Chat Turn state is missing") - if active_id and active_session_ids is not None: - if session.get("session_id") != directory.name: - raise ValueError("active Chat Session identity does not match its directory") - active_session_ids.append(directory.name) - return counts + """Strict read of all accepted work; never initialize or recover a store.""" + return _chat_runtime_activation_state( + runtime_root, + active_session_ids=active_session_ids, + ) class ChatIngressStore: + """Mixin owning durable queued inputs and idempotent ingress receipts on ``ChatSessionStore``.""" + + if TYPE_CHECKING: + root: Path + + def _session_dir(self, session_id: str) -> Path: ... + + def _session_path(self, session_id: str) -> Path: ... + + def _session_lock(self, session_id: str) -> AbstractContextManager[object]: ... + + def _turn_path(self, session_id: str, turn_id: str) -> Path: ... + + def _event_path(self, session_id: str, turn_id: str) -> Path: ... + + def _ingress_path(self, session_id: str, client_ingress_id: str) -> Path: ... + + def load_session(self, session_id: str) -> dict[str, object] | None: ... + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: ... + + def events_after(self, session_id: str, turn_id: str, event_id: str | None) -> list[dict[str, object]]: ... + + def messages(self, session_id: str, *, strict: bool = False) -> list[dict[str, object]]: ... + + def append_event( + self, + session_id: str, + turn_id: str, + *, + kind: str, + payload: dict[str, object], + buffered: bool = False, + ) -> dict[str, object]: ... + + def append_message( + self, + session_id: str, + *, + role: str, + text: str, + turn_id: str | None = None, + attachments: list[dict[str, object]] | None = None, + origin: str | None = None, + message_id: str | None = None, + goal_draft: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + def release_active_turn( + self, + session_id: str, + turn_id: str, + *, + last_activity_at: str | object = ..., + last_error_code: str | None | object = ..., + ) -> bool: ... + + def flush_events(self, session_id: str, turn_id: str) -> int: ... + @cached_property def _terminal_turn_discovery(self) -> FileChatDiscovery: # Queue discovery and client lookup share this hint. Concurrent first use @@ -158,300 +172,96 @@ def _terminal_turn_discovery(self) -> FileChatDiscovery: return FileChatDiscovery() def _turn_discovery_rows( - self, session_id: str, turns_dir: Path, read: Callable[[Path], dict[str, Any]], - ) -> Iterator[tuple[Path, dict[str, Any], dict[str, Any] | None]]: - from ..chat_store import CHAT_TURN_SCHEMA_VERSION, TERMINAL_TURN_STATES - - def terminal(path: Path, payload: dict[str, Any]) -> dict[str, Any] | None: - status = payload.get("status") - client_id = payload.get("client_turn_id") - if (payload.get("schema_version") == CHAT_TURN_SCHEMA_VERSION - and payload.get("session_id") == session_id and payload.get("turn_id") == path.stem - and isinstance(status, str) and status in TERMINAL_TURN_STATES - and (client_id is None or isinstance(client_id, str))): - return { - "schema_version": CHAT_TURN_SCHEMA_VERSION, "session_id": session_id, - "turn_id": path.stem, "status": status, "client_turn_id": client_id, - } - return None - - failed = getattr(self, "_last_read_error_paths", None) - if isinstance(failed, dict): - failed.pop(session_id, None) - paths = (path for path in turns_dir.glob("*.json") if not path.name.endswith(".events.json")) - fresh: dict[Path, dict[str, Any]] = {} - - def read_current(path: Path) -> dict[str, Any]: - try: - payload = read(path) - except Exception: - failed_map = getattr(self, "_last_read_error_paths", None) - if not isinstance(failed_map, dict): - failed_map = {} - setattr(self, "_last_read_error_paths", failed_map) - failed_map[session_id] = path - raise - fresh[path] = payload - return payload - - for path, observation in self._terminal_turn_discovery.rows( - turns_dir, paths, read=read_current, project=terminal, - ): - # Retain only the current iteration's complete read, never a body - # in the discovery cache or a second read on the cold path. - yield path, observation, fresh.pop(path, None) + self, + session_id: str, + turns_dir: Path, + read: Callable[[Path], dict[str, object]], + ) -> Iterator[tuple[Path, dict[str, object], dict[str, object] | None]]: + return _turn_discovery_rows(self, session_id, turns_dir, read) def _matched_discovered_turn( - self, session_id: str, client_id: str, path: Path, fresh: dict[str, Any] | None, - ) -> dict[str, Any]: - from ..chat_store import CHAT_TURN_SCHEMA_VERSION, _read_json - - payload = fresh if fresh is not None else _read_json(path) - if (payload.get("schema_version") != CHAT_TURN_SCHEMA_VERSION - or payload.get("session_id") != session_id or payload.get("turn_id") != path.stem - or payload.get("client_turn_id") != client_id): - raise ValueError("Matched Chat Turn is unavailable; retry the same client_turn_id.") - return payload - - def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, Any] | None: - from ..chat_store import _read_json - - turns_dir = self._session_dir(session_id) / "turns" - if not turns_dir.is_dir(): - return None - for path, observation, fresh in self._turn_discovery_rows(session_id, turns_dir, _read_json): - if observation.get("client_turn_id") != client_turn_id: - continue - # Replay validation needs the complete current record, including - # the original request body and the latest persisted result. - return self._matched_discovered_turn(session_id, client_turn_id, path, fresh) - return None - - def runtime_activation_lock(self): + self, + session_id: str, + client_id: str, + path: Path, + fresh: dict[str, object] | None, + ) -> dict[str, object]: + return _matched_discovered_turn(session_id, client_id, path, fresh) + + def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, object] | None: + return _turn_for_client(self, session_id, client_turn_id) + + def runtime_activation_lock(self) -> AbstractContextManager[Path]: return chat_runtime_activation_lock(self.root.parent) - def queued_turns(self, session_id: str, *, strict: bool = False, include_reserved: bool = False, capacity_at: str | None = None) -> list[dict[str, Any]]: - from ..chat_store import _read_json, CHAT_TURN_SCHEMA_VERSION, TERMINAL_TURN_STATES - - session = self.load_session(session_id) - if session is None: - raise KeyError("chat session was not found") - active_turn_id = str(session.get("active_turn_id") or "") - turns_dir = self._session_dir(session_id) / "turns" - rows: list[dict[str, Any]] = [] - - def read(path): - if strict: - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - raise OSError("Queued Turn state is unreadable") from exc - if (not isinstance(payload, dict) - or payload.get("schema_version") != CHAT_TURN_SCHEMA_VERSION - or payload.get("session_id") != session_id - or payload.get("turn_id") != path.stem - or not isinstance(payload.get("status"), str) - or payload.get("status") not in TERMINAL_TURN_STATES | { - "queued", "starting", "running", "completing", "interrupting", - }): - raise OSError("Queued Turn state is invalid") - else: - payload = _read_json(path) - return payload - - for _, payload, _ in self._turn_discovery_rows(session_id, turns_dir, read): - if ( - payload.get("schema_version") == CHAT_TURN_SCHEMA_VERSION - and payload.get("status") == "queued" - and str(payload.get("turn_id") or "") != active_turn_id - ): - rows.append(payload) - # The ordinary read has no selectable Turn when storage has no queued - # candidates. Explicit capacity and strict reads still use the owner. - if not rows and not strict and not include_reserved and capacity_at is None: - return [] - - from ..control_plane.chat_turn_acceptance import queued_chat_turn_ids - selected = set(queued_chat_turn_ids(rows, active_turn_id, include_reserved=include_reserved, capacity_at=capacity_at)) - return sorted( - [row for row in rows if row["turn_id"] in selected], - key=lambda item: ( - str(item.get("created_at") or ""), - str(item.get("turn_id") or ""), - ), + def queued_turns( + self, + session_id: str, + *, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, + ) -> list[dict[str, object]]: + return _queued_turns( + self, + session_id, + strict=strict, + include_reserved=include_reserved, + capacity_at=capacity_at, ) - def queue_steering_lock(self, session_id: str, turn_id: str): - """Use the same Session→Turn fences as automatic queue consumption.""" - from contextlib import ExitStack - stack = ExitStack() - try: - stack.enter_context(self._session_lock(session_id)) - stack.enter_context(exclusive_file_lock(self._session_path(session_id), - agent_id="loopx-chat", operation="steer_session_queue_turn")) - stack.enter_context(exclusive_file_lock(self._turn_path(session_id, turn_id), - agent_id="loopx-chat", operation="steer_queued_chat_turn")) - return stack - except BaseException: - stack.close() - raise - - def mutate_queued_input(self, session_id: str, turn_id: str, request: dict[str, Any]) -> dict[str, Any]: + def queue_steering_lock(self, session_id: str, turn_id: str) -> AbstractContextManager[object]: + """Use the same Session->Turn fences as automatic queue consumption.""" + return _queue_steering_lock(self, session_id, turn_id, lock_fn=exclusive_file_lock) + + def mutate_queued_input( + self, + session_id: str, + turn_id: str, + request: Mapping[str, object], + ) -> dict[str, object]: """Execute the TS owner's recoverable input plan under the consumer fences.""" - from ..chat_store import _atomic_write_json, _read_jsonl, utc_now - from ..control_plane.chat_turn_acceptance import plan_queued_chat_mutation - from ..file_lock import write_bytes_atomic - - with self.queue_steering_lock(session_id, turn_id): - session, turn = self.load_session(session_id), self.load_turn(session_id, turn_id) - if session is None or turn is None: - raise KeyError("chat turn was not found") - plan = plan_queued_chat_mutation(session, turn, request) - if plan["action"] == "reject": - raise RuntimeError(plan["error_code"]) - receipt = plan["receipt"] - if plan["action"] == "apply": - if turn.get("_queue_mutation") is None: - self._recover_queued_turn_input(session_id, turn) - path = self._turn_path(session_id, turn_id) - # The receipt precedes all other writes. A partial write stays - # reserved, including across process death; only this identity - # can finish it. No native call or active-Turn interrupt occurs. - turn = {**turn, "_queue_mutation": receipt, - "_queue_original_message": turn.get("_queue_original_message", turn["message"])} - _atomic_write_json(path, turn, preserve_mode=True) - messages_path = self._session_dir(session_id) / "messages.jsonl" - with exclusive_file_lock(messages_path, agent_id="loopx-chat", operation="update_queued_input"): - rows = _read_jsonl(messages_path, raise_on_error=True, strict=True) - matches = [r for r in rows if r.get("turn_id") == turn_id and r.get("role") == "user"] - if len(matches) != 1: - raise OSError("Original queued input is unavailable") - row = matches[0] - if row.get("queue_input_revision", 0) != receipt["input_revision"]: - if row.get("text") != turn["message"] or row.get("attachments") != turn.get("attachments"): - raise OSError("Original queued input changed") - if "text" in plan["message_patch"]: - row["queue_edit_history"] = [*row.get("queue_edit_history", []), - {"text": row["text"], "input_revision": turn.get("input_revision", 0), - "operation_id": receipt["operation_id"]}] - row.update(plan["message_patch"]) - write_bytes_atomic(messages_path, - ("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)).encode(), preserve_mode=True) - elif any(row.get(key) != value for key, value in plan["message_patch"].items()): - raise OSError("Queued input revision conflicts with its receipt") - event = plan["event"] - if not any(e.get("kind") == event["kind"] and e.get("payload") == event["payload"] - for e in self.events_after(session_id, turn_id, None)): - self.append_event(session_id, turn_id, kind=event["kind"], payload=event["payload"]) - # Metadata edits do not invent worker activity; invalidate the - # existing Session history cache without changing liveness. - session["updated_at"] = utc_now() - _atomic_write_json(self._session_path(session_id), session, preserve_mode=True) - turn.update(plan["turn_patch"]) - turn["_queue_operations"] = [*turn.get("_queue_operations", []), receipt] - turn.pop("_queue_mutation") - if receipt["action"] == "cancel": - turn["completed_at"] = utc_now() - _atomic_write_json(path, turn, preserve_mode=True) - return {"session_id": session_id, "queued_turn_id": turn_id, - "operation_id": receipt["operation_id"], "action": receipt["action"], - "input_revision": receipt["input_revision"], "status": "applied"} - - def steering_receipt(self, session_id: str, ingress_id: str): + return _mutate_queued_input(self, session_id, turn_id, request, lock_fn=exclusive_file_lock) + + def steering_receipt(self, session_id: str, ingress_id: str) -> dict[str, object] | None: """A corrupt receipt cannot be treated as absence and resent.""" return self._strict_ingress_receipt(session_id, ingress_id) - def _strict_ingress_receipt(self, session_id: str, ingress_id: str) -> dict[str, Any] | None: + def _strict_ingress_receipt(self, session_id: str, ingress_id: str) -> dict[str, object] | None: """Absent is ``None``; any other unreadable receipt fails closed.""" - from ..chat_store import CHAT_INGRESS_SCHEMA_VERSION, _opaque_id - # The receipt is stored under the normalized id, so a replay that repeats - # the original (padded) text must be matched against that same id. - ingress_id = _opaque_id(ingress_id, field="client_ingress_id") - path = self._ingress_path(session_id, ingress_id) - try: - value = json.loads(path.read_text(encoding="utf-8")) - except FileNotFoundError as exc: - if os.path.lexists(path): - # A link whose target is gone is an existing entry, not absence: - # replacing it would resend a message that may have been delivered. - raise OSError("Ingress receipt is unreadable") from exc - return None - except (OSError, ValueError) as exc: - raise OSError("Ingress receipt is unreadable") from exc - if (not isinstance(value, dict) or value.get("schema_version") != CHAT_INGRESS_SCHEMA_VERSION - or value.get("session_id") != session_id or value.get("client_ingress_id") != ingress_id): - raise OSError("Ingress receipt is unreadable") - return value - - def steering_delivery_lock(self, session_id: str, ingress_id: str): + return _strict_ingress_receipt(self, session_id, ingress_id) + + def steering_delivery_lock(self, session_id: str, ingress_id: str) -> AbstractContextManager[Path]: """Serialize one native send and its later readback across controllers.""" - return exclusive_file_lock(self._ingress_path(session_id, ingress_id).with_suffix(".delivery"), - agent_id="loopx-chat", operation="chat_steering_delivery") + return _steering_delivery_lock(self, session_id, ingress_id, lock_fn=exclusive_file_lock) - def write_queue_steering(self, session_id: str, turn: dict[str, Any], plan: dict[str, Any]): + def write_queue_steering( + self, + session_id: str, + turn: dict[str, object], + plan: Mapping[str, object], + ) -> dict[str, object]: """Persist the typed plan while the caller holds both queue fences.""" - from ..chat_store import _atomic_write_json, utc_now - if plan["action"] not in {"dispatch", "complete", "release"}: - return turn - turn = {**turn, "_queue_steering": plan["reservation"]} - if plan["action"] == "complete": - # Keep the existing SSE response envelope for older readers. The - # adoption marker distinguishes this receipt from a model answer; - # no assistant transcript row or invented answer is published. - response: dict[str, Any] = { - "schema_version": "loopx_chat_agent_response_v0", - "message": "", - "proposals": [], - "protected_action": None, - "gate": None, - } - turn.update(status="completed", completed_at=turn.get("completed_at") or utc_now(), response=response) - _atomic_write_json(self._turn_path(session_id, turn["turn_id"]), turn, preserve_mode=True) - if plan["action"] == "complete": - payload = {"steered_into_turn_id": plan["reservation"]["target_turn_id"], "response": turn["response"]} - if not any(e.get("kind") == "turn.completed" and e.get("payload") == payload - for e in self.events_after(session_id, turn["turn_id"], None)): - self.append_event(session_id, turn["turn_id"], kind="turn.completed", payload=payload) - return turn + return _write_queue_steering(self, session_id, turn, plan) def complete_recovered_terminalization( - self, session_id: str, turn_id: str, - session: dict[str, Any] | None, turn: dict[str, Any] | None, - *, recovery_messages: dict[str, str], + self, + session_id: str, + turn_id: str, + session: Mapping[str, object] | None, + turn: Mapping[str, object] | None, + *, + recovery_messages: Mapping[str, str], ) -> None: - """Finish the lifecycle owner's already-persisted failure, never dispatch. - - State precedes the event, error message and claim release. If one of - those writes failed, retain the exact recovery result and idempotently - finish only its missing writes under the caller's execution fence. - """ - from ..chat_store import CHAT_SESSION_MODE_MANAGED, utc_now - - if (session is None or turn is None - or session.get("session_mode") != CHAT_SESSION_MODE_MANAGED - or turn.get("status") != "failed"): - return - code = str(turn.get("error_code") or "") - message = recovery_messages.get(code) - if message is None or (code != "server_restarted" and turn.get("error") != message): - return # Match this owner's recorded recovery, not arbitrary failures. - if not any( - event.get("kind") == "turn.failed" - and (event.get("payload") or {}).get("error_code") == code - and (event.get("payload") or {}).get("message") == message - for event in self.events_after(session_id, turn_id, None) - ): - self.append_event(session_id, turn_id, kind="turn.failed", - payload={"error_code": code, "message": message}) - if not any( - item.get("turn_id") == turn_id and item.get("role") == "error" - and item.get("text") == message for item in self.messages(session_id) - ): - self.append_message(session_id, role="error", text=message, turn_id=turn_id) - if session.get("active_turn_id") == turn_id: - self.release_active_turn(session_id, turn_id, - last_activity_at=str(turn.get("completed_at") or utc_now()), - last_error_code=code) + """Finish the lifecycle owner's already-persisted failure, never dispatch.""" + _complete_recovered_terminalization( + self, + session_id, + turn_id, + session, + turn, + recovery_messages=recovery_messages, + ) def create_queued_turn( self, @@ -459,165 +269,32 @@ def create_queued_turn( *, client_turn_id: str, message: str, - attachments: list[dict[str, Any]] | None = None, + attachments: Sequence[Mapping[str, object]] | None = None, goal_instance_id: str | None = None, ttl_seconds: int | None = SESSION_QUEUE_TTL_SECONDS, origin: str = "external", - external_agent_target: dict[str, Any] | None = None, - collaboration_request: dict[str, Any] | None = None, - ) -> tuple[dict[str, Any], bool]: - """Persist one follow-up without replacing the active Turn. - - Accepted user input has no implicit wall-clock expiry. Callers may - still supply an explicit TTL for time-sensitive work. Queue capacity, - source revalidation and Stop remain independent bounds. - """ - - from ..chat_store import _opaque_id, _atomic_write_json, utc_now, CHAT_TURN_SCHEMA_VERSION - - client_id = _opaque_id(client_turn_id, field="client_turn_id") - from .attachments import normalize_chat_attachments, validate_chat_turn_envelope - normalized_attachments = normalize_chat_attachments(attachments) or None - if normalized_attachments: - validate_chat_turn_envelope({"message": message, "attachments": normalized_attachments}) - session_path = self._session_path(session_id) - with self.runtime_activation_lock(), self._session_lock(session_id): - with exclusive_file_lock( - session_path, - agent_id="loopx-chat", - operation="create_chat_queued_turn", - ): - existing = self.turn_for_client(session_id, client_id) - if existing is not None: - require_matching_replay( - {**existing, "message": existing.get("_queue_original_message", existing.get("message"))}, - identity="client_turn_id", - request={ - "message": str(message), - "attachments": normalized_attachments, - "origin": _opaque_id(origin, field="origin"), - "external_agent_target": external_agent_target, - **({"collaboration_request": collaboration_request} if collaboration_request is not None else {}), - }, - ) - # Managed acceptance retains its own message identity and - # visible text. A queue-mode retry only replays that receipt; - # the original typed acceptance owner finishes its writes. - if "_acceptance" not in existing: - self._recover_queued_turn_input(session_id, existing) - return existing, False - session = self.load_session(session_id) - if session is None or session.get("status") == "closed": - raise KeyError("chat session was not found") - now = datetime.now(timezone.utc) - queued = self.queued_turns(session_id, include_reserved=True, capacity_at=now.isoformat()) - if len(queued) >= SESSION_QUEUE_MAX_PENDING: - raise RuntimeError("session_queue_full") - turn_id = uuid.uuid4().hex - now_text = now.isoformat().replace("+00:00", "Z") - payload = { - "schema_version": CHAT_TURN_SCHEMA_VERSION, - "turn_id": turn_id, - "session_id": session_id, - **( - { - "goal_instance_id": _opaque_id( - goal_instance_id, - field="goal_instance_id", - ) - } - if goal_instance_id is not None - else {} - ), - "client_turn_id": client_id, - "status": "queued", - **({"external_agent_target": external_agent_target} if external_agent_target is not None else {}), - **({"collaboration_request": collaboration_request} if collaboration_request is not None else {}), - "message": str(message), - **({"attachments": normalized_attachments} if normalized_attachments else {}), - "origin": _opaque_id(origin, field="origin"), - "upstream_turn_id": None, - "response": None, - "error_code": None, - "error": None, - "created_at": now_text, - "expires_at": ((now + timedelta(seconds=max(1, ttl_seconds))) - .isoformat().replace("+00:00", "Z") if ttl_seconds is not None else None), - "started_at": None, - "first_event_at": None, - "completed_at": None, - "last_activity_at": now_text, - "delta_count": 0, - "sse_reconnect_count": 0, - } - path = self._turn_path(session_id, turn_id) - _atomic_write_json(path, payload) - os.chmod(path, 0o600) - session.update( - { - "last_activity_at": now_text, - "updated_at": utc_now(), - } - ) - _atomic_write_json(session_path, session, preserve_mode=True) - # Keep the cross-process Session fence through publication: - # neither another retry nor a queue claim may overtake it. - self.append_message( - session_id, - role="user", - text=message, - turn_id=turn_id, - origin=origin, - attachments=normalized_attachments, - ) - self.append_event( - session_id, - turn_id, - kind="turn.queued", - payload={"delivery_mode": "session_queue"}, - ) - return payload, True - - def _recover_queued_turn_input(self, session_id: str, turn: dict[str, Any]) -> None: - """Finish interrupted input IO under the caller's Session fence. - - The existing queued event follows the transcript append. It is the - publication marker, so healthy claims need no full transcript scan. - Recovery uses the saved request, never a retry's replacement text. - """ - from ..chat_store import _read_jsonl - - if "_acceptance" in turn: - raise ValueError("managed Turn acceptance must finish before queue dispatch") - turn_id = str(turn["turn_id"]) - event_path = self._event_path(session_id, turn_id) - try: - with event_path.open("rb") as stream: - first = stream.readline() - except FileNotFoundError: - first = b"" - if first.strip(): - import json - - event = json.loads(first) - if isinstance(event, dict) and event.get("kind") == "turn.queued": - return - self.flush_events(session_id, turn_id) - events = _read_jsonl(event_path, raise_on_error=True, strict=True) - if any(row["kind"] == "turn.queued" for row in events): - return - inputs = [row for row in _read_jsonl(self._session_dir(session_id) / "messages.jsonl", raise_on_error=True, strict=True) - if row.get("turn_id") == turn_id and row.get("role") == "user"] - expected = {"message_id": "queue." + turn_id, "role": "user", "turn_id": turn_id, - "text": turn["message"], "origin": turn["origin"], - "attachments": turn.get("attachments")} - if inputs: - if len(inputs) != 1: - raise ValueError("queued Turn has ambiguous input messages") - require_matching_message_replay(inputs[0], expected) - else: - self.append_message(session_id, **expected) - self.append_event(session_id, turn_id, kind="turn.queued", payload={"delivery_mode": "session_queue"}) + external_agent_target: Mapping[str, object] | None = None, + collaboration_request: Mapping[str, object] | None = None, + ) -> tuple[dict[str, object], bool]: + """Persist one follow-up without replacing the active Turn.""" + return _create_queued_turn( + self, + session_id, + client_turn_id=client_turn_id, + message=message, + attachments=attachments, + goal_instance_id=goal_instance_id, + ttl_seconds=ttl_seconds, + origin=origin, + external_agent_target=external_agent_target, + collaboration_request=collaboration_request, + max_pending=as_int(SESSION_QUEUE_MAX_PENDING, 20), + lock_fn=exclusive_file_lock, + ) + + def _recover_queued_turn_input(self, session_id: str, turn: Mapping[str, object]) -> None: + """Finish interrupted input IO under the caller's Session fence.""" + _recover_queued_turn_input(self, session_id, turn) def create_ingress_receipt( self, @@ -627,87 +304,32 @@ def create_ingress_receipt( mode: str, message: str, expected_turn_id: str | None = None, - ) -> tuple[dict[str, Any], bool]: + ) -> tuple[dict[str, object], bool]: """Reserve one idempotent external ingress before provider delivery.""" - - from ..chat_store import _opaque_id, _atomic_write_json, utc_now, CHAT_INGRESS_SCHEMA_VERSION - - if self.load_session(session_id) is None: - raise KeyError("chat session was not found") - path = self._ingress_path(session_id, client_ingress_id) - with exclusive_file_lock( - path, - agent_id="loopx-chat", - operation="create_chat_ingress_receipt", - ): - # A damaged receipt may record a delivered send. It is not absence: - # recreating it would resend the message and erase that evidence. - existing = self._strict_ingress_receipt(session_id, client_ingress_id) - if existing is not None: - request: dict[str, Any] = { - "mode": _opaque_id(mode, field="mode"), - "message": str(message), - } - if expected_turn_id is not None or "expected_turn_id" in existing: - request["expected_turn_id"] = expected_turn_id - require_matching_replay( - existing, - identity="client_ingress_id", - request=request, - ) - return existing, False - now = utc_now() - payload = { - "schema_version": CHAT_INGRESS_SCHEMA_VERSION, - "client_ingress_id": _opaque_id( - client_ingress_id, - field="client_ingress_id", - ), - "session_id": session_id, - "mode": _opaque_id(mode, field="mode"), - "status": "pending", - "message": str(message), - "active_turn_id": None, - **({"expected_turn_id": _opaque_id(expected_turn_id, field="expected_turn_id")} - if expected_turn_id is not None else {}), - "error_code": None, - "created_at": now, - "updated_at": now, - } - _atomic_write_json(path, payload) - os.chmod(path, 0o600) - return payload, True + return _create_ingress_receipt( + self, + session_id, + client_ingress_id=client_ingress_id, + mode=mode, + message=message, + expected_turn_id=expected_turn_id, + lock_fn=exclusive_file_lock, + ) def update_ingress_receipt( self, session_id: str, client_ingress_id: str, - **changes: Any, - ) -> dict[str, Any]: - from ..chat_store import _read_json, _atomic_write_json, utc_now, CHAT_INGRESS_SCHEMA_VERSION - - path = self._ingress_path(session_id, client_ingress_id) - with exclusive_file_lock( - path, - agent_id="loopx-chat", - operation="update_chat_ingress_receipt", - ): - payload = _read_json(path) - if payload.get("schema_version") != CHAT_INGRESS_SCHEMA_VERSION: - raise KeyError("chat ingress receipt was not found") - allowed = {"status", "active_turn_id", "error_code", "native_steering"} - unknown = set(changes) - allowed - if unknown: - raise ValueError(f"unsupported chat ingress fields: {sorted(unknown)}") - payload.update(changes) - payload["updated_at"] = utc_now() - _atomic_write_json(path, payload, preserve_mode=True) - return payload - - def loopx_ingress(self, session_id: str) -> list[dict[str, Any]]: - """Read the existing ingress ledger; no second queue or delivery truth.""" - from ..chat_store import _read_json + **changes: object, + ) -> dict[str, object]: + return _update_ingress_receipt( + self, + session_id, + client_ingress_id, + exclusive_file_lock, + **changes, + ) - rows = [_read_json(path) for path in (self._session_dir(session_id) / "ingress").glob("*.json")] - return sorted((row for row in rows if row.get("mode") in {"loopx_queue", "loopx_inbox"}), - key=lambda row: (row.get("created_at", ""), row.get("client_ingress_id", ""))) + def loopx_ingress(self, session_id: str) -> list[dict[str, object]]: + """Read the existing ingress ledger; no second queue or delivery truth.""" + return _loopx_ingress(self, session_id) diff --git a/loopx/chat/ingress_admission.py b/loopx/chat/ingress_admission.py new file mode 100644 index 0000000000..68e9860c04 --- /dev/null +++ b/loopx/chat/ingress_admission.py @@ -0,0 +1,188 @@ +"""External conversation admission and runtime activation checks for Chat ingress.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +from copy import deepcopy +import json +from pathlib import Path +from typing import cast + +from .ingress_common import ( + ConversationBindingsProtocol, + LockFileFn, + NONTERMINAL_TURN_STATES, + as_mapping, + is_valid_turn_record, +) + + +def resolve_external_admission_source( + bindings: ConversationBindingsProtocol, + binding_id: str, + source: Mapping[str, object], + source_preflight: Callable[[dict[str, object]], None] | None, + *, + session: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Resolve and optionally preflight-verify the authoritative binding for an inbound source.""" + observation_args: dict[str, object] = {**source} + if source_preflight is not None: + observation_args["include_observation"] = True + if session is not None: + observation_args.update(session=session, session_context=session["steward_context"]) + resolve_fn = cast(Callable[..., dict[str, object]], bindings.resolve) + selected = resolve_fn(binding_id=binding_id, **observation_args) + if source_preflight is not None and source_preflight(deepcopy(selected)) is not None: + raise ValueError("source preflight must complete verification or raise") + return selected + + +def ensure_external_admission_scope( + bindings: ConversationBindingsProtocol, + selected: dict[str, object], + path: Path, + request: dict[str, object], + *, + source_preflight: Callable[[dict[str, object]], None] | None, + adoption_pending_code: str, + lock_fn: LockFileFn, +) -> dict[str, object]: + """Revalidate delivery scope and handle atomic steward executor adoption when needed.""" + source = as_mapping(request["source"]) + previous = as_mapping(selected["binding"]) + if ( + request["command"] is not None + or request.get("agent_target") is not None + or source.get("private_human_message") is not True + or previous["context_kind"] != "steward" + or previous.get("audience", "owner") != "owner" + or previous.get("goal_scope") not in {"all_registered", "selected"} + or bindings.controller is None + ): + bindings.ensure_delivery_scope(selected) + return selected + + controller = bindings.controller + with lock_fn(bindings.path, operation="configure_bound_delivery_scope"): + raw_bindings = bindings.read().get("bindings") + current = ( + next( + ( + binding + for binding in raw_bindings + if isinstance(binding, dict) and binding.get("binding_id") == previous["binding_id"] + ), + None, + ) + if isinstance(raw_bindings, list) + else None + ) + if current == previous: + bindings._ensure_delivery_scope(selected) # This caller retains the binding fence. + return selected + if ( + current is None + or {previous.get("executor_endpoint_id"), current.get("executor_endpoint_id")} + != {"antigravity", "codex"} + or current != {**previous, "executor_endpoint_id": current["executor_endpoint_id"]} + ): + raise ValueError("conversation binding is no longer authorized") + endpoint = str(current["executor_endpoint_id"]) + raw_channel = selected["channel_id"] + channel_id = raw_channel if isinstance(raw_channel, str) else None + candidates = controller.store.resumable_session_candidates( + goal_id="loopx-manager", + agent_id=endpoint, + channel_id=channel_id, + ) + if len(candidates) != 1: + raise ValueError("the original steward Session is unavailable for admission") + original = candidates[0] + session_id = original["session_id"] + if ( + original.get("executor_endpoint_id") != endpoint + or not isinstance(original.get("steward_context"), dict) + or request.get("session_id") not in (None, session_id) + ): + raise ValueError("the original steward Session changed during admission") + # Preserve the original Session across provider IO, service interruption + # or Close. The existing prepared-request path owns subsequent admission. + from ..chat_store import _atomic_write_json + + request.update(session_id=session_id, response_code=adoption_pending_code) + _atomic_write_json(path, request) + + # No delivery effect has run. Reverify the same original source outside + # the binding fence, then require the exact refreshed binding at the fence. + fresh = resolve_external_admission_source( + bindings, + str(previous["binding_id"]), + source, + source_preflight, + session=original, + ) + if ( + fresh["binding"] != current + or fresh["context"] != selected["context"] + or fresh["channel_id"] != selected["channel_id"] + ): + raise ValueError("conversation binding changed during identity verification") + bindings.ensure_delivery_scope(fresh) + return fresh + + +def chat_runtime_activation_state( + runtime_root: Path, + *, + active_session_ids: list[str] | None = None, +) -> dict[str, int]: + """Strict read of all accepted work; never initialize or recover a store. + + The caller holds ``chat_runtime_activation_lock`` through the service switch. + Session summaries alone omit queued input and are insufficient for this check. + Unknown or unreadable records must not authorize stopping their consumer. + When requested, collect Sessions with active pointers during this same scan. + Their pointers only select recovery candidates. Turn records decide admission. + """ + from ..chat_store import TERMINAL_TURN_STATES + from ..control_plane.collaboration.source_chat_observation import ( + CHAT_SESSION_SCHEMA_VERSION, + CHAT_TURN_SCHEMA_VERSION, + ) + + sessions = runtime_root.expanduser().resolve() / "chat" / "sessions" + counts = {"sessions": 0, "nonterminal_turns": 0} + if not sessions.exists(): + return counts + valid_statuses = TERMINAL_TURN_STATES | NONTERMINAL_TURN_STATES + for directory in sessions.iterdir(): + if not directory.is_dir(): + continue + raw_session: object = json.loads((directory / "session.json").read_text(encoding="utf-8")) + if not isinstance(raw_session, dict) or raw_session.get("schema_version") != CHAT_SESSION_SCHEMA_VERSION: + raise ValueError("unreadable Chat Session state") + counts["sessions"] += 1 + active_id = raw_session.get("active_turn_id") + active_found = not active_id + turns = directory / "turns" + for path in turns.iterdir() if turns.exists() else (): + if path.suffix != ".json": + continue + raw_turn: object = json.loads(path.read_text(encoding="utf-8")) + if not is_valid_turn_record( + raw_turn, + schema_version=CHAT_TURN_SCHEMA_VERSION, + valid_statuses=valid_statuses, + ): + raise ValueError("unreadable Chat Turn state") + if raw_turn.get("turn_id") == active_id: + active_found = True + if raw_turn["status"] not in TERMINAL_TURN_STATES: + counts["nonterminal_turns"] += 1 + if not active_found: + raise ValueError("active Chat Turn state is missing") + if active_id and active_session_ids is not None: + if raw_session.get("session_id") != directory.name: + raise ValueError("active Chat Session identity does not match its directory") + active_session_ids.append(directory.name) + return counts diff --git a/loopx/chat/ingress_common.py b/loopx/chat/ingress_common.py new file mode 100644 index 0000000000..cbd6d79e51 --- /dev/null +++ b/loopx/chat/ingress_common.py @@ -0,0 +1,233 @@ +"""Shared Zero-Any schema, validation, and protocol contracts for Chat ingress.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping, Set as AbstractSet +from contextlib import AbstractContextManager +from pathlib import Path +from typing import Protocol, TypeAlias, TypeGuard, cast + +from ..capabilities.native_chat.file_discovery import FileChatDiscovery + +LockFileFn: TypeAlias = Callable[..., AbstractContextManager[Path]] + +NONTERMINAL_TURN_STATES: frozenset[str] = frozenset( + {"queued", "starting", "running", "completing", "interrupting"} +) + + +def as_mapping(value: object) -> Mapping[str, object]: + """Narrow an arbitrary JSON object to a read-only string-keyed mapping.""" + return cast(Mapping[str, object], value) if isinstance(value, Mapping) else {} + + +def as_dict(value: object) -> dict[str, object]: + """Copy a mapping value into a mutable dict, preserving concrete dicts as shallow copies.""" + if isinstance(value, Mapping): + return {str(key): item for key, item in value.items()} + return {} + + +def as_str(value: object, default: str = "") -> str: + """Convert non-None scalars to ``str`` while mapping ``None`` to ``default``.""" + return default if value is None else str(value) + + +def read_chat_json(path: Path) -> dict[str, object]: + """Read one persisted Chat JSON object while preserving ``chat_store._read_json`` hooks.""" + from .. import chat_store + from ..control_plane.collaboration.source_chat_observation import ( + _read_json as default_read_json, + ) + + read_fn = getattr(chat_store, "_read_json", default_read_json) + raw = read_fn(path) if callable(read_fn) else default_read_json(path) + return cast(dict[str, object], raw) if isinstance(raw, dict) else {} + + +def as_int(value: object, default: int = 0) -> int: + """Return an integer value when numeric (excluding bool), else ``default``.""" + if isinstance(value, bool): + return default + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + return default + + +def is_valid_turn_record( + payload: object, + *, + schema_version: str, + valid_statuses: AbstractSet[str], + session_id: str | None = None, + turn_id: str | None = None, +) -> TypeGuard[dict[str, object]]: + """Check persistent Chat Turn record structure and lifecycle status.""" + if not isinstance(payload, dict) or payload.get("schema_version") != schema_version: + return False + if session_id is not None and payload.get("session_id") != session_id: + return False + if turn_id is not None and payload.get("turn_id") != turn_id: + return False + status = payload.get("status") + return isinstance(status, str) and status in valid_statuses + + +class AdmissionStoreProtocol(Protocol): + """Subset of Chat store operations used during external steward admission.""" + + def resumable_session_candidates( + self, + *, + goal_id: str | None, + agent_id: str, + channel_id: str | None = None, + ) -> list[dict[str, object]]: ... + + +class AdmissionControllerProtocol(Protocol): + """Runtime controller attribute exposed on ``ChatConversationBindings``.""" + + @property + def store(self) -> AdmissionStoreProtocol: ... + + +class ConversationBindingsProtocol(Protocol): + """Conversation-bindings interface consumed by external Chat ingress admission.""" + + path: Path + + @property + def controller(self) -> AdmissionControllerProtocol | None: ... + + def read(self) -> dict[str, object]: ... + + def resolve( + self, + *, + binding_id: str, + source_ref: str, + sender_ref: str, + private_human_message: bool, + session_context: dict[str, object] | None = None, + group_ref: str | None = None, + topic_ref: str | None = None, + group_human_message: bool = False, + include_observation: bool = False, + origin: str | None = None, + session: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + def ensure_delivery_scope( + self, + selected: dict[str, object], + *, + if_absent: bool = True, + execute: bool = True, + ) -> None: ... + + def _ensure_delivery_scope( + self, + selected: dict[str, object], + *, + if_absent: bool = True, + execute: bool = True, + ) -> None: ... + + +class IngressStoreHostProtocol(Protocol): + """Store host contract required by ``ChatIngressStore`` queue and receipt helpers.""" + + root: Path + + @property + def _terminal_turn_discovery(self) -> FileChatDiscovery: ... + + def _session_dir(self, session_id: str) -> Path: ... + + def _session_path(self, session_id: str) -> Path: ... + + def _session_lock(self, session_id: str) -> AbstractContextManager[object]: ... + + def _turn_path(self, session_id: str, turn_id: str) -> Path: ... + + def _event_path(self, session_id: str, turn_id: str) -> Path: ... + + def _ingress_path(self, session_id: str, client_ingress_id: str) -> Path: ... + + def _turn_discovery_rows( + self, + session_id: str, + turns_dir: Path, + read: Callable[[Path], dict[str, object]], + ) -> Iterator[tuple[Path, dict[str, object], dict[str, object] | None]]: ... + + def _matched_discovered_turn( + self, + session_id: str, + client_id: str, + path: Path, + fresh: dict[str, object] | None, + ) -> dict[str, object]: ... + + def _strict_ingress_receipt(self, session_id: str, ingress_id: str) -> dict[str, object] | None: ... + + def _recover_queued_turn_input(self, session_id: str, turn: Mapping[str, object]) -> None: ... + + def runtime_activation_lock(self) -> AbstractContextManager[Path]: ... + + def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, object] | None: ... + + def queued_turns( + self, + session_id: str, + *, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, + ) -> list[dict[str, object]]: ... + + def queue_steering_lock(self, session_id: str, turn_id: str) -> AbstractContextManager[object]: ... + + def load_session(self, session_id: str) -> dict[str, object] | None: ... + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: ... + + def events_after(self, session_id: str, turn_id: str, event_id: str | None) -> list[dict[str, object]]: ... + + def messages(self, session_id: str, *, strict: bool = False) -> list[dict[str, object]]: ... + + def append_event( + self, + session_id: str, + turn_id: str, + *, + kind: str, + payload: dict[str, object], + buffered: bool = False, + ) -> dict[str, object]: ... + + def append_message( + self, + session_id: str, + *, + role: str, + text: str, + turn_id: str | None = None, + attachments: list[dict[str, object]] | None = None, + origin: str | None = None, + message_id: str | None = None, + goal_draft: dict[str, object] | None = None, + ) -> dict[str, object]: ... + + def release_active_turn( + self, + session_id: str, + turn_id: str, + *, + last_activity_at: str | object = ..., + last_error_code: str | None | object = ..., + ) -> bool: ... + + def flush_events(self, session_id: str, turn_id: str) -> int: ... diff --git a/loopx/chat/ingress_queue.py b/loopx/chat/ingress_queue.py new file mode 100644 index 0000000000..5bbe5eed01 --- /dev/null +++ b/loopx/chat/ingress_queue.py @@ -0,0 +1,679 @@ +"""Queued Chat turn discovery, admission, mutation, steering, and recovery helpers.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager, ExitStack +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +from typing import cast +import uuid + +from .attachments import normalize_chat_attachments, validate_chat_turn_envelope +from .ingress_common import ( + IngressStoreHostProtocol, + LockFileFn, + NONTERMINAL_TURN_STATES, + as_dict, + as_mapping, + is_valid_turn_record, + read_chat_json, +) + + +def turn_discovery_rows( + host: IngressStoreHostProtocol, + session_id: str, + turns_dir: Path, + read: Callable[[Path], dict[str, object]], +) -> Iterator[tuple[Path, dict[str, object], dict[str, object] | None]]: + """Iterate cached terminal observations or freshly parsed Chat Turn rows.""" + from ..chat_store import TERMINAL_TURN_STATES + from ..control_plane.collaboration.source_chat_observation import CHAT_TURN_SCHEMA_VERSION + + def terminal(path: Path, payload: Mapping[str, object]) -> dict[str, object] | None: + status = payload.get("status") + client_id = payload.get("client_turn_id") + if ( + payload.get("schema_version") == CHAT_TURN_SCHEMA_VERSION + and payload.get("session_id") == session_id + and payload.get("turn_id") == path.stem + and isinstance(status, str) + and status in TERMINAL_TURN_STATES + and (client_id is None or isinstance(client_id, str)) + ): + return { + "schema_version": CHAT_TURN_SCHEMA_VERSION, + "session_id": session_id, + "turn_id": path.stem, + "status": status, + "client_turn_id": client_id, + } + return None + + failed = getattr(host, "_last_read_error_paths", None) + if isinstance(failed, dict): + failed.pop(session_id, None) + paths = (path for path in turns_dir.glob("*.json") if not path.name.endswith(".events.json")) + fresh: dict[Path, dict[str, object]] = {} + + def read_current(path: Path) -> dict[str, object]: + try: + payload = read(path) + except Exception: + failed_map = getattr(host, "_last_read_error_paths", None) + if not isinstance(failed_map, dict): + failed_map = {} + setattr(host, "_last_read_error_paths", failed_map) + failed_map[session_id] = path + raise + fresh[path] = payload + return payload + + for path, observation in host._terminal_turn_discovery.rows( + turns_dir, + paths, + read=read_current, + project=terminal, + ): + # Retain only the current iteration's complete read, never a body + # in the discovery cache or a second read on the cold path. + yield path, observation, fresh.pop(path, None) + + +def matched_discovered_turn( + session_id: str, + client_id: str, + path: Path, + fresh: dict[str, object] | None, +) -> dict[str, object]: + """Validate and return the complete Turn record matched during discovery.""" + from ..control_plane.collaboration.source_chat_observation import CHAT_TURN_SCHEMA_VERSION + + payload = fresh if fresh is not None else read_chat_json(path) + if ( + payload.get("schema_version") != CHAT_TURN_SCHEMA_VERSION + or payload.get("session_id") != session_id + or payload.get("turn_id") != path.stem + or payload.get("client_turn_id") != client_id + ): + raise ValueError("Matched Chat Turn is unavailable; retry the same client_turn_id.") + return payload + + +def turn_for_client( + host: IngressStoreHostProtocol, + session_id: str, + client_turn_id: str, +) -> dict[str, object] | None: + """Return the persisted Turn owned by ``client_turn_id`` in ``session_id`` if any.""" + turns_dir = host._session_dir(session_id) / "turns" + if not turns_dir.is_dir(): + return None + for path, observation, fresh in host._turn_discovery_rows(session_id, turns_dir, read_chat_json): + if observation.get("client_turn_id") != client_turn_id: + continue + # Replay validation needs the complete current record, including + # the original request body and the latest persisted result. + return host._matched_discovered_turn(session_id, client_turn_id, path, fresh) + return None + + +def queued_turns( + host: IngressStoreHostProtocol, + session_id: str, + *, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, +) -> list[dict[str, object]]: + """List ordered queued Turns projected through the TS queue selection owner.""" + from ..chat_store import TERMINAL_TURN_STATES + from ..control_plane.collaboration.source_chat_observation import CHAT_TURN_SCHEMA_VERSION + + session = host.load_session(session_id) + if session is None: + raise KeyError("chat session was not found") + active_turn_id = str(session.get("active_turn_id") or "") + turns_dir = host._session_dir(session_id) / "turns" + rows: list[dict[str, object]] = [] + valid_statuses = TERMINAL_TURN_STATES | NONTERMINAL_TURN_STATES + + def read(path: Path) -> dict[str, object]: + if strict: + try: + raw_payload: object = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise OSError("Queued Turn state is unreadable") from exc + if not is_valid_turn_record( + raw_payload, + schema_version=CHAT_TURN_SCHEMA_VERSION, + valid_statuses=valid_statuses, + session_id=session_id, + turn_id=path.stem, + ): + raise OSError("Queued Turn state is invalid") + return raw_payload + return read_chat_json(path) + + for _, payload, _ in host._turn_discovery_rows(session_id, turns_dir, read): + if ( + payload.get("schema_version") == CHAT_TURN_SCHEMA_VERSION + and payload.get("status") == "queued" + and str(payload.get("turn_id") or "") != active_turn_id + ): + rows.append(payload) + # The ordinary read has no selectable Turn when storage has no queued + # candidates. Explicit capacity and strict reads still use the owner. + if not rows and not strict and not include_reserved and capacity_at is None: + return [] + + from ..control_plane.chat_turn_acceptance import queued_chat_turn_ids + + selected = set( + queued_chat_turn_ids( + rows, + active_turn_id, + include_reserved=include_reserved, + capacity_at=capacity_at, + ) + ) + return sorted( + [row for row in rows if row["turn_id"] in selected], + key=lambda item: ( + str(item.get("created_at") or ""), + str(item.get("turn_id") or ""), + ), + ) + + +def queue_steering_lock( + host: IngressStoreHostProtocol, + session_id: str, + turn_id: str, + *, + lock_fn: LockFileFn, +) -> AbstractContextManager[object]: + """Use the same Session->Turn fences as automatic queue consumption.""" + stack = ExitStack() + try: + stack.enter_context(host._session_lock(session_id)) + stack.enter_context( + lock_fn( + host._session_path(session_id), + agent_id="loopx-chat", + operation="steer_session_queue_turn", + ) + ) + stack.enter_context( + lock_fn( + host._turn_path(session_id, turn_id), + agent_id="loopx-chat", + operation="steer_queued_chat_turn", + ) + ) + return stack + except BaseException: + stack.close() + raise + + +def _apply_queued_input_message_patch( + messages_path: Path, + *, + turn_id: str, + turn: Mapping[str, object], + receipt: Mapping[str, object], + message_patch: Mapping[str, object], + lock_fn: LockFileFn, +) -> None: + from ..chat_store import _read_jsonl + from ..file_lock import write_bytes_atomic + + with lock_fn(messages_path, agent_id="loopx-chat", operation="update_queued_input"): + rows = cast( + list[dict[str, object]], + _read_jsonl(messages_path, raise_on_error=True, strict=True), + ) + matches = [r for r in rows if r.get("turn_id") == turn_id and r.get("role") == "user"] + if len(matches) != 1: + raise OSError("Original queued input is unavailable") + row = matches[0] + if row.get("queue_input_revision", 0) != receipt["input_revision"]: + if row.get("text") != turn["message"] or row.get("attachments") != turn.get("attachments"): + raise OSError("Original queued input changed") + if "text" in message_patch: + history = row.get("queue_edit_history") + prior_history = list(history) if isinstance(history, list) else [] + row["queue_edit_history"] = [ + *prior_history, + { + "text": row["text"], + "input_revision": turn.get("input_revision", 0), + "operation_id": receipt["operation_id"], + }, + ] + row.update(message_patch) + write_bytes_atomic( + messages_path, + ("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows)).encode(), + preserve_mode=True, + ) + elif any(row.get(key) != value for key, value in message_patch.items()): + raise OSError("Queued input revision conflicts with its receipt") + + +def mutate_queued_input( + host: IngressStoreHostProtocol, + session_id: str, + turn_id: str, + request: Mapping[str, object], + *, + lock_fn: LockFileFn, +) -> dict[str, object]: + """Execute the TS owner's recoverable input plan under the consumer fences.""" + from ..chat_store import _atomic_write_json, utc_now + from ..control_plane.chat_turn_acceptance import plan_queued_chat_mutation + + with host.queue_steering_lock(session_id, turn_id): + session, turn = host.load_session(session_id), host.load_turn(session_id, turn_id) + if session is None or turn is None: + raise KeyError("chat turn was not found") + request_dict = ( + cast(dict[str, object], request) if isinstance(request, dict) else as_dict(request) + ) + plan = as_mapping(plan_queued_chat_mutation(session, turn, request_dict)) + if plan["action"] == "reject": + raise RuntimeError(str(plan["error_code"])) + receipt = as_dict(plan["receipt"]) + if plan["action"] == "apply": + if turn.get("_queue_mutation") is None: + host._recover_queued_turn_input(session_id, turn) + path = host._turn_path(session_id, turn_id) + # The receipt precedes all other writes. A partial write stays + # reserved, including across process death; only this identity + # can finish it. No native call or active-Turn interrupt occurs. + turn = { + **turn, + "_queue_mutation": receipt, + "_queue_original_message": turn.get("_queue_original_message", turn["message"]), + } + _atomic_write_json(path, turn, preserve_mode=True) + messages_path = host._session_dir(session_id) / "messages.jsonl" + _apply_queued_input_message_patch( + messages_path, + turn_id=turn_id, + turn=turn, + receipt=receipt, + message_patch=as_mapping(plan["message_patch"]), + lock_fn=lock_fn, + ) + event = as_mapping(plan["event"]) + event_kind = str(event["kind"]) + event_payload = as_dict(event["payload"]) + if not any( + e.get("kind") == event_kind and e.get("payload") == event_payload + for e in host.events_after(session_id, turn_id, None) + ): + host.append_event(session_id, turn_id, kind=event_kind, payload=event_payload) + # Metadata edits do not invent worker activity; invalidate the + # existing Session history cache without changing liveness. + session["updated_at"] = utc_now() + _atomic_write_json(host._session_path(session_id), session, preserve_mode=True) + turn.update(as_mapping(plan["turn_patch"])) + existing_ops = turn.get("_queue_operations") + prior_ops = list(existing_ops) if isinstance(existing_ops, list) else [] + turn["_queue_operations"] = [*prior_ops, receipt] + turn.pop("_queue_mutation") + if receipt["action"] == "cancel": + turn["completed_at"] = utc_now() + _atomic_write_json(path, turn, preserve_mode=True) + return { + "session_id": session_id, + "queued_turn_id": turn_id, + "operation_id": receipt["operation_id"], + "action": receipt["action"], + "input_revision": receipt["input_revision"], + "status": "applied", + } + + +def write_queue_steering( + host: IngressStoreHostProtocol, + session_id: str, + turn: dict[str, object], + plan: Mapping[str, object], +) -> dict[str, object]: + """Persist the typed plan while the caller holds both queue fences.""" + from ..chat_store import _atomic_write_json, utc_now + + if plan["action"] not in {"dispatch", "complete", "release"}: + return turn + reservation = as_dict(plan["reservation"]) + updated_turn: dict[str, object] = {**turn, "_queue_steering": reservation} + if plan["action"] == "complete": + # Keep the existing SSE response envelope for older readers. The + # adoption marker distinguishes this receipt from a model answer; + # no assistant transcript row or invented answer is published. + response: dict[str, object] = { + "schema_version": "loopx_chat_agent_response_v0", + "message": "", + "proposals": [], + "protected_action": None, + "gate": None, + } + updated_turn.update( + status="completed", + completed_at=updated_turn.get("completed_at") or utc_now(), + response=response, + ) + turn_id = str(updated_turn["turn_id"]) + _atomic_write_json(host._turn_path(session_id, turn_id), updated_turn, preserve_mode=True) + if plan["action"] == "complete": + payload: dict[str, object] = { + "steered_into_turn_id": reservation["target_turn_id"], + "response": updated_turn["response"], + } + if not any( + e.get("kind") == "turn.completed" and e.get("payload") == payload + for e in host.events_after(session_id, turn_id, None) + ): + host.append_event(session_id, turn_id, kind="turn.completed", payload=payload) + return updated_turn + + +def complete_recovered_terminalization( + host: IngressStoreHostProtocol, + session_id: str, + turn_id: str, + session: Mapping[str, object] | None, + turn: Mapping[str, object] | None, + *, + recovery_messages: Mapping[str, str], +) -> None: + """Finish the lifecycle owner's already-persisted failure, never dispatch. + + State precedes the event, error message and claim release. If one of + those writes failed, retain the exact recovery result and idempotently + finish only its missing writes under the caller's execution fence. + """ + from ..chat_store import CHAT_SESSION_MODE_MANAGED, utc_now + + if ( + session is None + or turn is None + or session.get("session_mode") != CHAT_SESSION_MODE_MANAGED + or turn.get("status") != "failed" + ): + return + code = str(turn.get("error_code") or "") + message = recovery_messages.get(code) + if message is None or (code != "server_restarted" and turn.get("error") != message): + return # Match this owner's recorded recovery, not arbitrary failures. + if not any( + event.get("kind") == "turn.failed" + and as_mapping(event.get("payload")).get("error_code") == code + and as_mapping(event.get("payload")).get("message") == message + for event in host.events_after(session_id, turn_id, None) + ): + host.append_event( + session_id, + turn_id, + kind="turn.failed", + payload={"error_code": code, "message": message}, + ) + if not any( + item.get("turn_id") == turn_id + and item.get("role") == "error" + and item.get("text") == message + for item in host.messages(session_id) + ): + host.append_message(session_id, role="error", text=message, turn_id=turn_id) + if session.get("active_turn_id") == turn_id: + host.release_active_turn( + session_id, + turn_id, + last_activity_at=str(turn.get("completed_at") or utc_now()), + last_error_code=code, + ) + + +def _build_queued_turn_payload( + *, + schema_version: str, + turn_id: str, + session_id: str, + client_id: str, + message: str, + normalized_attachments: list[dict[str, object]], + origin_id: str, + now: datetime, + now_text: str, + ttl_seconds: int | None, + goal_instance_token: str | None, + external_agent_target: Mapping[str, object] | None, + collaboration_request: Mapping[str, object] | None, +) -> dict[str, object]: + expires_at = ( + (now + timedelta(seconds=max(1, ttl_seconds))).isoformat().replace("+00:00", "Z") + if ttl_seconds is not None + else None + ) + return { + "schema_version": schema_version, + "turn_id": turn_id, + "session_id": session_id, + **({"goal_instance_id": goal_instance_token} if goal_instance_token is not None else {}), + "client_turn_id": client_id, + "status": "queued", + **({"external_agent_target": external_agent_target} if external_agent_target is not None else {}), + **({"collaboration_request": collaboration_request} if collaboration_request is not None else {}), + "message": str(message), + **({"attachments": normalized_attachments} if normalized_attachments else {}), + "origin": origin_id, + "upstream_turn_id": None, + "response": None, + "error_code": None, + "error": None, + "created_at": now_text, + "expires_at": expires_at, + "started_at": None, + "first_event_at": None, + "completed_at": None, + "last_activity_at": now_text, + "delta_count": 0, + "sse_reconnect_count": 0, + } + + +def create_queued_turn( + host: IngressStoreHostProtocol, + session_id: str, + *, + client_turn_id: str, + message: str, + attachments: Sequence[Mapping[str, object]] | None = None, + goal_instance_id: str | None = None, + ttl_seconds: int | None = None, + origin: str = "external", + external_agent_target: Mapping[str, object] | None = None, + collaboration_request: Mapping[str, object] | None = None, + max_pending: int, + lock_fn: LockFileFn, +) -> tuple[dict[str, object], bool]: + """Persist one follow-up without replacing the active Turn. + + Accepted user input has no implicit wall-clock expiry. Callers may + still supply an explicit TTL for time-sensitive work. Queue capacity, + source revalidation and Stop remain independent bounds. + """ + from ..chat import require_matching_replay + from ..chat_store import _atomic_write_json, utc_now + from ..control_plane.collaboration.source_chat_observation import ( + CHAT_TURN_SCHEMA_VERSION, + _opaque_id, + ) + + client_id = _opaque_id(client_turn_id, field="client_turn_id") + normalized_attachments = cast(list[dict[str, object]], normalize_chat_attachments(attachments)) + attachments_payload = normalized_attachments or None + if attachments_payload: + validate_chat_turn_envelope({"message": message, "attachments": attachments_payload}) + session_path = host._session_path(session_id) + with host.runtime_activation_lock(), host._session_lock(session_id): + with lock_fn( + session_path, + agent_id="loopx-chat", + operation="create_chat_queued_turn", + ): + existing = host.turn_for_client(session_id, client_id) + if existing is not None: + require_matching_replay( + {**existing, "message": existing.get("_queue_original_message", existing.get("message"))}, + identity="client_turn_id", + request={ + "message": str(message), + "attachments": attachments_payload, + "origin": _opaque_id(origin, field="origin"), + "external_agent_target": external_agent_target, + **( + {"collaboration_request": collaboration_request} + if collaboration_request is not None + else {} + ), + }, + ) + # Managed acceptance retains its own message identity and + # visible text. A queue-mode retry only replays that receipt; + # the original typed acceptance owner finishes its writes. + if "_acceptance" not in existing: + host._recover_queued_turn_input(session_id, existing) + return existing, False + session = host.load_session(session_id) + if session is None or session.get("status") == "closed": + raise KeyError("chat session was not found") + now = datetime.now(timezone.utc) + queued = host.queued_turns(session_id, include_reserved=True, capacity_at=now.isoformat()) + if len(queued) >= max_pending: + raise RuntimeError("session_queue_full") + turn_id = uuid.uuid4().hex + now_text = now.isoformat().replace("+00:00", "Z") + origin_id = _opaque_id(origin, field="origin") + goal_instance_token = ( + _opaque_id(goal_instance_id, field="goal_instance_id") + if goal_instance_id is not None + else None + ) + payload = _build_queued_turn_payload( + schema_version=CHAT_TURN_SCHEMA_VERSION, + turn_id=turn_id, + session_id=session_id, + client_id=client_id, + message=message, + normalized_attachments=normalized_attachments, + origin_id=origin_id, + now=now, + now_text=now_text, + ttl_seconds=ttl_seconds, + goal_instance_token=goal_instance_token, + external_agent_target=external_agent_target, + collaboration_request=collaboration_request, + ) + path = host._turn_path(session_id, turn_id) + _atomic_write_json(path, payload) + os.chmod(path, 0o600) + session.update( + { + "last_activity_at": now_text, + "updated_at": utc_now(), + } + ) + _atomic_write_json(session_path, session, preserve_mode=True) + # Keep the cross-process Session fence through publication: + # neither another retry nor a queue claim may overtake it. + host.append_message( + session_id, + role="user", + text=message, + turn_id=turn_id, + origin=origin, + attachments=attachments_payload, + ) + host.append_event( + session_id, + turn_id, + kind="turn.queued", + payload={"delivery_mode": "session_queue"}, + ) + return payload, True + + +def recover_queued_turn_input( + host: IngressStoreHostProtocol, + session_id: str, + turn: Mapping[str, object], +) -> None: + """Finish interrupted input IO under the caller's Session fence. + + The existing queued event follows the transcript append. It is the + publication marker, so healthy claims need no full transcript scan. + Recovery uses the saved request, never a retry's replacement text. + """ + from ..chat import require_matching_message_replay + from ..chat_store import _read_jsonl + + if "_acceptance" in turn: + raise ValueError("managed Turn acceptance must finish before queue dispatch") + turn_id = str(turn["turn_id"]) + event_path = host._event_path(session_id, turn_id) + try: + with event_path.open("rb") as stream: + first = stream.readline() + except FileNotFoundError: + first = b"" + if first.strip(): + event: object = json.loads(first) + if isinstance(event, dict) and event.get("kind") == "turn.queued": + return + host.flush_events(session_id, turn_id) + events = _read_jsonl(event_path, raise_on_error=True, strict=True) + if any(row["kind"] == "turn.queued" for row in events): + return + inputs = [ + row + for row in _read_jsonl(host._session_dir(session_id) / "messages.jsonl", raise_on_error=True, strict=True) + if row.get("turn_id") == turn_id and row.get("role") == "user" + ] + expected_attachments = turn.get("attachments") + expected: dict[str, object] = { + "message_id": "queue." + turn_id, + "role": "user", + "turn_id": turn_id, + "text": str(turn["message"]), + "origin": str(turn["origin"]), + "attachments": expected_attachments, + } + if inputs: + if len(inputs) != 1: + raise ValueError("queued Turn has ambiguous input messages") + require_matching_message_replay(inputs[0], expected) + else: + if expected_attachments is None: + attachments: list[dict[str, object]] | None = None + elif isinstance(expected_attachments, list) and all( + isinstance(item, dict) for item in expected_attachments + ): + attachments = cast(list[dict[str, object]], expected_attachments) + else: + raise ValueError("queued Turn attachments must be null or a list of objects") + host.append_message( + session_id, + message_id="queue." + turn_id, + role="user", + turn_id=turn_id, + text=str(turn["message"]), + origin=str(turn["origin"]), + attachments=attachments, + ) + host.append_event(session_id, turn_id, kind="turn.queued", payload={"delivery_mode": "session_queue"}) diff --git a/loopx/chat/ingress_receipts.py b/loopx/chat/ingress_receipts.py new file mode 100644 index 0000000000..bf279e2531 --- /dev/null +++ b/loopx/chat/ingress_receipts.py @@ -0,0 +1,173 @@ +"""Idempotent steering and ingress receipt operations for ``ChatIngressStore``.""" +from __future__ import annotations + +from contextlib import AbstractContextManager +import json +import os +from pathlib import Path +from typing import cast + +from .ingress_common import IngressStoreHostProtocol, LockFileFn, as_str, read_chat_json + + +def strict_ingress_receipt( + host: IngressStoreHostProtocol, + session_id: str, + ingress_id: str, +) -> dict[str, object] | None: + """Absent is ``None``; any other unreadable receipt fails closed.""" + from ..chat_store import CHAT_INGRESS_SCHEMA_VERSION + from ..control_plane.collaboration.source_chat_observation import _opaque_id + + # The receipt is stored under the normalized id, so a replay that repeats + # the original (padded) text must be matched against that same id. + ingress_id = _opaque_id(ingress_id, field="client_ingress_id") + path = host._ingress_path(session_id, ingress_id) + try: + value: object = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError as exc: + if os.path.lexists(path): + # A link whose target is gone is an existing entry, not absence: + # replacing it would resend a message that may have been delivered. + raise OSError("Ingress receipt is unreadable") from exc + return None + except (OSError, ValueError) as exc: + raise OSError("Ingress receipt is unreadable") from exc + if ( + not isinstance(value, dict) + or value.get("schema_version") != CHAT_INGRESS_SCHEMA_VERSION + or value.get("session_id") != session_id + or value.get("client_ingress_id") != ingress_id + ): + raise OSError("Ingress receipt is unreadable") + return cast(dict[str, object], value) + + +def steering_delivery_lock( + host: IngressStoreHostProtocol, + session_id: str, + ingress_id: str, + *, + lock_fn: LockFileFn, +) -> AbstractContextManager[Path]: + """Serialize one native send and its later readback across controllers.""" + return lock_fn( + host._ingress_path(session_id, ingress_id).with_suffix(".delivery"), + agent_id="loopx-chat", + operation="chat_steering_delivery", + ) + + +def create_ingress_receipt( + host: IngressStoreHostProtocol, + session_id: str, + *, + client_ingress_id: str, + mode: str, + message: str, + expected_turn_id: str | None = None, + lock_fn: LockFileFn, +) -> tuple[dict[str, object], bool]: + """Reserve one idempotent external ingress before provider delivery.""" + from ..chat import require_matching_replay + from ..chat_store import ( + CHAT_INGRESS_SCHEMA_VERSION, + _atomic_write_json, + utc_now, + ) + from ..control_plane.collaboration.source_chat_observation import _opaque_id + + if host.load_session(session_id) is None: + raise KeyError("chat session was not found") + path = host._ingress_path(session_id, client_ingress_id) + with lock_fn( + path, + agent_id="loopx-chat", + operation="create_chat_ingress_receipt", + ): + # A damaged receipt may record a delivered send. It is not absence: + # recreating it would resend the message and erase that evidence. + existing = host._strict_ingress_receipt(session_id, client_ingress_id) + if existing is not None: + request: dict[str, object] = { + "mode": _opaque_id(mode, field="mode"), + "message": str(message), + } + if expected_turn_id is not None or "expected_turn_id" in existing: + request["expected_turn_id"] = expected_turn_id + require_matching_replay( + existing, + identity="client_ingress_id", + request=request, + ) + return existing, False + now = utc_now() + payload: dict[str, object] = { + "schema_version": CHAT_INGRESS_SCHEMA_VERSION, + "client_ingress_id": _opaque_id( + client_ingress_id, + field="client_ingress_id", + ), + "session_id": session_id, + "mode": _opaque_id(mode, field="mode"), + "status": "pending", + "message": str(message), + "active_turn_id": None, + **( + {"expected_turn_id": _opaque_id(expected_turn_id, field="expected_turn_id")} + if expected_turn_id is not None + else {} + ), + "error_code": None, + "created_at": now, + "updated_at": now, + } + _atomic_write_json(path, payload) + os.chmod(path, 0o600) + return payload, True + + +def update_ingress_receipt( + host: IngressStoreHostProtocol, + session_id: str, + client_ingress_id: str, + lock_fn: LockFileFn, + /, + **changes: object, +) -> dict[str, object]: + """Update allowed fields on an existing Chat ingress receipt under its file lock.""" + from ..chat_store import ( + CHAT_INGRESS_SCHEMA_VERSION, + _atomic_write_json, + utc_now, + ) + + path = host._ingress_path(session_id, client_ingress_id) + with lock_fn( + path, + agent_id="loopx-chat", + operation="update_chat_ingress_receipt", + ): + payload = read_chat_json(path) + if payload.get("schema_version") != CHAT_INGRESS_SCHEMA_VERSION: + raise KeyError("chat ingress receipt was not found") + allowed = {"status", "active_turn_id", "error_code", "native_steering"} + unknown = set(changes) - allowed + if unknown: + raise ValueError(f"unsupported chat ingress fields: {sorted(unknown)}") + payload.update(changes) + payload["updated_at"] = utc_now() + _atomic_write_json(path, payload, preserve_mode=True) + return payload + + +def loopx_ingress(host: IngressStoreHostProtocol, session_id: str) -> list[dict[str, object]]: + """Read the existing ingress ledger; no second queue or delivery truth.""" + rows = [ + read_chat_json(path) + for path in (host._session_dir(session_id) / "ingress").glob("*.json") + ] + return sorted( + (row for row in rows if row.get("mode") in {"loopx_queue", "loopx_inbox"}), + key=lambda row: (as_str(row.get("created_at")), as_str(row.get("client_ingress_id"))), + ) diff --git a/tests/test_chat_ingress_contract.py b/tests/test_chat_ingress_contract.py new file mode 100644 index 0000000000..3548c3ceb6 --- /dev/null +++ b/tests/test_chat_ingress_contract.py @@ -0,0 +1,375 @@ +"""Contract and boundary tests for the modular Zero-Any ``loopx.chat.ingress`` slice.""" +from __future__ import annotations + +import ast +import base64 +from collections.abc import Mapping, Sequence +import importlib.util +import inspect +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +import pytest + +from loopx.capabilities.native_chat.conversation_bindings import ChatConversationBindings +from loopx.chat.ingress import ( + ChatIngressStore, + chat_runtime_activation_state, +) +from loopx.chat.ingress_common import ( + AdmissionStoreProtocol, + ConversationBindingsProtocol, + IngressStoreHostProtocol, +) +from loopx.chat_store import ChatSessionStore + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_MYPY_SUCCESS_RE = re.compile(r"^Success: no issues found in (\d+) source files?\s*$", re.MULTILINE) +_MYPY_FOUND_RE = re.compile( + r"^Found (\d+) errors? in (\d+) files? \(checked (\d+) source files?\)\s*$", + re.MULTILINE, +) + +_INGRESS_MODULES = ( + "loopx/chat/ingress.py", + "loopx/chat/ingress_common.py", + "loopx/chat/ingress_admission.py", + "loopx/chat/ingress_queue.py", + "loopx/chat/ingress_receipts.py", +) + + +def _collect_mypy_contract_errors( + proc: subprocess.CompletedProcess[str], + *, + probe: Path, + callers: Sequence[str], +) -> tuple[list[str], dict[str, list[str]]]: + expected_files = 1 + len(callers) + details = f"rc={proc.returncode}\nSTDOUT:\n{proc.stdout.strip()}\nSTDERR:\n{proc.stderr.strip()}" + if proc.returncode not in (0, 1): + raise AssertionError(f"mypy exited unexpectedly:\n{details}") + if proc.stderr.strip(): + raise AssertionError(f"mypy reported errors on stderr:\n{details}") + if proc.returncode == 0: + match = _MYPY_SUCCESS_RE.search(proc.stdout) + if match is None or int(match.group(1)) != expected_files: + raise AssertionError(f"mypy did not inspect all {expected_files} files:\n{details}") + else: + found = _MYPY_FOUND_RE.search(proc.stdout) + if found is None or int(found.group(3)) != expected_files or int(found.group(1)) <= 0: + raise AssertionError(f"mypy failed or aborted before checking {expected_files} files:\n{details}") + + probe_errors: list[str] = [] + caller_errors: dict[str, list[str]] = {path: [] for path in callers} + probe_prefix = f"{probe}:" + for line in proc.stdout.splitlines(): + if ": error:" not in line: + continue + if line.startswith(probe_prefix): + probe_errors.append(line) + continue + for caller in callers: + if line.startswith(f"{caller}:"): + caller_errors[caller].append(line) + break + return probe_errors, caller_errors + + +def _run_mypy_contract_probe( + tmp_path: Path, + *, + probe_lines: Sequence[str], + callers: Sequence[str], + extra_env: Mapping[str, str] | None = None, +) -> tuple[list[str], dict[str, list[str]]]: + if importlib.util.find_spec("mypy") is None: + pytest.skip("mypy optional test dependency is unavailable") + probe = tmp_path / "ingress_contract_probe.py" + probe.write_text("\n".join([*probe_lines, ""]), encoding="utf-8") + cmd = [ + sys.executable, + "-m", + "mypy", + "--config-file", + str(_REPO_ROOT / "pyproject.toml"), + "--no-incremental", + "--follow-imports=silent", + "--cache-dir", + str(tmp_path / ".mypy_cache"), + "--show-error-codes", + str(probe), + *callers, + ] + env = {**os.environ, **extra_env} if extra_env is not None else None + proc = subprocess.run(cmd, cwd=_REPO_ROOT, env=env, capture_output=True, text=True, check=False) + return _collect_mypy_contract_errors(proc, probe=probe, callers=callers) + + +def test_chat_ingress_modules_meet_loc_zero_any_and_layout_pins() -> None: + assert ChatIngressStore.__module__ == "loopx.chat.ingress" + assert importlib.util.find_spec("loopx.chat_ingress") is None + + for rel in (*_INGRESS_MODULES, "tests/test_chat_ingress_contract.py"): + src = (_REPO_ROOT / rel).read_text(encoding="utf-8") + tree = ast.parse(src) + any_hits = sum(isinstance(node, ast.Name) and node.id == "Any" for node in ast.walk(tree)) + ignore_marker = "# " + "type: ignore" + noqa_marker = "# " + "noqa" + ignores = sum(ignore_marker in line for line in src.splitlines()) + noqas = sum(noqa_marker in line for line in src.splitlines()) + loc = len(src.splitlines()) + assert any_hits == 0, f"{rel} leaked AST Any" + assert ignores == 0, f"{rel} leaked type-ignore comment" + assert noqas == 0, f"{rel} leaked noqa comment" + if rel == "loopx/chat/ingress.py": + assert loc <= 550, f"{rel} exceeded 550 LOC ({loc})" + elif rel.startswith("loopx/chat/"): + assert loc < 750, f"{rel} exceeded 750 LOC ({loc})" + + +def test_real_store_and_bindings_match_ingress_protocols(tmp_path: Path) -> None: + store = ChatSessionStore(tmp_path / "runtime", startup_maintenance=False) + bindings = ChatConversationBindings( + root=tmp_path / "runtime" / "chat", + project_contexts=object(), + observe=lambda _ref: {}, + ) + assert isinstance(store, ChatIngressStore) + assert bindings.controller is None + + method_checks: tuple[tuple[type[object], type[object], str], ...] = ( + (IngressStoreHostProtocol, ChatSessionStore, "load_session"), + (IngressStoreHostProtocol, ChatSessionStore, "load_turn"), + (IngressStoreHostProtocol, ChatSessionStore, "events_after"), + (IngressStoreHostProtocol, ChatSessionStore, "messages"), + (IngressStoreHostProtocol, ChatSessionStore, "append_event"), + (IngressStoreHostProtocol, ChatSessionStore, "append_message"), + (IngressStoreHostProtocol, ChatSessionStore, "release_active_turn"), + (IngressStoreHostProtocol, ChatSessionStore, "flush_events"), + (AdmissionStoreProtocol, ChatSessionStore, "resumable_session_candidates"), + (ConversationBindingsProtocol, ChatConversationBindings, "read"), + (ConversationBindingsProtocol, ChatConversationBindings, "resolve"), + (ConversationBindingsProtocol, ChatConversationBindings, "ensure_delivery_scope"), + (ConversationBindingsProtocol, ChatConversationBindings, "_ensure_delivery_scope"), + ) + for proto_cls, real_cls, name in method_checks: + proto_params = list(inspect.signature(getattr(proto_cls, name)).parameters.items())[1:] + real_params = inspect.signature(getattr(real_cls, name)).parameters + for param_name, proto_param in proto_params: + if proto_param.kind is inspect.Parameter.VAR_KEYWORD: + assert any(p.kind is inspect.Parameter.VAR_KEYWORD for p in real_params.values()) + continue + assert param_name in real_params, f"{real_cls.__name__}.{name} missing {param_name!r}" + + +def test_real_store_and_callers_mypy_contract(tmp_path: Path) -> None: + callers = [ + "loopx/chat_store.py", + "loopx/runtime_activation.py", + "loopx/capabilities/native_chat/external_conversations.py", + "loopx/capabilities/native_chat/external_mention_recovery.py", + "loopx/extensions/lark/goal_topic_runtime.py", + "loopx/extensions/lark/goal_topic_runtime_service.py", + "loopx/extensions/lark/private_topic_lanes.py", + ] + probe_errors, caller_errors = _run_mypy_contract_probe( + tmp_path, + probe_lines=[ + "from loopx.capabilities.native_chat.conversation_bindings import ChatConversationBindings", + "from loopx.chat.ingress_common import ConversationBindingsProtocol, IngressStoreHostProtocol", + "from loopx.chat_store import ChatSessionStore", + "", + "def bind_store(store: ChatSessionStore) -> IngressStoreHostProtocol:", + " return store", + "", + "def bind_bindings(bindings: ChatConversationBindings) -> ConversationBindingsProtocol:", + " return bindings", + ], + callers=callers, + ) + assert not probe_errors, f"Ingress protocol probe errors: {probe_errors}" + assert len(caller_errors["loopx/chat_store.py"]) <= 4 + assert len(caller_errors["loopx/runtime_activation.py"]) <= 2 + assert len(caller_errors["loopx/capabilities/native_chat/external_conversations.py"]) <= 33 + assert caller_errors["loopx/capabilities/native_chat/external_mention_recovery.py"] == [] + assert caller_errors["loopx/extensions/lark/goal_topic_runtime.py"] == [] + assert caller_errors["loopx/extensions/lark/goal_topic_runtime_service.py"] == [] + assert caller_errors["loopx/extensions/lark/private_topic_lanes.py"] == [] + + +def test_ingress_receipts_queue_and_strict_activation_contracts( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + runtime = tmp_path / "runtime" + store = ChatSessionStore(runtime, startup_maintenance=False) + created_session = store.create_session( + goal_id="g-ingress", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id="thread-1", + ) + sid = str(created_session["session_id"]) + + monkeypatch.setattr("loopx.chat.ingress.SESSION_QUEUE_MAX_PENDING", 1) + queued_one, created_flag = store.create_queued_turn( + sid, + client_turn_id="q-1", + message="first item", + origin="external", + ) + assert created_flag is True + replay_one, replay_flag = store.create_queued_turn( + sid, + client_turn_id="q-1", + message="first item", + origin="external", + ) + assert replay_flag is False + assert replay_one["turn_id"] == queued_one["turn_id"] + with pytest.raises(ValueError, match="client_turn_id already belongs to a different request"): + store.create_queued_turn(sid, client_turn_id="q-1", message="mutated", origin="external") + with pytest.raises(RuntimeError, match="session_queue_full"): + store.create_queued_turn(sid, client_turn_id="q-2", message="overflow", origin="external") + + active_ids: list[str] = [] + counts = chat_runtime_activation_state(runtime, active_session_ids=active_ids) + assert counts == {"sessions": 1, "nonterminal_turns": 1} + assert active_ids == [] + + receipt, receipt_created = store.create_ingress_receipt( + sid, + client_ingress_id="ing-1", + mode="loopx_queue", + message="hello", + ) + assert receipt_created is True and receipt["status"] == "pending" + updated = store.update_ingress_receipt(sid, "ing-1", status="delivered") + assert updated["status"] == "delivered" + with pytest.raises(ValueError, match="unsupported chat ingress fields"): + store.update_ingress_receipt(sid, "ing-1", lock_fn="unexpected") + assert [row["client_ingress_id"] for row in store.loopx_ingress(sid)] == ["ing-1"] + + dangling = store._ingress_path(sid, "ing-dangling") + dangling.parent.mkdir(parents=True, exist_ok=True) + dangling.symlink_to(tmp_path / "missing-target.json") + with pytest.raises(OSError, match="Ingress receipt is unreadable"): + store.steering_receipt(sid, "ing-dangling") + + turn_path = store._turn_path(sid, str(queued_one["turn_id"])) + bad_turn = dict(queued_one) + bad_turn["status"] = "corrupt_status" + turn_path.write_text(json.dumps(bad_turn), encoding="utf-8") + with pytest.raises(OSError, match="Queued Turn state is invalid"): + store.queued_turns(sid, strict=True) + with pytest.raises(ValueError, match="unreadable Chat Turn state"): + chat_runtime_activation_state(runtime) + + +def test_recover_queued_turn_input_preserves_valid_and_rejects_malformed_attachments( + tmp_path: Path, +) -> None: + store = ChatSessionStore(tmp_path / "runtime", startup_maintenance=False) + created_session = store.create_session( + goal_id="g-recover", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id="thread-recover", + ) + sid = str(created_session["session_id"]) + + # 1) Interrupted write with valid list attachments preserves exact list and recovers claim. + spec_bytes = b"# Spec\n" + valid_att = [{ + "id": "att-1", + "mime_type": "text/markdown", + "name": "spec.md", + "size": len(spec_bytes), + "data_url": f"data:text/markdown;base64,{base64.b64encode(spec_bytes).decode('ascii')}", + }] + valid_turn, created = store.create_queued_turn( + sid, + client_turn_id="q-valid-att", + message="with attachment", + attachments=valid_att, + origin="web", + ) + assert created is True + valid_tid = str(valid_turn["turn_id"]) + (store._session_dir(sid) / "messages.jsonl").unlink() + store._event_path(sid, valid_tid).unlink() + claimed = store.claim_next_queued_turn(sid, host_claim_id="claim-valid") + assert claimed is not None and str(claimed["turn_id"]) == valid_tid + msgs = [m for m in store.messages(sid) if m.get("turn_id") == valid_tid] + assert len(msgs) == 1 and msgs[0].get("attachments") == valid_att + assert any(e.get("kind") == "turn.queued" for e in store.events_after(sid, valid_tid, None)) + assert store.release_active_turn(sid, valid_tid) + store.update_turn(sid, valid_tid, status="completed") + + # 2) Interrupted write with non-empty non-list or non-dict attachments fails closed BEFORE + # writing messages.jsonl or turn.queued, keeping the turn queued/pending recovery. + for idx, bad_att in enumerate(({"name": "legacy-att"}, "persisted.txt", ["bad-item"])): + queued, _ = store.create_queued_turn( + sid, + client_turn_id=f"q-bad-{idx}", + message=f"bad {idx}", + origin="web", + ) + tid = str(queued["turn_id"]) + turn_path = store._turn_path(sid, tid) + raw_turn = json.loads(turn_path.read_text(encoding="utf-8")) + raw_turn["attachments"] = bad_att + turn_path.write_text(json.dumps(raw_turn), encoding="utf-8") + messages_path = store._session_dir(sid) / "messages.jsonl" + prior_msgs = messages_path.read_text(encoding="utf-8") + store._event_path(sid, tid).unlink() + with pytest.raises(ValueError, match="attachments"): + store.claim_next_queued_turn(sid, host_claim_id=f"claim-bad-{idx}") + assert messages_path.read_text(encoding="utf-8") == prior_msgs + assert not store._event_path(sid, tid).exists() + reloaded = store.load_turn(sid, tid) + assert reloaded is not None and reloaded["status"] == "queued" + # Clean up this bad turn so subsequent iterations inspect the next fixture cleanly. + store.update_turn(sid, tid, status="failed", error_code="test_cleanup") + + # 3) Interrupted event flush when messages.jsonl already recorded the input replays cleanly. + legacy_att: object = {"name": "legacy-att"} + replayed, _ = store.create_queued_turn( + sid, + client_turn_id="q-legacy-replay", + message="legacy replay", + origin="web", + ) + replay_tid = str(replayed["turn_id"]) + turn_path = store._turn_path(sid, replay_tid) + raw_replay = json.loads(turn_path.read_text(encoding="utf-8")) + raw_replay["attachments"] = legacy_att + turn_path.write_text(json.dumps(raw_replay), encoding="utf-8") + store._event_path(sid, replay_tid).unlink() + messages_path = store._session_dir(sid) / "messages.jsonl" + msg_rows = [json.loads(line) for line in messages_path.read_text(encoding="utf-8").splitlines() if line.strip()] + for row in msg_rows: + if row.get("turn_id") == replay_tid and row.get("role") == "user": + row["attachments"] = legacy_att + messages_path.write_text( + "".join(json.dumps(row) + "\n" for row in msg_rows), + encoding="utf-8", + ) + claimed_replay = store.claim_next_queued_turn(sid, host_claim_id="claim-legacy-replay") + assert claimed_replay is not None and str(claimed_replay["turn_id"]) == replay_tid + assert any(e.get("kind") == "turn.queued" for e in store.events_after(sid, replay_tid, None)) + assert store.release_active_turn(sid, replay_tid) + store.update_turn(sid, replay_tid, status="completed") + + # 4) Turn discovery read error populates host._last_read_error_paths[session_id]. + corrupt_path = store._turn_path(sid, "corruptturn001") + corrupt_path.write_text("{not-json", encoding="utf-8") + with pytest.raises(OSError, match="Queued Turn state is unreadable"): + store.queued_turns(sid, strict=True) + failed_map = getattr(store, "_last_read_error_paths", None) + assert isinstance(failed_map, dict) and failed_map.get(sid) == corrupt_path