# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-single-logical-tool-call-is-retried-across-two-model-invocations-under-one.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-single-logical-tool-call-is-retried-across-two-model-invocations-under-one.warrant.json
# Markdown SHA-256:   972be2719b511381866d00a267c4841bedd239b7ca613cd3b89c26a71d87b63e
# Code AST SHA-256:   1d3b7e7d449d601e1d20ede2fdc1580b2c4a648f3ea226ca394becb17cb128e6
# Verified Classes:   SpanReconciliationError, ToolSpan, TraceRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanReconciliationError(RuntimeError):
    """Raised when a retry chain violates the one-terminal-span-per-call invariant."""
    pass


@dataclass
class ToolSpan:
    trace_id: str
    tool_call_id: str
    attempt: int
    terminal: bool
    status_ok: bool


@dataclass
class TraceRegistry:
    # trace_id -> tool_call_id -> list of spans
    spans: dict = field(default_factory=dict)

    def register(self, span: ToolSpan) -> None:
        key = (span.trace_id, span.tool_call_id)
        existing = self.spans.setdefault(key, [])
        if span.terminal and any(s.terminal for s in existing):
            raise SpanReconciliationError(
                f"trace {span.trace_id} call {span.tool_call_id}: "
                f"second terminal span (attempt {span.attempt}); "
                f"a retry chain must have exactly one terminal span. "
                f"Set terminal=false on superseded attempts."
            )
        if span.attempt in {s.attempt for s in existing}:
            raise SpanReconciliationError(
                f"trace {span.trace_id} call {span.tool_call_id}: "
                f"duplicate attempt index {span.attempt}; "
                f"attempt must be monotonically increasing per call."
            )
        existing.append(span)

    def authoritative(self, trace_id: str, tool_call_id: str) -> Optional[ToolSpan]:
        chain = self.spans.get((trace_id, tool_call_id), [])
        terminals = [s for s in chain if s.terminal]
        if len(terminals) != 1:
            raise SpanReconciliationError(
                f"trace {trace_id} call {tool_call_id}: "
                f"expected exactly 1 terminal span, found {len(terminals)}"
            )
        return terminals[0]
