# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-reconstructing-multi-agent-sessions-from-otel-genai-span-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-reconstructing-multi-agent-sessions-from-otel-genai-span-graphs.warrant.json
# Markdown SHA-256:   d496d26f80ec41a6f19efa45e49ec3fd89a6934e89860b0477502e0f6a67027c
# Code AST SHA-256:   8d7935e8432c9fc4f0fd2db556ba8517f704335b97eb73a620a65d02dfbc048b
# Verified Classes:   ReplayDivergenceError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class ReplayDivergenceError(RuntimeError):
    """Raised when a span graph cannot be replayed without divergence."""
    pass

@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    kind: str  # "llm" | "tool" | "fanin" | "retry"
    final_prompt_bytes: Optional[bytes]  # authoritative input, post-assembly
    tool_output_bytes: Optional[bytes]   # transport-captured, byte-stable
    child_order: Optional[list[str]]     # explicit fan-in arrival order
    retry_of: Optional[str] = None
    start_time_ns: int = 0

def validate_replayable(spans: list[Span]) -> None:
    for s in spans:
        if s.kind == "llm" and s.final_prompt_bytes is None:
            raise ReplayDivergenceError(
                f"span {s.span_id}: LLM prompt absent; re-derivation from "
                f"children is not replay-equivalent"
            )
        if s.kind == "tool" and s.tool_output_bytes is None:
            raise ReplayDivergenceError(
                f"span {s.span_id}: tool output not transport-captured; "
                f"parse-round-trip is not byte-stable"
            )
        if s.kind == "fanin" and s.child_order is None:
            raise ReplayDivergenceError(
                f"span {s.span_id}: fan-in without explicit child order; "
                f"start_time/span_id sort does not encode arrival order"
            )
        if s.kind == "retry" and s.parent_id is not None:
            parent = next((p for p in spans if p.span_id == s.parent_id), None)
            if parent is not None and parent.kind != "fanin":
                raise ReplayDivergenceError(
                    f"span {s.span_id}: retry parented under non-initiating "
                    f"span {s.parent_id}; replay would re-execute failed branch"
                )
