# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-from-its-opentelemetry-genai-trace-when-tool-outputs-are-re-executed-instead-of-frozen.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-from-its-opentelemetry-genai-trace-when-tool-outputs-are-re-executed-instead-of-frozen.warrant.json
# Markdown SHA-256:   f2aeab2c65600c1b63c1274c5c205c72fcc27d0d1e5153cea56e1361fc3a621d
# Code AST SHA-256:   9418449c5900ef55347da64fd80efdd575b647599225f2f4cf6c40f273ebc49b
# Verified Classes:   ReplayInvariantViolation, ToolSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayInvariantViolation(RuntimeError):
    """Raised when a trace cannot be faithfully replayed because a tool
    payload is missing or truncated, forcing the harness to re-execute
    (a re-run, not a replay)."""


@dataclass
class ToolSpan:
    span_id: str
    tool_name: str
    recorded_payload: Optional[str]
    truncated: bool


def substitute_tool_output(span: ToolSpan) -> str:
    """Return the recorded tool output for injection into the next chat span.

    The invariant: a replay must inject the recorded payload byte-for-byte.
    If the payload is absent or truncated, the harness must refuse rather
    than fall back to live re-execution.
    """
    if span.recorded_payload is None:
        raise ReplayInvariantViolation(
            f"tool span {span.span_id} ({span.tool_name}) has no recorded "
            f"payload; replay would re-execute and diverge at this span"
        )
    if span.truncated:
        raise ReplayInvariantViolation(
            f"tool span {span.span_id} ({span.tool_name}) payload is "
            f"truncated; substitution would diverge at the truncation "
            f"boundary — re-export the trace without truncation"
        )
    return span.recorded_payload


def replay_session(tool_spans: list[ToolSpan]) -> list[str]:
    """Replay by substitution only. Any missing payload halts the replay."""
    injected = []
    for span in tool_spans:
        injected.append(substitute_tool_output(span))
    return injected


if __name__ == "__main__":
    # A trace whose second tool span was truncated by the exporter.
    spans = [
        ToolSpan("s1", "read_file", "TIMEOUT=30", truncated=False),
        ToolSpan("s2", "search", "[A, B, C", truncated=True),
    ]
    try:
        replay_session(spans)
    except ReplayInvariantViolation as e:
        print(f"replay refused: {e}")
