# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-replay-an-agentic-trace-deterministically-under-otel-genai-conventions-the-span-parenting-invariant-that-silently-breaks-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-replay-an-agentic-trace-deterministically-under-otel-genai-conventions-the-span-parenting-invariant-that-silently-breaks-replay.warrant.json
# Markdown SHA-256:   73e4873210a40569519caf627cfdf9ce76f5cf4eec0b5c2b35e273862e61a0c4
# Code AST SHA-256:   4f4e91d3488925fc709e8d6b72e04f0f6ade1065552d26363cef495975ad8a37
# Verified Classes:   ReplayIneligibilityError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


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


@dataclass(frozen=True)
class Span:
    name: str
    operation: str              # gen_ai.operation.name
    parent_id: str | None
    span_id: str
    consumed_tool_call_ids: frozenset[str]
    emitted_tool_call_ids: frozenset[str]
    start_ns: int
    has_seed: bool
    temperature: float


def assert_deterministically_replayable(spans: Iterable[Span]) -> None:
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}
    tool_spans = [s for s in spans if s.operation == "execute_tool"]
    chat_spans = [s for s in spans if s.operation == "chat"]

    concurrent = len(tool_spans) > 1 and len({t.parent_id for t in tool_spans}) == 1

    for chat in chat_spans:
        for tcid in chat.consumed_tool_call_ids:
            producer = next(
                (t for t in tool_spans if tcid in t.emitted_tool_call_ids), None
            )
            if producer is None:
                raise ReplayIneligibilityError(
                    f"chat span {chat.span_id} consumed tool call {tcid} "
                    f"with no producing span"
                )
            is_descendant = producer.parent_id == chat.span_id
            has_edge = tcid in chat.consumed_tool_call_ids
            if concurrent and not (is_descendant or has_edge):
                raise ReplayIneligibilityError(
                    f"concurrent tool {producer.span_id} consumed by chat "
                    f"{chat.span_id} lacks consumption edge; "
                    f"replay would be structural only"
                )

    for chat in chat_spans:
        if chat.temperature > 0.0 and not chat.has_seed:
            raise ReplayIneligibilityError(
                f"chat span {chat.span_id} has temperature={chat.temperature} "
                f"without gen_ai.request.seed; content replay is nondeterministic"
            )
