# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-deterministic-replay-of-agent-traces-when-opentelemetry-genai-span-attributes-are-truncated-reordered-or-sampled-away.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-deterministic-replay-of-agent-traces-when-opentelemetry-genai-span-attributes-are-truncated-reordered-or-sampled-away.warrant.json
# Markdown SHA-256:   e85ecf083216c3d237d2bbf120ccd4bb9f477a2b718088e15ddd222d4de29e50
# Code AST SHA-256:   dd669c30ca3543822281724e68c7ab3ef8da97e7939c019179995058543be560
# Verified Classes:   ReplayInvariantViolation, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayInvariantViolation(RuntimeError):
    """Raised when a trace cannot support deterministic replay."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    step_index: Optional[int]
    start_time_ns: int
    prompt_truncated: bool
    prompt_hash: Optional[str]
    completion_present: bool
    sampled_in: bool
    sampling_rule: Optional[str]


def assert_replayable(spans: list[GenAISpan], require_full_prompt: bool = True) -> None:
    if not spans:
        raise ReplayInvariantViolation("empty span set: nothing to replay")

    for s in spans:
        if not s.sampled_in:
            raise ReplayInvariantViolation(
                f"span {s.span_id} was sampled out; trace is a symptom record, not causal"
            )
        if require_full_prompt and s.prompt_truncated:
            raise ReplayInvariantViolation(
                f"span {s.span_id} prompt truncated; decision inputs not recoverable "
                f"(prompt_hash={s.prompt_hash})"
            )
        if s.step_index is None and s.parent_id is None:
            raise ReplayInvariantViolation(
                f"span {s.span_id} has neither step_index nor parent_id; causal order unprovable"
            )

    # Causal order must be derivable from links/step index, never wall-clock alone.
    by_step = [s for s in spans if s.step_index is not None]
    if by_step:
        steps = [s.step_index for s in by_step]
        if steps != sorted(steps):
            raise ReplayInvariantViolation(
                "step_index sequence is non-monotonic; exporter reordering suspected"
            )


def replay_turn(spans: list[GenAISpan]) -> str:
    assert_replayable(spans)
    # ... feed recorded inputs into pinned model, compare tool-call sequence ...
    return "verified"
