# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-forensic-replay-from-silently-diverging-when-an-agent-resumes-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-forensic-replay-from-silently-diverging-when-an-agent-resumes-mid-tool-call.warrant.json
# Markdown SHA-256:   1cb514caa79cbc02ff2513e357b1ed16bfd68f36d07d78cbf8d5101516211136
# Code AST SHA-256:   37a65d93f5e0909404a005f97e07ae8fb4f9755f8b6f8bd3aa09b5fdf8c5c3b9
# Verified Classes:   ReplayIntegrityError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ReplayIntegrityError(RuntimeError):
    """Raised when a GenAI telemetry trace cannot be deterministically replayed."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    start_time: float
    end_time: Optional[float]
    attrs: dict


def _hash_messages(messages: list) -> str:
    return hashlib.sha256(
        json.dumps(messages, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def verify_replayable(spans: list[Span], checkpoint_span_id: str) -> None:
    """
    Enforce the four replay invariants before any reconstruction is attempted.
    Raises ReplayIntegrityError on the first violated invariant, with the
    offending span id so downstream tooling can localize the gap.
    """
    by_id = {s.span_id: s for s in spans}

    # Invariant 1: span closure (or explicit orphan marking).
    for s in spans:
        if s.end_time is None:
            if not s.attrs.get("gen_ai.checkpoint.orphan"):
                raise ReplayIntegrityError(
                    f"open span {s.span_id} at checkpoint {checkpoint_span_id} "
                    f"is not marked gen_ai.checkpoint.orphan=true"
                )

    # Invariant 2: per-span context hash present.
    for s in spans:
        if "gen_ai.input.messages.hash" not in s.attrs:
            raise ReplayIntegrityError(
                f"span {s.span_id} missing gen_ai.input.messages.hash; "
                f"context-hash invariant cannot be verified"
            )

    # Invariant 3: idempotency-key persistence across resume boundary.
    call_ids = {}
    for s in spans:
        cid = s.attrs.get("gen_ai.tool.call.id")
        if cid is None:
            continue
        if cid in call_ids and call_ids[cid] != s.span_id:
            prev = by_id[call_ids[cid]]
            if prev.trace_id != s.trace_id and not s.attrs.get("gen_ai.tool.call.retry_of"):
                raise ReplayIntegrityError(
                    f"tool call id {cid} reused across trace boundary "
                    f"({prev.trace_id} -> {s.trace_id}) without retry_of edge"
                )
        call_ids[cid] = s.span_id

    # Invariant 4: causal order across resume (cross-trace parent).
    for s in spans:
        if s.parent_span_id and s.parent_span_id not in by_id:
            if "gen_ai.resume.from_span_id" not in s.attrs:
                raise ReplayIntegrityError(
                    f"span {s.span_id} references parent {s.parent_span_id} "
                    f"outside trace {s.trace_id} without gen_ai.resume.from_span_id"
                )


def replay_decision(span: Span, reconstructed_messages: list) -> None:
    """Replay a single decision, verifying the context-hash invariant first."""
    recorded = span.attrs["gen_ai.input.messages.hash"]
    actual = _hash_messages(reconstructed_messages)
    if recorded != actual:
        raise ReplayIntegrityError(
            f"context-hash divergence at span {span.span_id}: "
            f"recorded={recorded[:12]} actual={actual[:12]}"
        )
