# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-graph-replay-from-silently-diverging-when-a-tool-span-s-non-deterministic-output-is-re-materialized-as-a-coun.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-graph-replay-from-silently-diverging-when-a-tool-span-s-non-deterministic-output-is-re-materialized-as-a-coun.warrant.json
# Markdown SHA-256:   27aef49b6b7280f2d586de6b79a837c25fbdea96a6868027c81987fa0df63546
# Code AST SHA-256:   354f1aeb1058473814803471450afd2ef8c55720594e73b1b175e5d111a9d564
# Verified Classes:   ReplayPinningViolation, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayPinningViolation(RuntimeError):
    """Raised when a counterfactual replay would re-materialize a non-pinned span
    whose value feeds a descendant LLM span, breaking the pinning invariant."""
    pass


@dataclass
class Span:
    span_id: str
    operation: str                      # e.g. "chat", "execute_tool"
    replay_mode: Optional[str]          # "pin" | "live" | None
    recorded_attrs: dict = field(default_factory=dict)
    replayed_attrs: dict = field(default_factory=dict)
    parent_id: Optional[str] = None


def assert_pinning_invariant(
    spans: list[Span],
    mutation_set: set[str],
    causal_cone: dict[str, set[str]],   # span_id -> set of downstream span_ids it feeds
) -> None:
    """Enforce: every span in the causal cone of any mutated span must be either
    pinned (byte-identical) or explicitly covered by the mutation set. Any span with
    replay_mode None, or a live span whose cone contains an unpinned tool span, fails."""
    by_id = {s.span_id: s for s in spans}

    for mutated_id in mutation_set:
        if mutated_id not in by_id:
            raise ReplayPinningViolation(
                f"mutation references unknown span {mutated_id!r}"
            )
        for downstream_id in causal_cone.get(mutated_id, set()):
            s = by_id.get(downstream_id)
            if s is None:
                raise ReplayPinningViolation(
                    f"causal cone of {mutated_id!r} references missing span {downstream_id!r}"
                )
            if s.replay_mode is None:
                raise ReplayPinningViolation(
                    f"span {s.span_id!r} in cone of mutation {mutated_id!r} "
                    f"has no replay.mode; refusing to guess pin-vs-execute"
                )
            if s.replay_mode == "live" and s.operation == "execute_tool":
                raise ReplayPinningViolation(
                    f"tool span {s.span_id!r} is live inside cone of mutation "
                    f"{mutated_id!r}; non-deterministic output would be "
                    f"misattributed to the mutation"
                )
            if s.replay_mode == "pin" and s.recorded_attrs != s.replayed_attrs:
                raise ReplayPinningViolation(
                    f"pinned span {s.span_id!r} diverged from recording: "
                    f"recorded={s.recorded_attrs!r} replayed={s.replayed_attrs!r}"
                )
