# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-spans-when-a-tool-call-is-retried-inside-a-single-agent-turn-and-the-span-model-loses-causal-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-spans-when-a-tool-call-is-retried-inside-a-single-agent-turn-and-the-span-model-loses-causal-identity.warrant.json
# Markdown SHA-256:   0feb51fe04ec8eed8d5381a5f60fb6dd830d39d002eb8f9f177d6e785f3e479d
# Code AST SHA-256:   a576568c3db33d581dc491cf085be56e6d135568f6a13d449f1f66290d8ad809
# Verified Classes:   SpanCausalityViolation, 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 GenAI tool-call trace violates the 1:1 logical-call invariant."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    tool_call_id: str
    attempt: Optional[int]          # gen_ai.tool.attempt, None if adapter omitted it
    status: str                     # "OK" or "ERROR"
    tool_name: str


def validate_tool_causality(spans: list[ToolSpan]) -> dict[str, ToolSpan]:
    """Return {tool_call_id: terminal_span}. Enforce the retry invariant."""
    by_call: dict[str, list[ToolSpan]] = {}
    for s in spans:
        by_call.setdefault(s.tool_call_id, []).append(s)

    terminal: dict[str, ToolSpan] = {}
    for call_id, attempts in by_call.items():
        # Invariant 1: attempt index must be present and contiguous from 1.
        indices = sorted(a.attempt for a in attempts)
        if None in indices:
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: attempt index missing on a retried call; "
                f"causal identity is ambiguous and downstream joins will collide"
            )
        if indices != list(range(1, len(indices) + 1)):
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: non-contiguous attempt sequence {indices}; "
                f"a retry was emitted without an attempt discriminator"
            )
        # Invariant 2: exactly one terminal-success attempt.
        ok = [a for a in attempts if a.status == "OK"]
        if len(ok) != 1:
            raise SpanCausalityViolation(
                f"tool_call_id={call_id}: expected exactly 1 terminal-success span, "
                f"found {len(ok)}; replay and cost attribution will double-count"
            )
        terminal[call_id] = ok[0]
    return terminal


def reconstruct_turn(spans: list[ToolSpan]) -> list[ToolSpan]:
    """Replay-safe reconstruction: terminal attempts only, attempt-ordered."""
    terminal = validate_tool_causality(spans)
    return sorted(terminal.values(), key=lambda s: (s.parent_span_id, s.attempt or 0))
