# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-trees-from-silently-dropping-tool-call-causality-during-agent-turn-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-trees-from-silently-dropping-tool-call-causality-during-agent-turn-fan-out.warrant.json
# Markdown SHA-256:   c4bf03adab3b100760fda8b764678a08596179cd356934176f7f2572b680d60c
# Code AST SHA-256:   81fa5b26702407e3ac59b00ed89529b71edfbaa9f91598c3dceb967483c9d036
# Verified Classes:   SpanCausalityViolation, TurnSpan, ToolSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanCausalityViolation(RuntimeError):
    """Raised when a tool-call span's parent/call-id edge is not causally valid."""
    pass


@dataclass
class TurnSpan:
    span_id: str
    requested_call_ids: set[str] = field(default_factory=set)
    closed: bool = False


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: Optional[str]
    tool_call_id: str


def validate_tool_span_causality(turn: TurnSpan, tool: ToolSpan) -> None:
    """Enforce the invariant: tool span must be parented by the turn that
    requested its call ID, and that call ID must be in the turn's completion."""
    if turn.closed:
        raise SpanCausalityViolation(
            f"turn {turn.span_id} closed before tool {tool.tool_call_id} "
            "reported; parent edge lost (orphaned fan-out)"
        )
    if tool.parent_span_id != turn.span_id:
        raise SpanCausalityViolation(
            f"tool {tool.tool_call_id} parented to {tool.parent_span_id}, "
            f"expected turn {turn.span_id} (contextvar reset / cross-wire)"
        )
    if tool.tool_call_id not in turn.requested_call_ids:
        raise SpanCausalityViolation(
            f"tool {tool.tool_call_id} not present in turn {turn.span_id} "
            f"completion tool_calls {sorted(turn.requested_call_ids)} "
            "(call-id swap under non-deterministic completion order)"
        )


def emit_fanout(turn: TurnSpan, tools: list[ToolSpan]) -> None:
    for t in tools:
        validate_tool_span_causality(turn, t)
    # only reached if every child edge is causally faithful
