# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-reconstructing-an-agentic-session-from-opentelemetry-spans-whose-tool-call-results-were-non-determi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-reconstructing-an-agentic-session-from-opentelemetry-spans-whose-tool-call-results-were-non-determi.warrant.json
# Markdown SHA-256:   fbfc14637cbc07ee9cdfe929efdcada39bdeb5168405afd822528466150d88d1
# Code AST SHA-256:   b495026e0424c83bb8d997c2d0e4d80b8fcfb04459485dc21ffc0d7fd76ceee0
# Verified Classes:   ReplayDivergenceError, UnreconstructableObservationError, ToolSpan, ModelCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when reconstructed model observation != captured observation."""


class UnreconstructableObservationError(RuntimeError):
    """Raised when a span lacks the state needed to rebuild the model input."""


@dataclass
class ToolSpan:
    call_id: str
    truncated: bool
    full_payload: Optional[bytes]      # None if only a preview was recorded
    retained_region: Optional[dict]    # {policy, offset, length, dropped_ranges}
    preview: Optional[bytes]


@dataclass
class ModelCall:
    call_id: str
    input_messages_digest: str         # emitted at capture time; "" if absent


def canonical_digest(messages: list[dict]) -> str:
    # Normalize exactly the fields the model conditioned on.
    norm = [
        {
            "role": m["role"],
            "content": m.get("content", ""),
            "tool_call_id": m.get("tool_call_id"),
            "truncation_marker": m.get("truncation_marker"),
        }
        for m in messages
    ]
    blob = json.dumps(norm, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def rehydrate_tool_message(span: ToolSpan) -> dict:
    if span.truncated and span.full_payload is None:
        if span.retained_region is None:
            raise UnreconstructableObservationError(
                f"span {span.call_id}: truncated=true but no retained_region "
                f"and no full payload; preview cannot substitute for observation"
            )
        # We can rebuild the retained window from the descriptor if payload exists;
        # without payload we still cannot reconstruct bytes.
        raise UnreconstructableObservationError(
            f"span {span.call_id}: retained_region present but full payload absent"
        )
    payload = span.full_payload if span.full_payload is not None else span.preview
    if payload is None:
        raise UnreconstructableObservationError(
            f"span {span.call_id}: no payload or preview recorded"
        )
    return {
        "role": "tool",
        "tool_call_id": span.call_id,
        "content": payload.decode("utf-8", errors="replace"),
        "truncation_marker": (
            f"truncated:{span.retained_region['policy']}"
            if span.truncated and span.retained_region
            else None
        ),
    }


def replay_model_call(span: ToolSpan, call: ModelCall) -> list[dict]:
    tool_msg = rehydrate_tool_message(span)
    messages = [{"role": "assistant", "content": "", "tool_call_id": span.call_id}, tool_msg]
    if not call.input_messages_digest:
        raise UnreconstructableObservationError(
            f"model call {call.call_id}: no capture-time input digest; "
            f"replay cannot be verified, must be marked UNVERIFIED"
        )
    got = canonical_digest(messages)
    if got != call.input_messages_digest:
        raise ReplayDivergenceError(
            f"model call {call.call_id}: reconstructed digest {got[:12]} != "
            f"captured {call.input_messages_digest[:12]}; replay reconstructed "
            f"an observation the model never received"
        )
    return messages


# Trigger trace: truncated tool span, preview only, no region descriptor, no digest.
span = ToolSpan(
    call_id="call_8f2a",
    truncated=True,
    full_payload=None,
    retained_region=None,
    preview=b'[{"id":"doc_11"}, ... 47 items ...]',
)
call = ModelCall(call_id="mc_01", input_messages_digest="")

try:
    replay_model_call(span, call)
except UnreconstructableObservationError as e:
    # Correct outcome: refuse attribution, do not conclude "model ignored doc_11".
    print(f"REPLAY HALTED: {e}")
