# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-in-counterfactual-auditing-of-opentelemetry-genai-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-in-counterfactual-auditing-of-opentelemetry-genai-agent-traces.warrant.json
# Markdown SHA-256:   d202f483f73010aed3f87031d73f22c2eccaeec17512bab16e2ae804aa31043b
# Code AST SHA-256:   9b0a295841108084930fc68818faf79d619e31771084812303df48e3953a4504
# Verified Classes:   ReplayDivergenceError, SpanRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a counterfactual replay cannot be certified sound."""


@dataclass
class SpanRecord:
    span_id: str
    kind: str  # "chat" | "tool"
    assembled_context_hash: Optional[str]  # None if runtime did not log it
    consumption_seq: Optional[int]         # None if runtime did not stamp it
    model_version: Optional[str]
    seed: Optional[int]
    output_tokens: Optional[list]


def certify_replayable(spans: list[SpanRecord], perturbation_span_id: str) -> None:
    """Fail closed unless the trace satisfies the counterfactual-audit contract."""
    seen_perturbation = False
    for span in spans:
        if span.span_id == perturbation_span_id:
            seen_perturbation = True
            break
        if span.kind == "chat":
            if span.assembled_context_hash is None:
                raise ReplayDivergenceError(
                    f"chat span {span.span_id} lacks assembled_context_hash; "
                    "context assembly is not recoverable, replay would re-sample"
                )
            if span.model_version is None or span.seed is None:
                raise ReplayDivergenceError(
                    f"chat span {span.span_id} lacks pinned model_version/seed; "
                    "temperature=0 is not determinism"
                )
        elif span.kind == "tool":
            if span.consumption_seq is None:
                raise ReplayDivergenceError(
                    f"tool span {span.span_id} lacks consumption_seq; "
                    "sibling span order reflects export order, not agent consumption order"
                )
    if not seen_perturbation:
        raise ReplayDivergenceError(
            f"perturbation span {perturbation_span_id} not found in trace"
        )


def run_counterfactual(spans: list[SpanRecord], perturbation_span_id: str,
                       recorded_tokens: list, replayed_tokens: list) -> str:
    certify_replayable(spans, perturbation_span_id)
    if recorded_tokens != replayed_tokens:
        # Divergence before the perturbation point voids the audit.
        raise ReplayDivergenceError(
            "replay diverged from recorded trajectory before perturbation; "
            "counterfactual result is inadmissible"
        )
    return "admissible"
