# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-the-model-invocation-span-closes-before-the-tool-result-is-attributed.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-the-model-invocation-span-closes-before-the-tool-result-is-attributed.warrant.json
# Markdown SHA-256:   cc6388ecf90c010bbfcd3136fca1a6408a31fac0364ad8243c8723f3215f26cd
# Code AST SHA-256:   c8de0f88904b2557bb3bea7e8b3a70d85c0bd6235f1cb5f66c49111391d5d422
# Verified Classes:   TraceAttributionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceAttributionError(RuntimeError):
    """Raised when a GenAI trace's tool-call attribution is causally invalid."""
    pass


@dataclass
class Span:
    name: str
    operation: str            # "chat" or "execute_tool"
    start_time: float
    end_time: Optional[float]
    tool_call_ids: list[str]  # IDs this span requested (chat) or executed (tool)
    parent_id: Optional[str]
    link_ids: list[str]       # explicit span links, timestamp-agnostic
    span_id: str


def validate_genai_trace(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}

    for chat in (s for s in spans if s.operation == "chat"):
        if chat.end_time is None:
            raise TraceAttributionError(
                f"chat span {chat.span_id} never closed; cannot attribute tool calls"
            )
        for call_id in chat.tool_call_ids:
            resolved = [
                t for t in spans
                if t.operation == "execute_tool" and call_id in t.tool_call_ids
            ]
            if not resolved:
                raise TraceAttributionError(
                    f"chat {chat.span_id} requested tool call {call_id} "
                    f"but no execute_tool span carries that id"
                )
            for tool in resolved:
                linked = tool.span_id in chat.link_ids or chat.span_id in tool.link_ids
                parented = tool.parent_id == chat.span_id
                if parented and tool.start_time > chat.end_time:
                    raise TraceAttributionError(
                        f"causal inversion: tool {tool.span_id} starts "
                        f"({tool.start_time}) after parent chat {chat.span_id} "
                        f"ended ({chat.end_time}); use a span link, not parent-child"
                    )
                if not linked and not parented:
                    raise TraceAttributionError(
                        f"tool {tool.span_id} for call {call_id} is unattributed: "
                        f"no link or parent edge to chat {chat.span_id}"
                    )
