# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-genai-span-log-whose-tool-call-results-were-truncated-by-the-exporter-s-attribute-size-cap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-genai-span-log-whose-tool-call-results-were-truncated-by-the-exporter-s-attribute-size-cap.warrant.json
# Markdown SHA-256:   9dde5dd2a436bcd7ace71be558ee088ebb87e8c3e469c4cb85d754fe2235f341
# Code AST SHA-256:   645db69e93db318854e60f8b45165a772529abfdab469bfe3acadc262c0e1540
# Verified Classes:   TruncationFrontierError, ToolSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Iterable


class TruncationFrontierError(RuntimeError):
    """Raised when replay would reason across a capped causal input."""
    pass


@dataclass(frozen=True)
class ToolSpan:
    turn_index: int
    tool_name: str
    stored_result: str
    declared_original_len: int | None  # from gen_ai.tool.call.result.original_length, if emitted
    truncated_flag: bool | None        # from gen_ai.tool.call.result.truncated, if emitted


def compute_truncation_frontier(spans: Iterable[ToolSpan], effective_cap: int) -> int | None:
    """
    Return the earliest turn index whose causal input cannot be proven complete,
    or None if every tool result is provably byte-identical to the live input.

    A span is 'provably complete' only if:
      - it declares original_length and that length equals the stored length, OR
      - it explicitly declares truncated=False AND stored length < effective_cap.
    Length-equal-to-cap with no flag is treated as UNKNOWN -> frontier.
    """
    for span in sorted(spans, key=lambda s: s.turn_index):
        stored_len = len(span.stored_result.encode("utf-8"))

        if span.declared_original_len is not None:
            if span.declared_original_len != stored_len:
                return span.turn_index
            continue

        if span.truncated_flag is True:
            return span.turn_index

        if span.truncated_flag is False and stored_len < effective_cap:
            continue

        # No flag, or stored length sits exactly at the cap: unprovable.
        if stored_len >= effective_cap:
            return span.turn_index

    return None


def assert_replay_admissible(spans: list[ToolSpan], investigate_turn: int, effective_cap: int) -> None:
    frontier = compute_truncation_frontier(spans, effective_cap)
    if frontier is not None and investigate_turn >= frontier:
        raise TruncationFrontierError(
            f"Cannot explain turn {investigate_turn}: causal input truncated at turn "
            f"{frontier} (cap={effective_cap}B). Replay above frontier is "
            f"reconstruction-only; re-acquire untruncated tool payloads via "
            f"tool.output.ref before drawing causal conclusions."
        )


# Example: the turn-17 divergence from the observed session.
session_spans = [
    ToolSpan(3,  "read_file",   "x" * 1200, None, False),
    ToolSpan(17, "read_file",   "y" * 4096, None, None),   # hit the cap, no flag
    ToolSpan(29, "read_file",   "z" * 4096, None, None),
]

assert_replay_admissible(session_spans, investigate_turn=18, effective_cap=4096)
# -> raises TruncationFrontierError, preventing the fabricated "agent looped" postmortem
