From 367a629c9a00e3e47b17ba528ef2b4ca010b1562 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:55:57 +0800 Subject: [PATCH 1/2] refactor(turn_driver): slim codex_context_history and remove Any typing Split loopx/control_plane/turn_driver/codex_context_history.py into codex_context_history_json.py and codex_context_history_replay.py with zero Any annotations and preserve the bare POSIX flag ceiling. Reuse already-read bounded chunks for in-chunk JSONL lines in _reader_slices/_native_reader to avoid redundant per-line seek/read syscalls. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../turn_driver/codex_context_history.py | 1055 ++++++----------- .../turn_driver/codex_context_history_json.py | 340 ++++++ .../codex_context_history_replay.py | 493 ++++++++ .../test_codex_context_history_contract.py | 318 +++++ 4 files changed, 1505 insertions(+), 701 deletions(-) create mode 100644 loopx/control_plane/turn_driver/codex_context_history_json.py create mode 100644 loopx/control_plane/turn_driver/codex_context_history_replay.py create mode 100644 tests/control_plane/test_codex_context_history_contract.py diff --git a/loopx/control_plane/turn_driver/codex_context_history.py b/loopx/control_plane/turn_driver/codex_context_history.py index a0956d2737..6a2d947540 100644 --- a/loopx/control_plane/turn_driver/codex_context_history.py +++ b/loopx/control_plane/turn_driver/codex_context_history.py @@ -9,62 +9,63 @@ """ from __future__ import annotations -import codecs +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager import hashlib import json import os -import re -import stat -from collections.abc import Iterator, Mapping -from contextlib import contextmanager from pathlib import Path -from typing import Any, BinaryIO - -# A compatibility profile of the native rollout, not a shared control vocabulary. -# Unknown record types fall back to full until their replay semantics qualify. -_APPEND_RECORDS = {"response_item", "turn_context", "world_state", "token_usage_record"} -_APPEND_EVENTS = {"task_started", "task_complete", "item_completed", "token_count", - "thread_settings_applied", "exec_command_begin", "exec_command_end", "agent_message", - "agent_reasoning", "agent_reasoning_raw_content", "agent_reasoning_section_break", - "agent_reasoning_raw_content_delta", "agent_reasoning_delta", "agent_message_delta", - "hook_started", "hook_completed", "warning", "error", "stream_error", "turn_aborted", - "terminal_interaction", "background_event"} -_IO_CHUNK_BYTES = 64 * 1024 -# Bound one decoded protocol record, not the history or the replay interval. -_MAX_RECORD_BYTES = 16 * 1024 * 1024 -_MAX_HEADER_FIELD_BYTES = 16 * 1024 -_MAX_PRIMITIVE_BYTES = 1024 -_MAX_SKIP_DEPTH = 256 -_MAX_SELECTED_REPLAY_READS = 32 -_MAX_COMPLETE_REREADS = 32 -_SHELL_OUTPUT = re.compile(r"\AChunk ID: [^\r\n]+\nWall time: [0-9.]+ seconds\n" - r"Process exited with code 0\n(?:Original token count: [0-9]+\n)?Output:\n(.*)\Z", re.DOTALL) -_JSON_WS_STOP = re.compile(rb"[^ \t\r\n]") -_JSON_STR_SPAN = re.compile(rb'(?:[^"\\\x00-\x1f]+|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})){1,64}') -_JSON_DIGITS = re.compile(rb"[0-9]+") -_JSON_PRIMITIVE_STOP = frozenset(b" \t\r\n,}]") -_JSON_TOKEN_STOP = re.compile(rb"[ \t\r\n,\}\]]") -_PREFIX_PAYLOAD_SPEC: dict[str, Any] = { - "type": None, - "call_id": None, - "name": None, - "turn_id": None, - "item": {"type": None, "id": None, "exit_code": None}, - "internal_chat_message_metadata_passthrough": {"turn_id": None}, -} -_PREFIX_RECORD_SPEC: dict[str, Any] = {"type": None, "payload": _PREFIX_PAYLOAD_SPEC} -_REPLAY_ERRORS = (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError) -_SOURCE_IDENTITY_FIELDS = ("path", "device", "inode", "metadata_sha256", "model", "permission_mode") - - -def _digest(value: object) -> str: - return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, - separators=(",", ":")).encode()).hexdigest() +import stat +from typing import BinaryIO, cast + +from .codex_context_history_json import ( + _IO_CHUNK_BYTES as _IO_CHUNK_BYTES, + _MAX_HEADER_FIELD_BYTES as _MAX_HEADER_FIELD_BYTES, + _MAX_PRIMITIVE_BYTES as _MAX_PRIMITIVE_BYTES, + _MAX_RECORD_BYTES as _MAX_RECORD_BYTES, + _MAX_SKIP_DEPTH as _MAX_SKIP_DEPTH, + _PREFIX_PAYLOAD_SPEC as _PREFIX_PAYLOAD_SPEC, + _PREFIX_RECORD_SPEC as _PREFIX_RECORD_SPEC, + _JsonSliceCursor as _JsonSliceCursor, + _digest as _digest, + _reject_json_constant as _reject_json_constant, + _scan_selected_object as _scan_selected_object, + _scan_turn_prefix_record as _scan_turn_prefix_record, +) +from .codex_context_history_replay import ( + _APPEND_EVENTS as _APPEND_EVENTS, + _APPEND_RECORDS as _APPEND_RECORDS, + _MAX_COMPLETE_REREADS as _MAX_COMPLETE_REREADS, + _MAX_SELECTED_REPLAY_READS as _MAX_SELECTED_REPLAY_READS, + _REPLAY_ERRORS as _REPLAY_ERRORS, + _SOURCE_IDENTITY_FIELDS as _SOURCE_IDENTITY_FIELDS, + _append_only as _append_only, + _covers_bytes as _covers_bytes, + _emission_pages as _emission_pages, + _mapping_field, + _matches as _matches, + _matching_replay_interval as _matching_replay_interval, + _matching_resume_session as _matching_resume_session, + _native_reader as _native_reader, + _read_pages as _read_pages, + _read_receipt as _read_receipt, + _reader_slices as _reader_slices, + _reader_spans as _reader_spans, + _records as _records, + _region_digest as _region_digest, + _replayed_output_groups as _replayed_output_groups, + _replayed_selection_sections as _replayed_selection_sections, + _same_replay_source as _same_replay_source, + _turn_boundary as _turn_boundary, + _verified_replay_capture as _verified_replay_capture, +) @contextmanager -def _snapshot(event: dict[str, Any]) -> Iterator[tuple[dict[str, Any], BinaryIO]]: - path = Path(event.get("transcript_path") or "") +def _snapshot( + event: Mapping[str, object], +) -> Iterator[tuple[dict[str, object], BinaryIO]]: + path = Path(str(event.get("transcript_path") or "")) if not path.is_absolute() or path.resolve(strict=True) != path: raise ValueError("native replay source must be physical and absolute") # Inspect the opened descriptor before reading. A FIFO must not wait for a @@ -72,671 +73,198 @@ def _snapshot(event: dict[str, Any]) -> Iterator[tuple[dict[str, Any], BinaryIO] descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) with os.fdopen(descriptor, "rb") as stream: info = os.fstat(stream.fileno()) - if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() - or info.st_ino != path.lstat().st_ino - or info.st_mode & 0o022 or info.st_size <= 0): + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != os.getuid() + or info.st_ino != path.lstat().st_ino + or info.st_mode & 0o022 + or info.st_size <= 0 + ): raise ValueError("native replay source must be an owned regular file") first_raw = stream.readline(_MAX_RECORD_BYTES + 1) if len(first_raw) > _MAX_RECORD_BYTES or not first_raw.endswith(b"\n"): raise ValueError("invalid native session metadata") first = json.loads(first_raw) - meta = first.get("payload", {}) - if (first.get("type") != "session_meta" or meta.get("id") != event.get("session_id") - or meta.get("cwd") != event.get("cwd") or meta.get("forked_from_id") - or meta.get("history_mode") != "paginated" - or meta.get("cli_version") not in ( - "0.153.4", "0.162.1", "0.163.0-alpha.11.1", "0.163.0-alpha.11.2", - "0.166.0-alpha.5.1", "0.167.0-alpha.3.2", "0.169.0-alpha.11.1") - or not event.get("model") or not event.get("permission_mode")): + if not isinstance(first, Mapping): + raise ValueError("invalid native session metadata") + meta = _mapping_field(first, "payload") + if ( + first.get("type") != "session_meta" + or meta.get("id") != event.get("session_id") + or meta.get("cwd") != event.get("cwd") + or meta.get("forked_from_id") + or meta.get("history_mode") != "paginated" + or meta.get("cli_version") + not in ( + "0.153.4", + "0.162.1", + "0.163.0-alpha.11.1", + "0.163.0-alpha.11.2", + "0.166.0-alpha.5.1", + "0.167.0-alpha.3.2", + "0.169.0-alpha.11.1", + ) + or not event.get("model") + or not event.get("permission_mode") + ): raise ValueError("unqualified native replay metadata") stream.seek(info.st_size - 1) if stream.read(1) != b"\n": raise ValueError("native replay observation ends within a record") # cli_version describes the original writer, not the current host. # Qualify the supported replay records below, including after upgrade. - facts = {"path": str(path), "device": str(info.st_dev), "inode": str(info.st_ino), + facts: dict[str, object] = { + "path": str(path), + "device": str(info.st_dev), + "inode": str(info.st_ino), "metadata_sha256": hashlib.sha256(first_raw).hexdigest(), - "observed_bytes": info.st_size, "model": event["model"], - "permission_mode": event["permission_mode"]} + "observed_bytes": info.st_size, + "model": event["model"], + "permission_mode": event["permission_mode"], + } yield facts, stream after = os.fstat(stream.fileno()) - if (after.st_size != info.st_size or after.st_mtime_ns != info.st_mtime_ns - or path.lstat().st_ino != info.st_ino): + if ( + after.st_size != info.st_size + or after.st_mtime_ns != info.st_mtime_ns + or path.lstat().st_ino != info.st_ino + ): raise ValueError("native replay source changed during observation") -def _records(stream: BinaryIO, start: int, end: int) -> Iterator[tuple[int, dict[str, Any]]]: - stream.seek(start) - while stream.tell() < end: - offset = stream.tell() - raw = stream.readline(min(_MAX_RECORD_BYTES + 1, end - offset)) - if len(raw) > _MAX_RECORD_BYTES or not raw.endswith(b"\n"): - raise ValueError("incomplete or unsupported native replay record") - yield offset, json.loads(raw) - - -def _region_digest(stream: BinaryIO, start: int, end: int) -> str: - digest = hashlib.sha256() - stream.seek(start) - remaining = end - start - while remaining: - chunk = stream.read(min(_IO_CHUNK_BYTES, remaining)) - if not chunk: - raise ValueError("native reader interval was truncated") - digest.update(chunk) - remaining -= len(chunk) - return digest.hexdigest() - - -def _reader_spans(stream: BinaryIO, end: int) -> Iterator[tuple[int, int]]: - """Walk backwards from the hook one bounded chunk at a time, yielding line spans.""" - if end <= 0: - return - stream.seek(end - 1) - if stream.read(1) != b"\n": - raise ValueError("incomplete native reader record") - line_end = end - cursor = end - 1 - while cursor > 0: - chunk_start = max(0, cursor - _IO_CHUNK_BYTES) - stream.seek(chunk_start) - chunk = stream.read(cursor - chunk_start) - if len(chunk) != cursor - chunk_start: - raise ValueError("native reader interval was truncated") - pos = len(chunk) - while True: - split = chunk.rfind(b"\n", 0, pos) - if split < 0: - break - line_start = chunk_start + split + 1 - if line_end > line_start: - yield line_start, line_end - line_end = line_start - pos = split - cursor = chunk_start - if line_end > 0: - yield 0, line_end - - -def _reject_json_constant(token: str) -> Any: - raise ValueError(f"unsupported JSON constant: {token}") - - -class _JsonSliceCursor: - """Chunked JSON validator and header extractor for oversized Turn-prefix records.""" - - def __init__(self, stream: BinaryIO, start: int, stop: int) -> None: - stream.seek(start) - self._stream = stream - self._cursor = start - self._stop = stop - self._buf = b"" - self._pos = 0 - - def _ensure(self, n: int = 1) -> bool: - while len(self._buf) - self._pos < n and self._cursor < self._stop: - chunk = self._stream.read(min(_IO_CHUNK_BYTES, self._stop - self._cursor)) - if not chunk: - raise ValueError("native reader interval was truncated") - self._cursor += len(chunk) - self._buf = self._buf[self._pos:] + chunk - self._pos = 0 - return len(self._buf) - self._pos >= n - - def _peek_byte(self) -> int | None: - if self._pos >= len(self._buf) and not self._ensure(1): - return None - return self._buf[self._pos] - - def _consume_digits(self) -> bool: - matched = False - while True: - if self._pos >= len(self._buf) and not self._ensure(1): - return matched - match = _JSON_DIGITS.match(self._buf, self._pos) - if match is None: - return matched - matched = True - self._pos = match.end() - - def skip_ws(self) -> int | None: - while True: - if self._pos >= len(self._buf) and not self._ensure(1): - return None - match = _JSON_WS_STOP.search(self._buf, self._pos) - if match is not None: - self._pos = match.start() - return self._buf[self._pos] - self._pos = len(self._buf) - - def consume_byte(self, expected: int) -> None: - if not self._ensure(1) or self._buf[self._pos] != expected: - raise ValueError("malformed native JSON record") - self._pos += 1 - - def scan_string(self, *, capture_limit: int | None = None, allow_long_key: bool = False) -> str: - self.consume_byte(0x22) - decoder = codecs.getincrementaldecoder("utf-8")("strict") - raw: bytearray | None = bytearray(b'"') if capture_limit is not None else None - - def _append_raw(data: bytes) -> bytearray | None: - if raw is None or capture_limit is None: - return None - if len(raw) + len(data) > capture_limit: - if not allow_long_key: - raise ValueError("oversized JSON header field") - return None - raw.extend(data) - return raw - - while True: - if self._pos >= len(self._buf) and not self._ensure(1): - raise ValueError("unterminated JSON string") - match = _JSON_STR_SPAN.match(self._buf, self._pos) - if match is not None: - seg = self._buf[self._pos:match.end()] - decoder.decode(seg, final=False) - raw = _append_raw(seg) - self._pos = match.end() - continue - ch = self._buf[self._pos] - if ch == 0x22: - decoder.decode(b"", final=True) - self._pos += 1 - raw = _append_raw(b'"') - return "" if raw is None else str(json.loads(bytes(raw))) - if ch == 0x5c and len(self._buf) - self._pos < 6 and self._cursor < self._stop: - before = len(self._buf) - self._pos - self._ensure(6) - if len(self._buf) - self._pos > before: - continue - raise ValueError("invalid JSON string") - - def read_primitive(self) -> Any: - raw = bytearray() - while True: - if self._pos >= len(self._buf) and not self._ensure(1): - break - match = _JSON_TOKEN_STOP.search(self._buf, self._pos) - end = len(self._buf) if match is None else match.start() - seg = self._buf[self._pos:end] - if len(raw) + len(seg) > _MAX_PRIMITIVE_BYTES: - raise ValueError("oversized JSON primitive") - raw.extend(seg) - self._pos = end - if match is not None: - break - if not raw: - raise ValueError("expected JSON value") - return json.loads(bytes(raw), parse_constant=_reject_json_constant) - - def skip_primitive(self) -> None: - """Validate and skip a JSON literal or number in O(1) memory.""" - ch = self._peek_byte() - if ch is None: - raise ValueError("expected JSON value") - if ch in {0x74, 0x66, 0x6e}: - literal = b"true" if ch == 0x74 else b"false" if ch == 0x66 else b"null" - if not self._ensure(len(literal)) or self._buf[self._pos:self._pos + len(literal)] != literal: - raise ValueError("invalid JSON literal") - self._pos += len(literal) - else: - if ch == 0x2d: - self._pos += 1 - ch = self._peek_byte() - if ch is None: - raise ValueError("invalid JSON number") - if ch == 0x30: - self._pos += 1 - elif 0x31 <= ch <= 0x39: - self._pos += 1 - self._consume_digits() - else: - raise ValueError("invalid JSON number") - if self._peek_byte() == 0x2e: - self._pos += 1 - if not self._consume_digits(): - raise ValueError("invalid JSON number") - if self._peek_byte() in {0x65, 0x45}: - self._pos += 1 - if self._peek_byte() in {0x2b, 0x2d}: - self._pos += 1 - if not self._consume_digits(): - raise ValueError("invalid JSON number") - nxt = self._peek_byte() - if nxt is not None and nxt not in _JSON_PRIMITIVE_STOP: - raise ValueError("invalid JSON primitive") - - def skip_value(self) -> None: - stack: list[bool] = [] # True = object, False = array - state = 0 # 0=val, 1=val|arr_end, 2=arr_sep, 3=key|obj_end, 4=key, 5=colon, 6=obj_sep - while True: - ch = self.skip_ws() - if ch is None: - raise ValueError("unexpected EOF in JSON value") - if state in {3, 6}: - if ch == 0x7d: - self._pos += 1 - stack.pop() - if not stack: - return - state = 6 if stack[-1] else 2 - continue - if state == 6: - if ch != 0x2c: - raise ValueError("expected comma or end of JSON object") - self._pos += 1 - state = 4 - continue - state = 4 - if state == 4: - self.scan_string() - state = 5 - continue - if state == 5: - if ch != 0x3a: - raise ValueError("expected colon in JSON object") - self._pos += 1 - state = 0 - continue - if state == 2: - if ch == 0x5d: - self._pos += 1 - stack.pop() - if not stack: - return - state = 6 if stack[-1] else 2 - continue - if ch != 0x2c: - raise ValueError("expected comma or end of JSON array") - self._pos += 1 - state = 0 - continue - if state == 1 and ch == 0x5d: - self._pos += 1 - stack.pop() - if not stack: - return - state = 6 if stack[-1] else 2 - continue - if ch == 0x7b: - if len(stack) >= _MAX_SKIP_DEPTH: - raise RecursionError("JSON nesting too deep") - self._pos += 1 - stack.append(True) - state = 3 - elif ch == 0x5b: - if len(stack) >= _MAX_SKIP_DEPTH: - raise RecursionError("JSON nesting too deep") - self._pos += 1 - stack.append(False) - state = 1 - elif ch == 0x22: - self.scan_string() - if not stack: - return - state = 6 if stack[-1] else 2 - else: - self.skip_primitive() - if not stack: - return - state = 6 if stack[-1] else 2 - - def read_small_value(self) -> Any: - ch = self.skip_ws() - if ch is None: - raise ValueError("unexpected EOF in JSON value") - if ch == 0x22: - return self.scan_string(capture_limit=_MAX_HEADER_FIELD_BYTES) - if ch == 0x7b: - self.skip_value() - return {} - if ch == 0x5b: - self.skip_value() - return [] - return self.read_primitive() - - -def _scan_selected_object(cursor: _JsonSliceCursor, spec: Mapping[str, Any]) -> dict[str, Any]: - cursor.consume_byte(0x7b) - result: dict[str, Any] = {} - ch = cursor.skip_ws() - if ch == 0x7d: - cursor._pos += 1 - return result - while True: - if ch != 0x22: - raise ValueError("expected JSON object key") - key = cursor.scan_string(capture_limit=128, allow_long_key=True) - if cursor.skip_ws() != 0x3a: - raise ValueError("expected colon in JSON object") - cursor._pos += 1 - if key not in spec: - cursor.skip_value() - elif isinstance(spec[key], dict): - if cursor.skip_ws() == 0x7b: - result[key] = _scan_selected_object(cursor, spec[key]) - else: - result[key] = cursor.read_small_value() - else: - result[key] = cursor.read_small_value() - ch = cursor.skip_ws() - if ch == 0x7d: - cursor._pos += 1 - return result - if ch != 0x2c: - raise ValueError("expected comma or end of JSON object") - cursor._pos += 1 - ch = cursor.skip_ws() - - -def _scan_turn_prefix_record(stream: BinaryIO, start: int, stop: int) -> dict[str, Any]: - """Decode only Turn/parent metadata from a large earlier record in O(chunk) memory.""" - cursor = _JsonSliceCursor(stream, start, stop) - if cursor.skip_ws() != 0x7b: - raise ValueError("native replay record must be a JSON object") - record = _scan_selected_object(cursor, _PREFIX_RECORD_SPEC) - if cursor.skip_ws() is not None: - raise ValueError("trailing data in native replay record") - return record - - -def _turn_boundary(record: dict[str, Any]) -> bool: - return record.get("type") == "event_msg" and record.get("payload", {}).get("type") == "task_started" - - -def _native_reader(stream: BinaryIO, end: int, event: dict[str, Any]) -> tuple[int, str] | None: - """Bind a hook to its own call, or to a single open native Code Mode call.""" - reader = event["tool_use_id"] - completed = False - closed_parents: set[str] = set() - parent: tuple[int, str] | None = None - for offset, stop in _reader_spans(stream, end): - raw_len = stop - offset - 1 - if raw_len > _MAX_RECORD_BYTES: - if parent is None: - raise ValueError("unsupported native reader record") - record = _scan_turn_prefix_record(stream, offset, stop - 1) - else: - stream.seek(offset) - record = json.loads(stream.read(stop - offset)) - if _turn_boundary(record): - break - payload = record["payload"] - kind = payload.get("type") - if record.get("type") == "event_msg" and kind == "item_completed": - item = payload.get("item", {}) - if item.get("type") == "CommandExecution" and item.get("id") == reader: - if item.get("exit_code") != 0 or payload.get("turn_id") != event.get("turn_id"): - return None - completed = True - if record.get("type") != "response_item": - continue - call = payload.get("call_id") - if not isinstance(call, str) or not call: - continue - if call == reader and kind in {"function_call", "function_call_output"}: - if raw_len > _MAX_RECORD_BYTES: - return None - return offset, _digest(record) - if kind == "custom_tool_call_output": - closed_parents.add(call) - if kind != "custom_tool_call" or payload.get("name") != "exec" or call in closed_parents: - continue - if not completed or parent is not None or not isinstance(event.get("turn_id"), str): - return None - # A qualified native record can omit message metadata. The completed - # command still carries the Turn, and the parent is uniquely open. - metadata = payload.get("internal_chat_message_metadata_passthrough") or {} - if metadata.get("turn_id") not in (None, event["turn_id"]): - return None - parent = offset, _digest(record) - return parent - - -def _read_pages(output: object) -> list[dict[str, Any]]: - from .codex_context import _context_pages - - # This is the native exec_command result envelope, not a prose classifier. - if isinstance(output, str) and (match := _SHELL_OUTPUT.fullmatch(output)): - output = match[1] - if isinstance(output, list): - return [page for item in output if isinstance(item, dict) and item.get("type") == "input_text" - for page in _read_pages(item.get("text"))] - return _context_pages(output) - - -def _covers_bytes(ranges: list[tuple[int, int]], total: int) -> bool: - cursor = 0 - for start, stop in sorted(ranges): - if start > cursor: - return False - cursor = max(cursor, stop) - return cursor == total - - -def _same_replay_source(anchor: dict[str, Any], snapshot: dict[str, Any]) -> bool: - return all(anchor.get(k) == snapshot.get(k) for k in _SOURCE_IDENTITY_FIELDS) - - -def _matching_replay_interval(anchor: dict[str, Any], snapshot: dict[str, Any], stream: BinaryIO) -> bool: - start, end = anchor.get("reader_start"), anchor.get("observed_bytes") - return (_same_replay_source(anchor, snapshot) and type(start) is int and type(end) is int - and 0 < start <= end <= snapshot["observed_bytes"] - and _region_digest(stream, start, end) == anchor.get("reader_sha256")) - - -def _read_receipt(offset: int, digest: str, pages: list[dict[str, Any]]) -> dict[str, Any]: - return {"native_offset": offset, "native_sha256": digest, "pages_sha256": _digest(pages)} - - -def _matching_resume_session(state: dict[str, Any], event: dict[str, Any], anchor: object) -> bool: - return (event.get("source") == "resume" and isinstance(anchor, dict) - and state.get("session_id") == event.get("session_id") - and state.get("cwd") == event.get("cwd")) - - -def _verified_replay_capture(anchor: dict[str, Any], snapshot: dict[str, Any], stream: BinaryIO) -> tuple[Path, bytes, dict[str, Any]] | None: - from .decision_capture import read_context_capture_file - - reference = anchor.get("read_source") - if not isinstance(reference, dict) or not _matching_replay_interval(anchor, snapshot, stream): - return None - return read_context_capture_file(reference["path"], reference["sha256"], private=True) - - -def _emission_pages(payload: dict[str, Any]) -> Iterator[list[dict[str, Any]]]: - output = payload.get("output") - if payload["type"] == "custom_tool_call_output" and isinstance(output, list): - for item in output: - if isinstance(item, dict) and item.get("type") == "input_text": - yield _read_pages(item.get("text")) - else: - yield _read_pages(output) - - -def _replayed_output_groups(anchor: dict[str, Any], snapshot: dict[str, Any], stream: BinaryIO, - event: dict[str, Any], reads: list[dict[str, Any]], - ) -> Iterator[tuple[int, str, list[dict[str, Any]]]]: - # Old private checkpoints did not bind full reads to a call. They may - # still serve their saved file, but cannot attest cross-process retention. - call_offsets: dict[int, str] = {} - for read in reads: - offset, digest = read["native_offset"], read["native_sha256"] - if call_offsets.setdefault(offset, digest) != digest: - raise ValueError("native replay call changed between observations") - native_calls: dict[str, tuple[int, str]] = {} - closed_calls: set[str] = set() - for offset, record in _records(stream, anchor["reader_start"], snapshot["observed_bytes"]): - if not _append_only(record, event): - raise ValueError("unsupported native replay continuation") - payload = record["payload"] - if _turn_boundary(record): - native_calls.clear() - closed_calls.clear() - if record["type"] != "response_item": - continue - kind, call = payload.get("type"), payload.get("call_id") - if kind in {"function_call", "custom_tool_call"}: - # Call IDs can repeat in later Turns. Match the exact call - # occurrence observed by the hook. - native_calls.pop(call, None) - closed_calls.discard(call) - if offset in call_offsets and call_offsets[offset] == _digest(record): - native_calls[call] = offset, kind - elif kind in {"function_call_output", "custom_tool_call_output"}: - opened = native_calls.pop(call, None) - if opened is None: - if call in closed_calls: - raise ValueError("duplicate native tool output without a new call") - if (kind != "function_call_output" or offset not in call_offsets - or call_offsets[offset] != _digest(record)): - continue - call_offset = offset # the direct output was already present at hook time - else: - call_offset, call_kind = opened - if kind != call_kind + "_output" or call_offset not in call_offsets: - continue - closed_calls.add(call) - for group in _emission_pages(payload): - if group: - yield call_offset, _digest(group), group - - -def _matches(anchor: dict[str, Any], snapshot: dict[str, Any], stream: BinaryIO, - event: dict[str, Any]) -> bool: - from .decision_capture import capture_page_range - - reads, rereads = anchor.get("reads"), anchor.get("rereads", []) - if not isinstance(reads, list) or not reads or not isinstance(rereads, list): - return False - verified = _verified_replay_capture(anchor, snapshot, stream) - if verified is None: - return False - _, body, _ = verified - reference_sha = anchor["read_source"]["sha256"] - all_reads = [*reads, *rereads] - required = {(read["native_offset"], read["pages_sha256"]) for read in all_reads} - ranges = [] - for offset, digest, group in _replayed_output_groups(anchor, snapshot, stream, event, all_reads): - if (offset, digest) not in required: - continue - for page in group: - span = capture_page_range(page, raw=body, digest=reference_sha) - if span is None: - return False - ranges.append(span) - # An independently observed reread can recover a missing range. A copy - # emitted by an unrelated call cannot contribute even identical bytes. - return _covers_bytes(ranges, len(body)) - - -def _replayed_selection_sections(anchor: dict[str, Any], snapshot: dict[str, Any], stream: BinaryIO, - event: dict[str, Any]) -> dict[str, str]: - selections = anchor.get("selections") - if not isinstance(selections, dict) or not selections or _verified_replay_capture(anchor, snapshot, stream) is None: - return {} - reads = [read for selection in selections.values() for read in selection["reads"]] - outputs = {(offset, digest) for offset, digest, _ in _replayed_output_groups(anchor, snapshot, stream, event, reads)} - retained = {} - for selection in selections.values(): - ranges = [(read["start"], read["end"]) for read in selection["reads"] - if (read["native_offset"], read["pages_sha256"]) in outputs] - if _covers_bytes(ranges, selection["total_bytes"]): - retained.update(selection["sections"]) - return retained - - -def _append_only(record: dict[str, Any], event: dict[str, Any]) -> bool: - kind, payload = record.get("type"), record.get("payload", {}) - if kind == "event_msg": - if payload.get("type") not in _APPEND_EVENTS: - return False - if payload.get("type") == "thread_settings_applied" and payload.get("history_mode") not in (None, "paginated"): - return False - elif kind not in _APPEND_RECORDS: - return False - return kind != "turn_context" or ( - payload.get("cwd") == event["cwd"] and payload.get("model") == event["model"]) - - -def observe_native_read(state: dict[str, Any], event: dict[str, Any], - pages: list[dict[str, Any]]) -> dict[str, Any]: +def observe_native_read( + state: Mapping[str, object], + event: Mapping[str, object], + pages: Sequence[Mapping[str, object]], +) -> dict[str, object]: """Collect content-free IO facts alongside the existing pending byte ranges.""" pending = state.get("pending") call = event.get("tool_use_id") - if (not isinstance(call, str) or not call - or not pages or any(page.get("ok") is not True for page in pages)): - return state + if ( + not isinstance(call, str) + or not call + or not pages + or any(page.get("ok") is not True for page in pages) + ): + return dict(state) if pending is None: - recovery, candidate = state.get("recovery"), state.get("candidate") or {} - if (not isinstance(recovery, dict) or not isinstance(candidate, dict) - or any(page.get("sha256") != recovery.get("sha256") for page in pages) - or (candidate.get("capture_sha256") == recovery.get("sha256") - and candidate.get("capture_bytes_verified") is True)): - return state + recovery = state.get("recovery") + candidate = state.get("candidate") or {} + if ( + not isinstance(recovery, dict) + or not isinstance(candidate, dict) + or any(page.get("sha256") != recovery.get("sha256") for page in pages) + or ( + candidate.get("capture_sha256") == recovery.get("sha256") + and candidate.get("capture_bytes_verified") is True + ) + ): + return dict(state) # Invalidation clears pending reads. Record the first original-capture # recovery read too, including a full capture delivered in one page. # These are IO annotations only: the typed lifecycle still authenticates # coverage and decides whether a complete baseline can be established. pending = {} if not isinstance(pending, dict): - return state + return dict(state) try: with _snapshot(event) as (facts, stream): - native_reader = _native_reader(stream, facts["observed_bytes"], event) + observed_bytes = facts["observed_bytes"] + if not isinstance(observed_bytes, int): + raise TypeError("observed_bytes must be an int") + native_reader = _native_reader(stream, observed_bytes, event) except _REPLAY_ERRORS: - return state + return dict(state) if native_reader is None: - return state + return dict(state) offset, digest = native_reader read = _read_receipt(offset, digest, pages) start, reads = pending.get("native_reader_start"), pending.get("native_reads") - if not isinstance(start, dict) or not isinstance(reads, list) or not _same_replay_source(start, facts): + if ( + not isinstance(start, dict) + or not isinstance(reads, list) + or not _same_replay_source(start, facts) + ): start, reads = {**facts, "reader_start": offset}, [] - elif offset < start["reader_start"]: + elif isinstance(start.get("reader_start"), int) and offset < start["reader_start"]: start = {**facts, "reader_start": offset} if read not in reads: reads = [*reads, read] - pending = {**pending, "native_reads": reads, "native_reader_start": start} - return {**state, "pending": pending} + next_pending = {**pending, "native_reads": reads, "native_reader_start": start} + return {**state, "pending": next_pending} -def observe_completed_native_reread(state: dict[str, Any], updated: dict[str, Any], - event: dict[str, Any], pages: list[dict[str, Any]]) -> None: +def observe_completed_native_reread( + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], + pages: Sequence[Mapping[str, object]], +) -> None: """Add independently observed output to the current full-capture checkpoint.""" candidate = updated.get("candidate") if not isinstance(candidate, dict) or candidate != state.get("candidate") or not pages: return anchor, reference = candidate.get("native_resume"), state.get("recovery") - if (not isinstance(anchor, dict) or not isinstance(reference, dict) - or anchor.get("read_source", {}).get("sha256") != reference.get("sha256") - or any(page.get("ok") is not True or page.get("sha256") != reference.get("sha256") for page in pages)): + if not isinstance(anchor, dict) or not isinstance(reference, dict): + return + anchor_read_source = anchor.get("read_source") + if ( + not isinstance(anchor_read_source, Mapping) + or anchor_read_source.get("sha256") != reference.get("sha256") + or any( + page.get("ok") is not True or page.get("sha256") != reference.get("sha256") + for page in pages + ) + ): return try: with _snapshot(event) as (facts, stream): # Resume checks the original interval digest. Extra observations # cannot change it and do not need to hash it again at each hook. - if not _same_replay_source(anchor, facts) or anchor["observed_bytes"] > facts["observed_bytes"]: + anchor_bytes = anchor["observed_bytes"] + facts_bytes = facts["observed_bytes"] + anchor_start = anchor["reader_start"] + if ( + not _same_replay_source(anchor, facts) + or not isinstance(anchor_bytes, int) + or not isinstance(facts_bytes, int) + or not isinstance(anchor_start, int) + or anchor_bytes > facts_bytes + ): return - native_reader = _native_reader(stream, facts["observed_bytes"], event) - if native_reader is None or native_reader[0] < anchor["reader_start"]: + native_reader = _native_reader(stream, facts_bytes, event) + if native_reader is None or native_reader[0] < anchor_start: return read = _read_receipt(*native_reader, pages) rereads = anchor.get("rereads", []) - if read not in anchor["reads"] and read not in rereads: - candidate["native_resume"] = {**anchor, "rereads": [*rereads, read][-_MAX_COMPLETE_REREADS:]} + existing_reads = anchor["reads"] + if ( + isinstance(existing_reads, list) + and isinstance(rereads, list) + and read not in existing_reads + and read not in rereads + ): + candidate["native_resume"] = { + **anchor, + "rereads": [*rereads, read][-_MAX_COMPLETE_REREADS:], + } except _REPLAY_ERRORS: return -def native_resume_verified(state: dict[str, Any], event: dict[str, Any]) -> bool: +def native_resume_verified( + state: Mapping[str, object], event: Mapping[str, object] +) -> bool: """Observe a qualified replay source; the shared TS owner decides reuse.""" candidate = state.get("candidate") or {} if not isinstance(candidate, dict): return False anchor = candidate.get("native_resume") - if not _matching_resume_session(state, event, anchor) or state.get("pending") or not isinstance(anchor, dict): + if ( + not _matching_resume_session(state, event, anchor) + or state.get("pending") + or not isinstance(anchor, dict) + ): return False try: with _snapshot(event) as (facts, stream): @@ -746,13 +274,18 @@ def native_resume_verified(state: dict[str, Any], event: dict[str, Any]) -> bool return False -def native_resume_sections(state: dict[str, Any], event: dict[str, Any]) -> dict[str, str]: +def native_resume_sections( + state: Mapping[str, object], event: Mapping[str, object] +) -> dict[str, str]: """Verify replay of exact selected outputs without claiming a whole capture read.""" anchor = state.get("selected_resume") - if (not _matching_resume_session(state, event, anchor) or not isinstance(anchor, dict) - or anchor.get("scope") != state.get("read_scope") - or anchor.get("epoch") != state.get("context_epoch") - or anchor.get("read_source") != state.get("source_recovery")): + if ( + not _matching_resume_session(state, event, anchor) + or not isinstance(anchor, dict) + or anchor.get("scope") != state.get("read_scope") + or anchor.get("epoch") != state.get("context_epoch") + or anchor.get("read_source") != state.get("source_recovery") + ): return {} try: with _snapshot(event) as (facts, stream): @@ -762,103 +295,223 @@ def native_resume_sections(state: dict[str, Any], event: dict[str, Any]) -> dict return {} -def checkpoint_native_selection(state: dict[str, Any], updated: dict[str, Any], - event: dict[str, Any], raw_pages: list[dict[str, Any]], - verified_pages: list[dict[str, Any]]) -> None: +def _same_selected_source( + previous: object, + *, + scope: object, + epoch: object, + source: object, + event: Mapping[str, object], +) -> bool: + return ( + isinstance(previous, dict) + and previous.get("scope") == scope + and previous.get("epoch") == epoch + and previous.get("read_source") == source + and previous.get("path") == event.get("transcript_path") + and all(previous.get(k) == event.get(k) for k in ("model", "permission_mode")) + ) + + +def checkpoint_native_selection( + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], + raw_pages: Sequence[Mapping[str, object]], + verified_pages: Sequence[Mapping[str, object]], +) -> None: """Record bounded, self-contained selections after literal byte verification.""" if len(raw_pages) != 1 or len(verified_pages) != 1: return raw, page = raw_pages[0], verified_pages[0] sections, source = page.get("read_sections"), state.get("source_recovery") - scope, epoch, call = state.get("read_scope"), state.get("context_epoch"), event.get("tool_use_id") + scope, epoch, call = ( + state.get("read_scope"), + state.get("context_epoch"), + event.get("tool_use_id"), + ) consumed = updated.get("consumed_pointers", {}) - if (not (raw.get("schema_version") == "context_capture_selection_page_v1" - or "selected_pointers" in raw and "selection_sha256" in raw) - or page.get("ok") is not True or page.get("read_sections_inherited") - or not isinstance(sections, dict) - or not isinstance(source, dict) or page.get("source_sha256") != source.get("sha256") - or not isinstance(scope, dict) or not epoch or scope.get("context_epoch") != epoch - or not isinstance(call, str) or not call or not isinstance(consumed, dict)): + if ( + not ( + raw.get("schema_version") == "context_capture_selection_page_v1" + or ("selected_pointers" in raw and "selection_sha256" in raw) + ) + or page.get("ok") is not True + or page.get("read_sections_inherited") + or not isinstance(sections, dict) + or not isinstance(source, dict) + or page.get("source_sha256") != source.get("sha256") + or not isinstance(scope, dict) + or not epoch + or scope.get("context_epoch") != epoch + or not isinstance(call, str) + or not call + or not isinstance(consumed, dict) + ): return previous = state.get("selected_resume") - same_source = (isinstance(previous, dict) and previous.get("scope") == scope - and previous.get("epoch") == epoch and previous.get("read_source") == source - and previous.get("path") == event.get("transcript_path") - and all(previous.get(k) == event.get(k) for k in ("model", "permission_mode"))) + same_source = _same_selected_source( + previous, scope=scope, epoch=epoch, source=source, event=event + ) try: with _snapshot(event) as (facts, stream): - native_reader = _native_reader(stream, facts["observed_bytes"], event) + end = facts["observed_bytes"] + if not isinstance(end, int): + raise TypeError("observed_bytes must be an int") + native_reader = _native_reader(stream, end, event) if native_reader is None: return native_offset, native_sha256 = native_reader - anchor = previous if isinstance(previous, dict) and same_source and _same_replay_source(previous, facts) else {} - selections = dict(anchor.get("selections", {})) - all_reads = [read for entry in selections.values() for read in entry["reads"]] - if any(read["call_id"] == call and read["native_offset"] == native_offset for read in all_reads): + anchor: dict[str, object] = ( + dict(previous) + if isinstance(previous, dict) + and same_source + and _same_replay_source(previous, facts) + else {} + ) + raw_selections = anchor.get("selections", {}) + selections: dict[str, dict[str, object]] = ( + dict(raw_selections) if isinstance(raw_selections, dict) else {} + ) + all_reads = [ + read + for entry in selections.values() + if isinstance(entry, Mapping) + for read in cast(Sequence[Mapping[str, object]], entry["reads"]) + ] + if any( + read["call_id"] == call and read["native_offset"] == native_offset + for read in all_reads + ): return if not selections or len(all_reads) >= _MAX_SELECTED_REPLAY_READS: - end = facts["observed_bytes"] - anchor = {**facts, "reader_start": native_offset, + anchor = { + **facts, + "reader_start": native_offset, "reader_sha256": _region_digest(stream, native_offset, end), - "read_source": source, "scope": scope, "epoch": epoch} + "read_source": source, + "scope": scope, + "epoch": epoch, + } selections = {} - if native_offset < anchor["reader_start"]: + anchor_start = anchor["reader_start"] + if not isinstance(anchor_start, int) or native_offset < anchor_start: return # Offsets belong to the exact selected view, which can coincide across # different sources or presentation bindings. Only combine pages from # the same physical reader and its verified view. selection = _digest([raw.get("reference_file") or raw["sha256"], page["sha256"]]) offset = page["offset"] - end = offset + len(page["content"].encode("utf-8")) - receipt = {"call_id": call, **_read_receipt(native_offset, native_sha256, raw_pages), - "start": offset, "end": end} + content = page["content"] + total_bytes = page["total_bytes"] + if ( + not isinstance(offset, int) + or not isinstance(content, str) + or not isinstance(total_bytes, int) + ): + raise TypeError("verified selection page missing integer bounds") + end_offset = offset + len(content.encode("utf-8")) + receipt: dict[str, object] = { + "call_id": call, + **_read_receipt(native_offset, native_sha256, raw_pages), + "start": offset, + "end": end_offset, + } entry = selections.get(selection, {}) - observed = entry.get("sections", {}) - progress = [*entry.get("reads", []), receipt] - if _covers_bytes([(read["start"], read["end"]) for read in progress], page["total_bytes"]): + observed = entry.get("sections", {}) if isinstance(entry, Mapping) else {} + prev_reads = entry.get("reads", []) if isinstance(entry, Mapping) else [] + progress = [ + *cast(Sequence[Mapping[str, object]], prev_reads), + receipt, + ] + if _covers_bytes( + [(int(str(r["start"])), int(str(r["end"]))) for r in progress], total_bytes + ): # The reducer and this replay interval both observed full coverage. # Never resume an inherited selection from only its displayed pages. - if sections and all(consumed.get(pointer) == digest for pointer, digest in sections.items()): + if sections and all( + consumed.get(pointer) == digest for pointer, digest in sections.items() + ): observed = sections - selections[selection] = {"reads": progress, "sections": observed, "total_bytes": page["total_bytes"]} + selections[selection] = { + "reads": progress, + "sections": observed, + "total_bytes": total_bytes, + } updated["selected_resume"] = {**anchor, "selections": selections} except _REPLAY_ERRORS: return -def checkpoint_native_read(state: dict[str, Any], updated: dict[str, Any], - event: dict[str, Any], pages: list[dict[str, Any]]) -> None: +def checkpoint_native_read( + state: Mapping[str, object], + updated: dict[str, object], + event: Mapping[str, object], + pages: Sequence[Mapping[str, object]], +) -> None: """Attach content-free native source facts only after the typed complete read. A delta checkpoint can advance only a previously verified replay chain. Failure affects cross-process reuse, not normal in-process reader delivery. """ candidate = updated.get("candidate") - if (not isinstance(candidate, dict) or updated.get("pending") or not pages - or candidate == state.get("candidate") or not event.get("tool_use_id")): + if ( + not isinstance(candidate, dict) + or updated.get("pending") + or not pages + or candidate == state.get("candidate") + or not event.get("tool_use_id") + ): return try: pending = state.get("pending") or {} + if not isinstance(pending, Mapping): + return reference = pending if candidate.get("ancestry", 0) else state.get("recovery") reads = pending.get("native_reads") start = pending.get("native_reader_start") - if not isinstance(reference, dict) or not isinstance(reads, list) or not reads or not isinstance(start, dict): + if ( + not isinstance(reference, dict) + or not isinstance(reads, list) + or not reads + or not isinstance(start, dict) + ): return with _snapshot(event) as (facts, stream): - if any(start.get(k) != facts.get(k) for k in ("path", "device", "inode", "metadata_sha256")): + if any( + start.get(k) != facts.get(k) + for k in ("path", "device", "inode", "metadata_sha256") + ): return reader_start = start["reader_start"] + observed_bytes = facts["observed_bytes"] + if not isinstance(reader_start, int) or not isinstance(observed_bytes, int): + return if candidate.get("ancestry", 0): - anchor = (state.get("candidate") or {}).get("native_resume") - if not isinstance(anchor, dict) or not _matches(anchor, facts, stream, event): + state_candidate = state.get("candidate") or {} + anchor = ( + state_candidate.get("native_resume") + if isinstance(state_candidate, Mapping) + else None + ) + if not isinstance(anchor, dict) or not _matches( + anchor, facts, stream, event + ): return # A delta still depends on its earlier complete baseline. - reader_start = min(reader_start, anchor["reader_start"]) - if not 0 < reader_start <= facts["observed_bytes"]: + anchor_start = anchor["reader_start"] + if not isinstance(anchor_start, int): + return + reader_start = min(reader_start, anchor_start) + if not 0 < reader_start <= observed_bytes: return - checkpoint = {**facts, "reader_start": reader_start, - "reader_sha256": _region_digest(stream, reader_start, facts["observed_bytes"]), - "reads": reads, "read_source": {key: reference[key] for key in ("path", "sha256")}} + checkpoint: dict[str, object] = { + **facts, + "reader_start": reader_start, + "reader_sha256": _region_digest(stream, reader_start, observed_bytes), + "reads": reads, + "read_source": {key: reference[key] for key in ("path", "sha256")}, + } candidate["native_resume"] = checkpoint except _REPLAY_ERRORS: return diff --git a/loopx/control_plane/turn_driver/codex_context_history_json.py b/loopx/control_plane/turn_driver/codex_context_history_json.py new file mode 100644 index 0000000000..914c55707a --- /dev/null +++ b/loopx/control_plane/turn_driver/codex_context_history_json.py @@ -0,0 +1,340 @@ +"""Bounded JSON slice validation and digest helpers for Codex native replay.""" +from __future__ import annotations + +import codecs +from collections.abc import Mapping +import hashlib +import json +import re +from typing import BinaryIO, NoReturn, cast + +_IO_CHUNK_BYTES = 64 * 1024 +# Bound one decoded protocol record, not the history or the replay interval. +_MAX_RECORD_BYTES = 16 * 1024 * 1024 +_MAX_HEADER_FIELD_BYTES = 16 * 1024 +_MAX_PRIMITIVE_BYTES = 1024 +_MAX_SKIP_DEPTH = 256 + +_JSON_WS_STOP = re.compile(rb"[^ \t\r\n]") +_JSON_STR_SPAN = re.compile( + rb'(?:[^"\\\x00-\x1f]+|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})){1,64}' +) +_JSON_DIGITS = re.compile(rb"[0-9]+") +_JSON_PRIMITIVE_STOP = frozenset(b" \t\r\n,}]") +_JSON_TOKEN_STOP = re.compile(rb"[ \t\r\n,\}\]]") + +_PREFIX_PAYLOAD_SPEC: dict[str, object] = { + "type": None, + "call_id": None, + "name": None, + "turn_id": None, + "item": {"type": None, "id": None, "exit_code": None}, + "internal_chat_message_metadata_passthrough": {"turn_id": None}, +} +_PREFIX_RECORD_SPEC: dict[str, object] = {"type": None, "payload": _PREFIX_PAYLOAD_SPEC} + +JsonScalar = str | int | float | bool | None +JsonSmallValue = JsonScalar | dict[object, object] | list[object] + + +def _digest(value: object) -> str: + return hashlib.sha256( + json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":") + ).encode() + ).hexdigest() + + +def _reject_json_constant(token: str) -> NoReturn: + raise ValueError(f"unsupported JSON constant: {token}") + + +class _JsonSliceCursor: + """Chunked JSON validator and header extractor for oversized Turn-prefix records.""" + + def __init__(self, stream: BinaryIO, start: int, stop: int) -> None: + stream.seek(start) + self._stream = stream + self._cursor = start + self._stop = stop + self._buf = b"" + self._pos = 0 + + def _ensure(self, n: int = 1) -> bool: + while len(self._buf) - self._pos < n and self._cursor < self._stop: + chunk = self._stream.read(min(_IO_CHUNK_BYTES, self._stop - self._cursor)) + if not chunk: + raise ValueError("native reader interval was truncated") + self._cursor += len(chunk) + self._buf = self._buf[self._pos :] + chunk + self._pos = 0 + return len(self._buf) - self._pos >= n + + def _peek_byte(self) -> int | None: + if self._pos >= len(self._buf) and not self._ensure(1): + return None + return self._buf[self._pos] + + def _consume_digits(self) -> bool: + matched = False + while True: + if self._pos >= len(self._buf) and not self._ensure(1): + return matched + match = _JSON_DIGITS.match(self._buf, self._pos) + if match is None: + return matched + matched = True + self._pos = match.end() + + def skip_ws(self) -> int | None: + while True: + if self._pos >= len(self._buf) and not self._ensure(1): + return None + match = _JSON_WS_STOP.search(self._buf, self._pos) + if match is not None: + self._pos = match.start() + return self._buf[self._pos] + self._pos = len(self._buf) + + def consume_byte(self, expected: int) -> None: + if not self._ensure(1) or self._buf[self._pos] != expected: + raise ValueError("malformed native JSON record") + self._pos += 1 + + def scan_string( + self, *, capture_limit: int | None = None, allow_long_key: bool = False + ) -> str: + self.consume_byte(0x22) + decoder = codecs.getincrementaldecoder("utf-8")("strict") + raw: bytearray | None = bytearray(b'"') if capture_limit is not None else None + + def _append_raw(data: bytes) -> bytearray | None: + if raw is None or capture_limit is None: + return None + if len(raw) + len(data) > capture_limit: + if not allow_long_key: + raise ValueError("oversized JSON header field") + return None + raw.extend(data) + return raw + + while True: + if self._pos >= len(self._buf) and not self._ensure(1): + raise ValueError("unterminated JSON string") + match = _JSON_STR_SPAN.match(self._buf, self._pos) + if match is not None: + seg = self._buf[self._pos : match.end()] + decoder.decode(seg, final=False) + raw = _append_raw(seg) + self._pos = match.end() + continue + ch = self._buf[self._pos] + if ch == 0x22: + decoder.decode(b"", final=True) + self._pos += 1 + raw = _append_raw(b'"') + return "" if raw is None else str(json.loads(bytes(raw))) + if ch == 0x5C and len(self._buf) - self._pos < 6 and self._cursor < self._stop: + before = len(self._buf) - self._pos + self._ensure(6) + if len(self._buf) - self._pos > before: + continue + raise ValueError("invalid JSON string") + + def read_primitive(self) -> JsonScalar: + raw = bytearray() + while True: + if self._pos >= len(self._buf) and not self._ensure(1): + break + match = _JSON_TOKEN_STOP.search(self._buf, self._pos) + end = len(self._buf) if match is None else match.start() + seg = self._buf[self._pos : end] + if len(raw) + len(seg) > _MAX_PRIMITIVE_BYTES: + raise ValueError("oversized JSON primitive") + raw.extend(seg) + self._pos = end + if match is not None: + break + if not raw: + raise ValueError("expected JSON value") + return cast( + JsonScalar, + json.loads(bytes(raw), parse_constant=_reject_json_constant), + ) + + def skip_primitive(self) -> None: + """Validate and skip a JSON literal or number in O(1) memory.""" + ch = self._peek_byte() + if ch is None: + raise ValueError("expected JSON value") + if ch in {0x74, 0x66, 0x6E}: + literal = b"true" if ch == 0x74 else b"false" if ch == 0x66 else b"null" + if ( + not self._ensure(len(literal)) + or self._buf[self._pos : self._pos + len(literal)] != literal + ): + raise ValueError("invalid JSON literal") + self._pos += len(literal) + else: + if ch == 0x2D: + self._pos += 1 + ch = self._peek_byte() + if ch is None: + raise ValueError("invalid JSON number") + if ch == 0x30: + self._pos += 1 + elif 0x31 <= ch <= 0x39: + self._pos += 1 + self._consume_digits() + else: + raise ValueError("invalid JSON number") + if self._peek_byte() == 0x2E: + self._pos += 1 + if not self._consume_digits(): + raise ValueError("invalid JSON number") + if self._peek_byte() in {0x65, 0x45}: + self._pos += 1 + if self._peek_byte() in {0x2B, 0x2D}: + self._pos += 1 + if not self._consume_digits(): + raise ValueError("invalid JSON number") + nxt = self._peek_byte() + if nxt is not None and nxt not in _JSON_PRIMITIVE_STOP: + raise ValueError("invalid JSON primitive") + + def skip_value(self) -> None: + stack: list[bool] = [] # True = object, False = array + state = 0 # 0=val, 1=val|arr_end, 2=arr_sep, 3=key|obj_end, 4=key, 5=colon, 6=obj_sep + while True: + ch = self.skip_ws() + if ch is None: + raise ValueError("unexpected EOF in JSON value") + if state in {3, 6}: + if ch == 0x7D: + self._pos += 1 + stack.pop() + if not stack: + return + state = 6 if stack[-1] else 2 + continue + if state == 6: + if ch != 0x2C: + raise ValueError("expected comma or end of JSON object") + self._pos += 1 + state = 4 + continue + state = 4 + if state == 4: + self.scan_string() + state = 5 + continue + if state == 5: + if ch != 0x3A: + raise ValueError("expected colon in JSON object") + self._pos += 1 + state = 0 + continue + if state == 2: + if ch == 0x5D: + self._pos += 1 + stack.pop() + if not stack: + return + state = 6 if stack[-1] else 2 + continue + if ch != 0x2C: + raise ValueError("expected comma or end of JSON array") + self._pos += 1 + state = 0 + continue + if state == 1 and ch == 0x5D: + self._pos += 1 + stack.pop() + if not stack: + return + state = 6 if stack[-1] else 2 + continue + if ch == 0x7B: + if len(stack) >= _MAX_SKIP_DEPTH: + raise RecursionError("JSON nesting too deep") + self._pos += 1 + stack.append(True) + state = 3 + elif ch == 0x5B: + if len(stack) >= _MAX_SKIP_DEPTH: + raise RecursionError("JSON nesting too deep") + self._pos += 1 + stack.append(False) + state = 1 + elif ch == 0x22: + self.scan_string() + if not stack: + return + state = 6 if stack[-1] else 2 + else: + self.skip_primitive() + if not stack: + return + state = 6 if stack[-1] else 2 + + def read_small_value(self) -> JsonSmallValue: + ch = self.skip_ws() + if ch is None: + raise ValueError("unexpected EOF in JSON value") + if ch == 0x22: + return self.scan_string(capture_limit=_MAX_HEADER_FIELD_BYTES) + if ch == 0x7B: + self.skip_value() + return {} + if ch == 0x5B: + self.skip_value() + return [] + return self.read_primitive() + + +def _scan_selected_object( + cursor: _JsonSliceCursor, spec: Mapping[str, object] +) -> dict[str, object]: + cursor.consume_byte(0x7B) + result: dict[str, object] = {} + ch = cursor.skip_ws() + if ch == 0x7D: + cursor._pos += 1 + return result + while True: + if ch != 0x22: + raise ValueError("expected JSON object key") + key = cursor.scan_string(capture_limit=128, allow_long_key=True) + if cursor.skip_ws() != 0x3A: + raise ValueError("expected colon in JSON object") + cursor._pos += 1 + if key not in spec: + cursor.skip_value() + elif isinstance(spec[key], Mapping): + if cursor.skip_ws() == 0x7B: + result[key] = _scan_selected_object( + cursor, cast(Mapping[str, object], spec[key]) + ) + else: + result[key] = cursor.read_small_value() + else: + result[key] = cursor.read_small_value() + ch = cursor.skip_ws() + if ch == 0x7D: + cursor._pos += 1 + return result + if ch != 0x2C: + raise ValueError("expected comma or end of JSON object") + cursor._pos += 1 + ch = cursor.skip_ws() + + +def _scan_turn_prefix_record(stream: BinaryIO, start: int, stop: int) -> dict[str, object]: + """Decode only Turn/parent metadata from a large earlier record in O(chunk) memory.""" + cursor = _JsonSliceCursor(stream, start, stop) + if cursor.skip_ws() != 0x7B: + raise ValueError("native replay record must be a JSON object") + record = _scan_selected_object(cursor, _PREFIX_RECORD_SPEC) + if cursor.skip_ws() is not None: + raise ValueError("trailing data in native replay record") + return record diff --git a/loopx/control_plane/turn_driver/codex_context_history_replay.py b/loopx/control_plane/turn_driver/codex_context_history_replay.py new file mode 100644 index 0000000000..2397bdcffb --- /dev/null +++ b/loopx/control_plane/turn_driver/codex_context_history_replay.py @@ -0,0 +1,493 @@ +"""Replay verification and interval digestion helpers for native Codex history.""" +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence +import hashlib +import json +from pathlib import Path +import re +from typing import BinaryIO, cast + +from .codex_context_history_json import ( + _IO_CHUNK_BYTES, + _MAX_RECORD_BYTES, + _digest, + _scan_turn_prefix_record, +) + +# A compatibility profile of the native rollout, not a shared control vocabulary. +# Unknown record types fall back to full until their replay semantics qualify. +_APPEND_RECORDS = {"response_item", "turn_context", "world_state", "token_usage_record"} +_APPEND_EVENTS = { + "task_started", + "task_complete", + "item_completed", + "token_count", + "thread_settings_applied", + "exec_command_begin", + "exec_command_end", + "agent_message", + "agent_reasoning", + "agent_reasoning_raw_content", + "agent_reasoning_section_break", + "agent_reasoning_raw_content_delta", + "agent_reasoning_delta", + "agent_message_delta", + "hook_started", + "hook_completed", + "warning", + "error", + "stream_error", + "turn_aborted", + "terminal_interaction", + "background_event", +} +_MAX_SELECTED_REPLAY_READS = 32 +_MAX_COMPLETE_REREADS = 32 +_SHELL_OUTPUT = re.compile( + r"\AChunk ID: [^\r\n]+\nWall time: [0-9.]+ seconds\n" + r"Process exited with code 0\n(?:Original token count: [0-9]+\n)?Output:\n(.*)\Z", + re.DOTALL, +) +_REPLAY_ERRORS = (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError) +_SOURCE_IDENTITY_FIELDS = ( + "path", + "device", + "inode", + "metadata_sha256", + "model", + "permission_mode", +) + + +def _mapping_field(record: Mapping[str, object], key: str) -> Mapping[str, object]: + """Match ``dict.get(key, {}).get(...)`` semantics cleanly for typed mappings.""" + if key not in record: + return {} + value = record[key] + if isinstance(value, Mapping): + return cast(Mapping[str, object], value) + raise AttributeError(f"{key} must be a mapping") + + +def _records(stream: BinaryIO, start: int, end: int) -> Iterator[tuple[int, dict[str, object]]]: + stream.seek(start) + while stream.tell() < end: + offset = stream.tell() + raw = stream.readline(min(_MAX_RECORD_BYTES + 1, end - offset)) + if len(raw) > _MAX_RECORD_BYTES or not raw.endswith(b"\n"): + raise ValueError("incomplete or unsupported native replay record") + parsed = json.loads(raw) + if not isinstance(parsed, dict): + raise TypeError("native replay record must be a JSON object") + yield offset, cast(dict[str, object], parsed) + + +def _region_digest(stream: BinaryIO, start: int, end: int) -> str: + digest = hashlib.sha256() + stream.seek(start) + remaining = end - start + while remaining: + chunk = stream.read(min(_IO_CHUNK_BYTES, remaining)) + if not chunk: + raise ValueError("native reader interval was truncated") + digest.update(chunk) + remaining -= len(chunk) + return digest.hexdigest() + + +def _turn_boundary(record: Mapping[str, object]) -> bool: + return ( + record.get("type") == "event_msg" + and _mapping_field(record, "payload").get("type") == "task_started" + ) + + +def _read_pages(output: object) -> list[dict[str, object]]: + from .codex_context import _context_pages + + # This is the native exec_command result envelope, not a prose classifier. + if isinstance(output, str) and (match := _SHELL_OUTPUT.fullmatch(output)): + output = match[1] + if isinstance(output, list): + return [ + page + for item in output + if isinstance(item, dict) and item.get("type") == "input_text" + for page in _read_pages(item.get("text")) + ] + return cast(list[dict[str, object]], _context_pages(output)) + + +def _covers_bytes(ranges: list[tuple[int, int]], total: int) -> bool: + cursor = 0 + for start, stop in sorted(ranges): + if start > cursor: + return False + cursor = max(cursor, stop) + return cursor == total + + +def _same_replay_source( + anchor: Mapping[str, object], snapshot: Mapping[str, object] +) -> bool: + return all(anchor.get(k) == snapshot.get(k) for k in _SOURCE_IDENTITY_FIELDS) + + +def _matching_replay_interval( + anchor: Mapping[str, object], snapshot: Mapping[str, object], stream: BinaryIO +) -> bool: + start, end = anchor.get("reader_start"), anchor.get("observed_bytes") + observed = snapshot["observed_bytes"] + return ( + _same_replay_source(anchor, snapshot) + and type(start) is int + and type(end) is int + and isinstance(observed, int) + and 0 < start <= end <= observed + and _region_digest(stream, start, end) == anchor.get("reader_sha256") + ) + + +def _read_receipt( + offset: int, digest: str, pages: Sequence[Mapping[str, object]] +) -> dict[str, object]: + return { + "native_offset": offset, + "native_sha256": digest, + "pages_sha256": _digest([dict(page) for page in pages]), + } + + +def _matching_resume_session( + state: Mapping[str, object], event: Mapping[str, object], anchor: object +) -> bool: + return ( + event.get("source") == "resume" + and isinstance(anchor, dict) + and state.get("session_id") == event.get("session_id") + and state.get("cwd") == event.get("cwd") + ) + + +def _verified_replay_capture( + anchor: Mapping[str, object], snapshot: Mapping[str, object], stream: BinaryIO +) -> tuple[Path, bytes, dict[str, object]] | None: + from .decision_capture import read_context_capture_file + + reference = anchor.get("read_source") + if not isinstance(reference, Mapping) or not _matching_replay_interval( + anchor, snapshot, stream + ): + return None + ref_path = reference["path"] + ref_sha = reference["sha256"] + if not isinstance(ref_path, str) or not isinstance(ref_sha, str): + raise TypeError("read_source path and sha256 must be strings") + path, body, payload = read_context_capture_file(ref_path, ref_sha, private=True) + return path, body, cast(dict[str, object], payload) + + +def _emission_pages(payload: Mapping[str, object]) -> Iterator[list[dict[str, object]]]: + output = payload.get("output") + if payload["type"] == "custom_tool_call_output" and isinstance(output, list): + for item in output: + if isinstance(item, dict) and item.get("type") == "input_text": + yield _read_pages(item.get("text")) + else: + yield _read_pages(output) + + +def _append_only(record: Mapping[str, object], event: Mapping[str, object]) -> bool: + kind = record.get("type") + payload = _mapping_field(record, "payload") + if kind == "event_msg": + if payload.get("type") not in _APPEND_EVENTS: + return False + if payload.get("type") == "thread_settings_applied" and payload.get( + "history_mode" + ) not in (None, "paginated"): + return False + elif kind not in _APPEND_RECORDS: + return False + return kind != "turn_context" or ( + payload.get("cwd") == event["cwd"] and payload.get("model") == event["model"] + ) + + +def _replayed_output_groups( + anchor: Mapping[str, object], + snapshot: Mapping[str, object], + stream: BinaryIO, + event: Mapping[str, object], + reads: Sequence[Mapping[str, object]], +) -> Iterator[tuple[int, str, list[dict[str, object]]]]: + # Old private checkpoints did not bind full reads to a call. They may + # still serve their saved file, but cannot attest cross-process retention. + call_offsets: dict[int, str] = {} + for read in reads: + offset = read["native_offset"] + digest = read["native_sha256"] + if not isinstance(offset, int) or not isinstance(digest, str): + raise TypeError("native read receipt must carry int offset and str digest") + if call_offsets.setdefault(offset, digest) != digest: + raise ValueError("native replay call changed between observations") + reader_start = anchor["reader_start"] + observed_bytes = snapshot["observed_bytes"] + if not isinstance(reader_start, int) or not isinstance(observed_bytes, int): + raise TypeError("replay bounds must be integers") + native_calls: dict[str, tuple[int, str]] = {} + closed_calls: set[str] = set() + for offset, record in _records(stream, reader_start, observed_bytes): + if not _append_only(record, event): + raise ValueError("unsupported native replay continuation") + raw_payload = record["payload"] + if not isinstance(raw_payload, Mapping): + raise TypeError("native replay payload must be a mapping") + payload = cast(Mapping[str, object], raw_payload) + if _turn_boundary(record): + native_calls.clear() + closed_calls.clear() + if record["type"] != "response_item": + continue + kind, call = payload.get("type"), payload.get("call_id") + if kind in {"function_call", "custom_tool_call"} and isinstance(call, str): + # Call IDs can repeat in later Turns. Match the exact call + # occurrence observed by the hook. + native_calls.pop(call, None) + closed_calls.discard(call) + if offset in call_offsets and call_offsets[offset] == _digest(record): + native_calls[call] = offset, str(kind) + elif kind in {"function_call_output", "custom_tool_call_output"} and isinstance( + call, str + ): + opened = native_calls.pop(call, None) + if opened is None: + if call in closed_calls: + raise ValueError("duplicate native tool output without a new call") + if ( + kind != "function_call_output" + or offset not in call_offsets + or call_offsets[offset] != _digest(record) + ): + continue + call_offset = offset # the direct output was already present at hook time + else: + call_offset, call_kind = opened + if kind != call_kind + "_output" or call_offset not in call_offsets: + continue + closed_calls.add(call) + for group in _emission_pages(payload): + if group: + yield call_offset, _digest(group), group + + +def _matches( + anchor: Mapping[str, object], + snapshot: Mapping[str, object], + stream: BinaryIO, + event: Mapping[str, object], +) -> bool: + from .decision_capture import capture_page_range + + reads, rereads = anchor.get("reads"), anchor.get("rereads", []) + if not isinstance(reads, list) or not reads or not isinstance(rereads, list): + return False + verified = _verified_replay_capture(anchor, snapshot, stream) + if verified is None: + return False + _, body, _ = verified + read_source = anchor["read_source"] + if not isinstance(read_source, Mapping): + raise TypeError("read_source must be a mapping") + reference_sha = str(read_source["sha256"]) + all_reads = cast(list[Mapping[str, object]], [*reads, *rereads]) + required = {(read["native_offset"], read["pages_sha256"]) for read in all_reads} + ranges: list[tuple[int, int]] = [] + for offset, digest, group in _replayed_output_groups( + anchor, snapshot, stream, event, all_reads + ): + if (offset, digest) not in required: + continue + for page in group: + span = capture_page_range(page, raw=body, digest=reference_sha) + if span is None: + return False + ranges.append(span) + # An independently observed reread can recover a missing range. A copy + # emitted by an unrelated call cannot contribute even identical bytes. + return _covers_bytes(ranges, len(body)) + + +def _int_value(value: object, *, field_name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"{field_name} must be an int") + return value + + +def _reader_slices( + stream: BinaryIO, end: int +) -> Iterator[tuple[int, int, bytes | None]]: + """Walk backwards from ``end`` one chunk at a time, sharing in-chunk line slices.""" + if end <= 0: + return + stream.seek(end - 1) + if stream.read(1) != b"\n": + raise ValueError("incomplete native reader record") + line_end = end + cursor = end - 1 + chunk = b"" + chunk_end = 0 + while cursor > 0: + chunk_start = max(0, cursor - _IO_CHUNK_BYTES) + stream.seek(chunk_start) + chunk = stream.read(cursor - chunk_start) + if len(chunk) != cursor - chunk_start: + raise ValueError("native reader interval was truncated") + chunk_end = chunk_start + len(chunk) + pos = len(chunk) + while True: + split = chunk.rfind(b"\n", 0, pos) + if split < 0: + break + line_start = chunk_start + split + 1 + if line_end > line_start: + raw_slice: bytes | None = None + if line_end <= chunk_end: + raw_slice = chunk[line_start - chunk_start : line_end - chunk_start] + elif line_end == end and cursor == end - 1: + raw_slice = chunk[line_start - chunk_start :] + b"\n" + yield line_start, line_end, raw_slice + line_end = line_start + pos = split + cursor = chunk_start + if line_end > 0: + head_slice = chunk[:line_end] if line_end <= chunk_end else None + yield 0, line_end, head_slice + + +def _reader_spans(stream: BinaryIO, end: int) -> Iterator[tuple[int, int]]: + """Walk backwards from the hook one bounded chunk at a time, yielding line spans.""" + for start, stop, _ in _reader_slices(stream, end): + yield start, stop + + +def _native_reader( + stream: BinaryIO, end: int, event: Mapping[str, object] +) -> tuple[int, str] | None: + """Bind a hook to its own call, or to a single open native Code Mode call.""" + reader = event["tool_use_id"] + completed = False + closed_parents: set[str] = set() + parent: tuple[int, str] | None = None + for offset, stop, raw_slice in _reader_slices(stream, end): + raw_len = stop - offset - 1 + if raw_len > _MAX_RECORD_BYTES: + if parent is None: + raise ValueError("unsupported native reader record") + record = _scan_turn_prefix_record(stream, offset, stop - 1) + else: + if raw_slice is None: + stream.seek(offset) + raw_slice = stream.read(stop - offset) + parsed = json.loads(raw_slice) + if not isinstance(parsed, dict): + raise TypeError("native replay record must be a JSON object") + record = cast(dict[str, object], parsed) + if _turn_boundary(record): + break + raw_payload = record["payload"] + if not isinstance(raw_payload, Mapping): + raise TypeError("native replay payload must be a mapping") + payload = cast(Mapping[str, object], raw_payload) + kind = payload.get("type") + if record.get("type") == "event_msg" and kind == "item_completed": + item = _mapping_field(payload, "item") + if item.get("type") == "CommandExecution" and item.get("id") == reader: + if item.get("exit_code") != 0 or payload.get("turn_id") != event.get( + "turn_id" + ): + return None + completed = True + if record.get("type") != "response_item": + continue + call = payload.get("call_id") + if not isinstance(call, str) or not call: + continue + if call == reader and kind in {"function_call", "function_call_output"}: + if raw_len > _MAX_RECORD_BYTES: + return None + return offset, _digest(record) + if kind == "custom_tool_call_output": + closed_parents.add(call) + if ( + kind != "custom_tool_call" + or payload.get("name") != "exec" + or call in closed_parents + ): + continue + if ( + not completed + or parent is not None + or not isinstance(event.get("turn_id"), str) + ): + return None + # A qualified native record can omit message metadata. The completed + # command still carries the Turn, and the parent is uniquely open. + metadata = payload.get("internal_chat_message_metadata_passthrough") or {} + if not isinstance(metadata, Mapping) or metadata.get("turn_id") not in ( + None, + event["turn_id"], + ): + return None + parent = offset, _digest(record) + return parent + + +def _replayed_selection_sections( + anchor: Mapping[str, object], + snapshot: Mapping[str, object], + stream: BinaryIO, + event: Mapping[str, object], +) -> dict[str, str]: + selections = anchor.get("selections") + if ( + not isinstance(selections, dict) + or not selections + or _verified_replay_capture(anchor, snapshot, stream) is None + ): + return {} + reads: list[Mapping[str, object]] = [ + cast(Mapping[str, object], read) + for selection in selections.values() + if isinstance(selection, Mapping) + for read in cast(Sequence[object], selection["reads"]) + if isinstance(read, Mapping) + ] + outputs = { + (offset, digest) + for offset, digest, _ in _replayed_output_groups( + anchor, snapshot, stream, event, reads + ) + } + retained: dict[str, str] = {} + for selection in selections.values(): + if not isinstance(selection, Mapping): + continue + raw_reads = selection["reads"] + ranges = [ + ( + _int_value(read["start"], field_name="start"), + _int_value(read["end"], field_name="end"), + ) + for read in cast(Sequence[Mapping[str, object]], raw_reads) + if (read["native_offset"], read["pages_sha256"]) in outputs + ] + total_bytes = selection["total_bytes"] + if isinstance(total_bytes, int) and _covers_bytes(ranges, total_bytes): + sections = selection["sections"] + if isinstance(sections, Mapping): + retained.update( + {str(k): str(v) for k, v in sections.items()} + ) + return retained diff --git a/tests/control_plane/test_codex_context_history_contract.py b/tests/control_plane/test_codex_context_history_contract.py new file mode 100644 index 0000000000..b14e77dfb7 --- /dev/null +++ b/tests/control_plane/test_codex_context_history_contract.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import ast +import io +import json +import os +from pathlib import Path +from types import MappingProxyType +import pytest + +from loopx.control_plane.turn_driver import ( + codex_context_history as history_io, + codex_context_history_json as history_json, + codex_context_history_replay as history_replay, +) +from loopx.control_plane.turn_driver.codex_context_history import ( + _IO_CHUNK_BYTES, + _MAX_PRIMITIVE_BYTES, + _MAX_RECORD_BYTES, + _MAX_SKIP_DEPTH, + _JsonSliceCursor, + _digest, + _native_reader, + _reader_slices, + _reader_spans, + _records, + _region_digest, + _scan_selected_object, + _scan_turn_prefix_record, + _turn_boundary, + checkpoint_native_read, + checkpoint_native_selection, + native_resume_sections, + native_resume_verified, + observe_completed_native_reread, + observe_native_read, +) + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _ast_any_nodes(source: str, filename: str) -> list[tuple[int, str]]: + tree = ast.parse(source, filename=filename) + hits: list[tuple[int, str]] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "Any": + hits.append((node.lineno, "Name")) + elif isinstance(node, ast.Attribute) and node.attr == "Any": + hits.append((node.lineno, "Attribute")) + elif isinstance(node, ast.alias) and node.name == "Any": + hits.append((node.lineno, "alias")) + return hits + + +def test_history_modules_satisfy_zero_any_loc_and_posix_budgets() -> None: + from tests.architecture.test_posix_flag_portability import bare_flag_uses + + root = _repo_root() + budgets = { + "loopx/control_plane/turn_driver/codex_context_history.py": (550, 2), + "loopx/control_plane/turn_driver/codex_context_history_json.py": (749, 0), + "loopx/control_plane/turn_driver/codex_context_history_replay.py": (749, 0), + "tests/control_plane/test_codex_context_history_contract.py": (749, 0), + } + type_ignore_marker = "type" + ": ignore" + for rel_path, (max_loc, max_posix) in budgets.items(): + source = (root / rel_path).read_text(encoding="utf-8") + lines = source.splitlines() + assert len(lines) <= max_loc, f"{rel_path} exceeded {max_loc} LOC: {len(lines)}" + assert _ast_any_nodes(source, rel_path) == [], f"{rel_path} uses Any" + ignores = [idx + 1 for idx, line in enumerate(lines) if type_ignore_marker in line] + assert ignores == [], f"{rel_path} has type-ignore comments on {ignores}" + posix_uses = bare_flag_uses(source) + assert len(posix_uses) <= max_posix, f"{rel_path} bare POSIX flags: {posix_uses}" + + +def test_codex_context_history_reexport_identities() -> None: + assert _IO_CHUNK_BYTES == history_json._IO_CHUNK_BYTES + assert _MAX_RECORD_BYTES == history_json._MAX_RECORD_BYTES + assert _JsonSliceCursor is history_json._JsonSliceCursor + assert _digest is history_json._digest + assert _scan_selected_object is history_json._scan_selected_object + assert _scan_turn_prefix_record is history_json._scan_turn_prefix_record + assert _records is history_replay._records + assert _region_digest is history_replay._region_digest + assert _reader_slices is history_replay._reader_slices + assert _reader_spans is history_replay._reader_spans + assert _native_reader is history_replay._native_reader + assert _turn_boundary is history_replay._turn_boundary + assert history_io.observe_native_read is observe_native_read + assert history_io.observe_completed_native_reread is observe_completed_native_reread + assert history_io.native_resume_verified is native_resume_verified + assert history_io.native_resume_sections is native_resume_sections + assert history_io.checkpoint_native_selection is checkpoint_native_selection + assert history_io.checkpoint_native_read is checkpoint_native_read + + +class _CountingBytesIO(io.BytesIO): + def __init__(self, initial_bytes: bytes) -> None: + super().__init__(initial_bytes) + self.seek_calls = 0 + self.read_calls = 0 + + def seek(self, offset: int, whence: int = 0) -> int: + self.seek_calls += 1 + return super().seek(offset, whence) + + def read(self, size: int | None = -1) -> bytes: + self.read_calls += 1 + return super().read(size) + + +def test_native_reader_reuses_chunk_slices_without_per_line_seeks() -> None: + lines: list[bytes] = [ + json.dumps( + { + "type": "session_meta", + "payload": {"id": "s1", "cwd": "/w", "cli_version": "0.169.0-alpha.11.1", "history_mode": "paginated"}, + } + ).encode(), + json.dumps({"type": "event_msg", "payload": {"type": "task_started", "turn_id": "t1"}}).encode(), + ] + call_record = { + "type": "response_item", + "payload": {"type": "function_call", "call_id": "call-target", "arguments": "{}"}, + } + call_bytes = json.dumps(call_record).encode() + lines.append(call_bytes) + for idx in range(120): + lines.append( + json.dumps( + { + "type": "event_msg", + "payload": {"type": "agent_message_delta", "delta": f"tok-{idx}"}, + } + ).encode() + ) + raw = b"\n".join(lines) + b"\n" + assert len(raw) < _IO_CHUNK_BYTES + expected_offset = raw.index(call_bytes) + + stream = _CountingBytesIO(raw) + result = _native_reader(stream, len(raw), {"tool_use_id": "call-target", "turn_id": "t1"}) + assert result == (expected_offset, _digest(call_record)) + # One EOF newline check + one chunk read (2 seeks, 2 reads) vs 120+ per-line seeks/reads. + assert stream.seek_calls <= 3 + assert stream.read_calls <= 3 + spans = list(_reader_spans(io.BytesIO(raw), len(raw))) + assert len(spans) == len(lines) + assert spans[-1][0] == 0 and spans[0][1] == len(raw) + + +def test_reader_slices_fallback_across_chunk_boundary_and_large_record_bounds() -> None: + prefix = json.dumps({"type": "event_msg", "payload": {"type": "task_started", "turn_id": "t1"}}).encode() + # Span across a 64 KiB chunk boundary with one medium JSON line (> 64 KiB, < 16 MiB). + crossing = json.dumps( + { + "type": "response_item", + "payload": { + "type": "function_call", + "call_id": "call-wide", + "padding": "p" * (_IO_CHUNK_BYTES + 2048), + }, + } + ).encode() + tail = json.dumps({"type": "event_msg", "payload": {"type": "background_event"}}).encode() + raw = prefix + b"\n" + crossing + b"\n" + tail + b"\n" + expected_offset = len(prefix) + 1 + result = _native_reader(io.BytesIO(raw), len(raw), {"tool_use_id": "call-wide", "turn_id": "t1"}) + assert result is not None + assert result[0] == expected_offset + + # Unterminated EOF raises cleanly. + with pytest.raises(ValueError, match="incomplete native reader record"): + list(_reader_slices(io.BytesIO(b'{"a":1}'), 7)) + + # Truncated stream mid-digest fails closed. + class _EmptyRead(io.BytesIO): + def read(self, size: int | None = -1) -> bytes: + return b"" + + with pytest.raises(ValueError, match="truncated"): + _region_digest(_EmptyRead(b"abc"), 0, 3) + + +def test_json_slice_cursor_rejects_malformed_constants_overflow_and_depth() -> None: + for bad_const in (b"NaN", b"Infinity", b"-Infinity"): + selected = b'{"type":"event_msg","payload":{"type":' + bad_const + b"}}" + with pytest.raises(ValueError, match="unsupported JSON constant"): + _scan_turn_prefix_record(io.BytesIO(selected), 0, len(selected)) + skipped = b'{"type":"event_msg","payload":{"type":"background_event","x":' + bad_const + b"}}" + with pytest.raises(ValueError, match="invalid JSON number"): + _scan_turn_prefix_record(io.BytesIO(skipped), 0, len(skipped)) + + with pytest.raises(ValueError, match="trailing data"): + _scan_turn_prefix_record(io.BytesIO(b'{"type":"event_msg","payload":{}} []'), 0, 36) + + with pytest.raises(ValueError, match="JSON object"): + _scan_turn_prefix_record(io.BytesIO(b"[]"), 0, 2) + + over_prim = b"1" * (_MAX_PRIMITIVE_BYTES + 1) + with pytest.raises(ValueError, match="oversized JSON primitive"): + _JsonSliceCursor(io.BytesIO(over_prim), 0, len(over_prim)).read_primitive() + + deep = (b"[" * (_MAX_SKIP_DEPTH + 1)) + (b"]" * (_MAX_SKIP_DEPTH + 1)) + with pytest.raises(RecursionError, match="JSON nesting too deep"): + _JsonSliceCursor(io.BytesIO(deep), 0, len(deep)).skip_value() + + +def test_records_and_turn_boundary_reject_non_object_json_and_null_payload() -> None: + with pytest.raises(TypeError, match="JSON object"): + list(_records(io.BytesIO(b"123\n"), 0, 4)) + + assert _turn_boundary({"type": "event_msg", "payload": {"type": "task_started"}}) is True + # Missing payload key falls back to {}, while explicit null/scalar fails closed cleanly. + assert _turn_boundary({"type": "event_msg"}) is False + with pytest.raises(AttributeError, match="payload"): + _turn_boundary({"type": "event_msg", "payload": None}) + + +def _make_valid_rollout(path: Path, *, session_id: str, cwd: str, call_id: str) -> bytes: + rows = [ + json.dumps( + { + "type": "session_meta", + "payload": { + "id": session_id, + "cwd": cwd, + "cli_version": "0.169.0-alpha.11.1", + "history_mode": "paginated", + }, + } + ).encode(), + json.dumps( + {"type": "event_msg", "payload": {"type": "task_started", "turn_id": "turn-1"}} + ).encode(), + json.dumps( + { + "type": "response_item", + "payload": { + "type": "custom_tool_call", + "call_id": "parent-open", + "name": "exec", + "internal_chat_message_metadata_passthrough": None, + }, + } + ).encode(), + json.dumps( + { + "type": "event_msg", + "payload": { + "type": "item_completed", + "turn_id": "turn-1", + "item": {"type": "CommandExecution", "id": call_id, "exit_code": 0}, + }, + } + ).encode(), + ] + data = b"\n".join(rows) + b"\n" + path.write_bytes(data) + os.chmod(path, 0o600) + return data + + +def test_public_entrypoints_preserve_mapping_proxy_and_fail_closed_boundaries( + tmp_path: Path, +) -> None: + rollout = tmp_path / "rollout.jsonl" + _make_valid_rollout(rollout, session_id="sess-1", cwd=str(tmp_path), call_id="cmd-1") + + event = MappingProxyType( + { + "transcript_path": str(rollout), + "session_id": "sess-1", + "cwd": str(tmp_path), + "model": "gpt-test", + "permission_mode": "default", + "turn_id": "turn-1", + "tool_use_id": "cmd-1", + "source": "resume", + } + ) + pages = ( + MappingProxyType({"ok": True, "sha256": "abc"}), + ) + # Null passthrough metadata matches missing passthrough in _native_reader and updates state cleanly. + updated_state = observe_native_read( + MappingProxyType({"pending": {}, "recovery": {"sha256": "abc"}}), + event, + pages, + ) + assert isinstance(updated_state["pending"], dict) + assert "native_reads" in updated_state["pending"] + + # Symlink transcript path fails snapshot check and leaves state unchanged. + symlink_path = tmp_path / "symlink.jsonl" + symlink_path.symlink_to(rollout) + unchanged = observe_native_read( + MappingProxyType({"pending": {}}), + {**dict(event), "transcript_path": str(symlink_path)}, + pages, + ) + assert unchanged == {"pending": {}} + + # Malformed candidate / anchor / empty legacy dicts fail closed cleanly without raising. + assert native_resume_verified({"candidate": None, "session_id": "sess-1", "cwd": str(tmp_path)}, event) is False + assert native_resume_sections({"selected_resume": {}, "session_id": "sess-1", "cwd": str(tmp_path)}, event) == {} + + mutated: dict[str, object] = { + "candidate": {"native_resume": {"read_source": {"sha256": "abc"}}}, + "consumed_pointers": {}, + } + observe_completed_native_reread({"candidate": None}, mutated, event, pages) + checkpoint_native_read({"candidate": None}, mutated, event, pages) + checkpoint_native_selection({}, mutated, event, pages, pages) + assert mutated["consumed_pointers"] == {} From 0d4d7e87278746a75dbfbd4cce60eb1c9d0908b8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:22:02 +0800 Subject: [PATCH 2/2] fix(turn_driver): reject invalid tool call_id on native replay Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../codex_context_history_replay.py | 16 +- .../test_codex_context_history_contract.py | 199 ++++++++++++++++++ 2 files changed, 208 insertions(+), 7 deletions(-) diff --git a/loopx/control_plane/turn_driver/codex_context_history_replay.py b/loopx/control_plane/turn_driver/codex_context_history_replay.py index 2397bdcffb..c177cdb445 100644 --- a/loopx/control_plane/turn_driver/codex_context_history_replay.py +++ b/loopx/control_plane/turn_driver/codex_context_history_replay.py @@ -1,7 +1,7 @@ """Replay verification and interval digestion helpers for native Codex history.""" from __future__ import annotations -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Hashable, Iterator, Mapping, Sequence import hashlib import json from pathlib import Path @@ -236,8 +236,8 @@ def _replayed_output_groups( observed_bytes = snapshot["observed_bytes"] if not isinstance(reader_start, int) or not isinstance(observed_bytes, int): raise TypeError("replay bounds must be integers") - native_calls: dict[str, tuple[int, str]] = {} - closed_calls: set[str] = set() + native_calls: dict[Hashable, tuple[int, str]] = {} + closed_calls: set[Hashable] = set() for offset, record in _records(stream, reader_start, observed_bytes): if not _append_only(record, event): raise ValueError("unsupported native replay continuation") @@ -251,16 +251,18 @@ def _replayed_output_groups( if record["type"] != "response_item": continue kind, call = payload.get("type"), payload.get("call_id") - if kind in {"function_call", "custom_tool_call"} and isinstance(call, str): + if kind in {"function_call", "custom_tool_call"}: + if not isinstance(call, Hashable): + raise TypeError("native tool call_id must be hashable") # Call IDs can repeat in later Turns. Match the exact call # occurrence observed by the hook. native_calls.pop(call, None) closed_calls.discard(call) if offset in call_offsets and call_offsets[offset] == _digest(record): native_calls[call] = offset, str(kind) - elif kind in {"function_call_output", "custom_tool_call_output"} and isinstance( - call, str - ): + elif kind in {"function_call_output", "custom_tool_call_output"}: + if not isinstance(call, Hashable): + raise TypeError("native tool call_id must be hashable") opened = native_calls.pop(call, None) if opened is None: if call in closed_calls: diff --git a/tests/control_plane/test_codex_context_history_contract.py b/tests/control_plane/test_codex_context_history_contract.py index b14e77dfb7..38fac646a5 100644 --- a/tests/control_plane/test_codex_context_history_contract.py +++ b/tests/control_plane/test_codex_context_history_contract.py @@ -1,13 +1,20 @@ from __future__ import annotations +import argparse import ast import io import json import os from pathlib import Path +import subprocess +import sys from types import MappingProxyType import pytest +from loopx.cli_commands.quota_capture import native_context_capture_view +from loopx.cli_commands.quota_context_reader import read_context_capture +from loopx.control_plane.turn_driver import codex_context as context + from loopx.control_plane.turn_driver import ( codex_context_history as history_io, codex_context_history_json as history_json, @@ -316,3 +323,195 @@ def test_public_entrypoints_preserve_mapping_proxy_and_fail_closed_boundaries( checkpoint_native_read({"candidate": None}, mutated, event, pages) checkpoint_native_selection({}, mutated, event, pages, pages) assert mutated["consumed_pointers"] == {} + + +def _project_context( + work: Path, + capture_id: str, + payload: dict[str, object], +) -> dict[str, object]: + capture_dir = work / capture_id + capture_dir.mkdir(mode=0o700) + return context.prepare_codex_context( + dict(payload), + directory=str(work), + capture_directory=capture_dir, + goal_id="fixture", + agent_id="agent", + surface="quota_packet", + capture_id=capture_id, + ).delivery + + +def _read_capture_pages(work: Path, wire: dict[str, object]) -> list[dict[str, object]]: + recovery = wire["recovery"] + assert isinstance(recovery, dict) + view = native_context_capture_view( + dict(wire), + Path(str(recovery["path"])).parent, + context_directory=str(work), + ) + pages: list[dict[str, object]] = [] + offset = 0 + while True: + page = read_context_capture( + argparse.Namespace( + capture_file=view["path"], + capture_sha256=view["sha256"], + offset=offset, + page_bytes=3072, + ) + ) + assert page["ok"] + pages.append(page) + if page["eof"]: + break + offset = int(page["next_offset"]) + return pages + + +@pytest.mark.parametrize( + ("item_kind", "call_id", "expect_candidate", "expect_guidance", "expect_mode"), + [ + ("function_call", ["bad"], False, True, "full"), + ("function_call", {"bad": 1}, False, True, "full"), + ("function_call_output", ["bad"], False, True, "full"), + ("custom_tool_call_output", {"bad": 1}, False, True, "full"), + ("function_call", "call-valid", True, False, "delta"), + ("unknown_item_kind", ["bad"], True, False, "delta"), + ], +) +def test_quota_context_hook_malformed_call_id_revokes_native_resume( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + item_kind: str, + call_id: object, + expect_candidate: bool, + expect_guidance: bool, + expect_mode: str, +) -> None: + base = tmp_path.resolve() + home = base / "home" + home.mkdir(mode=0o700) + work = base / "work" + work.mkdir(mode=0o700) + monkeypatch.chdir(work) + monkeypatch.setenv("CODEX_THREAD_ID", "session") + monkeypatch.delenv("CODEX_ROLLOUT_TRACE_ROOT", raising=False) + + cmd = [ + sys.executable, + "-m", + "loopx.entrypoint", + "--format", + "json", + "quota", + "context-hook", + "--context-delivery", + "on", + "--codex-app", + "--codex-context-dir", + str(work), + ] + env = { + **os.environ, + "HOME": str(home), + "PYTHONPATH": str(_repo_root()), + "CODEX_THREAD_ID": "session", + } + env.pop("CODEX_ROLLOUT_TRACE_ROOT", None) + env.pop("LOOPX_RUNTIME_ROOT", None) + env.pop("LOOPX_REGISTRY", None) + + history = work / "rollout.jsonl" + + def append(kind: str, payload: dict[str, object]) -> None: + with history.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"type": kind, "payload": payload}) + "\n") + + append( + "session_meta", + { + "id": "session", + "cwd": str(work), + "cli_version": "0.162.1", + "history_mode": "paginated", + }, + ) + os.chmod(history, 0o600) + event: dict[str, object] = { + "session_id": "session", + "cwd": str(work), + "hook_event_name": "SessionStart", + "source": "startup", + "transcript_path": str(history), + "model": "fixture", + "permission_mode": "bypassPermissions", + "turn_id": "read-turn", + } + started = subprocess.run( + cmd, input=json.dumps(event), capture_output=True, text=True, cwd=work, env=env, timeout=20, check=False + ) + assert started.returncode == 0, started.stderr + + append("event_msg", {"type": "task_started", "turn_id": "read-turn"}) + append("turn_context", {"cwd": str(work), "model": "fixture"}) + payload: dict[str, object] = { + "ok": True, + "plan_summary": {"requirements": "Keep original evidence. " * 1000}, + "heartbeat_receipt": {"turn_instance_id": "first"}, + } + first = _project_context(work, "one", payload) + first_recovery = first["recovery"] + assert isinstance(first_recovery, dict) + capture_bytes_before = Path(str(first_recovery["path"])).read_bytes() + + for index, page in enumerate(_read_capture_pages(work, first)): + cid = f"reader-{index}" + body = json.dumps(page) + append("response_item", {"type": "function_call_output", "call_id": cid, "output": body}) + hooked = subprocess.run( + cmd, + input=json.dumps( + {**event, "hook_event_name": "PostToolUse", "tool_use_id": cid, "tool_response": body} + ), + capture_output=True, + text=True, + cwd=work, + env=env, + timeout=20, + check=False, + ) + assert hooked.returncode == 0, hooked.stderr + + pre_resume = context._state(work) + assert "native_resume" in pre_resume.get("candidate", {}) + + append("response_item", {"type": item_kind, "call_id": call_id}) + resumed = subprocess.run( + cmd, + input=json.dumps({**event, "source": "resume"}), + capture_output=True, + text=True, + cwd=work, + env=env, + timeout=20, + check=False, + ) + assert resumed.returncode == 0, resumed.stderr + hook_out = json.loads(resumed.stdout or "{}") + post_resume = context._state(work) + second = _project_context( + work, + "second", + {**payload, "heartbeat_receipt": {"turn_instance_id": "second"}}, + ) + + assert ("candidate" in post_resume) is expect_candidate + if expect_guidance: + additional = hook_out["hookSpecificOutput"]["additionalContext"] + assert "quota context-read" in additional + else: + assert hook_out == {} + assert second["mode"] == expect_mode + assert Path(str(first_recovery["path"])).read_bytes() == capture_bytes_before