# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-opentelemetry-genai-spans-span-a-tool-call-graph-that-re-enters-a-resumed-agent-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-parentage-when-opentelemetry-genai-spans-span-a-tool-call-graph-that-re-enters-a-resumed-agent-turn.warrant.json
# Markdown SHA-256:   8d5e0b9c3dade7671083f85b12e4aca53a406e0a4562bdc29f6e72ad37444632
# Code AST SHA-256:   774a9464d5caf916aab3c28e85bc463724bf6afa3125a7049c7f4892c3210321
# Verified Classes:   GenAIParentageViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAIParentageViolation(RuntimeError):
    """Raised when a GenAI tool-call span breaks the semantic parentage invariant."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str            # "chat" | "execute_tool" | "invoke_agent"
    response_id: Optional[str]     # gen_ai.response.id
    tool_call_id: Optional[str]    # gen_ai.tool.call.id
    emitted_by_resumed_instance: bool = False
    inherited_response_id: Optional[str] = None  # resume.previous_response_id


def validate_tool_call_parentage(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    seen_tool_calls: dict[str, str] = {}  # tool_call_id -> span_id

    for s in spans:
        if s.operation_name != "execute_tool":
            continue

        # (1) at-most-once emission per tool.call.id per trace
        if s.tool_call_id in seen_tool_calls:
            raise GenAIParentageViolation(
                f"duplicate execute_tool for tool.call.id={s.tool_call_id}: "
                f"span {s.span_id} collides with {seen_tool_calls[s.tool_call_id]}"
            )
        seen_tool_calls[s.tool_call_id] = s.span_id

        # (2) transport parent must be a chat span
        parent = by_id.get(s.parent_span_id or "")
        if parent is None or parent.operation_name != "chat":
            raise GenAIParentageViolation(
                f"execute_tool {s.span_id} parent {s.parent_span_id} is not a chat span"
            )

        # (3) semantic parentage: response id must match the parent chat span
        if s.response_id != parent.response_id:
            raise GenAIParentageViolation(
                f"execute_tool {s.span_id} response.id={s.response_id} "
                f"!= parent chat response.id={parent.response_id}"
            )

        # (4) a resumed instance must never stamp an inherited response id
        if s.emitted_by_resumed_instance and s.response_id == s.inherited_response_id:
            raise GenAIParentageViolation(
                f"execute_tool {s.span_id} emitted by resumed instance carries "
                f"stale inherited response.id={s.response_id}; "
                f"must mint a fresh id and record inherited id in resume.previous_response_id"
            )
