# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-authoritative-when-its-gen-ai-tool-call-id-is-reused-across-a-retry-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-tool-call-span-as-non-authoritative-when-its-gen-ai-tool-call-id-is-reused-across-a-retry-boundar.warrant.json
# Markdown SHA-256:   57b55ae905507a3e51cb22bee696d4a1cb47e48b6f8fcbc1029c0971591fd530
# Code AST SHA-256:   0b5e922d4552760091ed8aa985f74e5f5a3d22d50e50ba5f2552d66b0753473e
# Verified Classes:   ContestedToolCallIdError, IndeterminateToolCallError, ToolSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Optional


class ContestedToolCallIdError(RuntimeError):
    """Raised when a tool.call.id cannot be resolved to a single authoritative outcome."""
    pass


class IndeterminateToolCallError(RuntimeError):
    """Raised when no terminal span exists but a non-terminal span does (call may have succeeded)."""
    pass


@dataclass(frozen=True)
class ToolSpan:
    tool_call_id: str
    span_id: str
    start_time: float
    end_time: Optional[float]   # None => non-terminal (still open or never closed)
    status: Optional[str]       # "OK" | "ERROR" | None
    result: Optional[str] = None


def resolve_authoritative_outcome(
    spans: Iterable[ToolSpan], tool_call_id: str
) -> ToolSpan:
    """Resolve the single terminal span that may gate execution for a given tool.call.id.

    Enforces the decision boundary: exactly one terminal span, not superseded by a
    later-starting span sharing the same id. Otherwise raise.
    """
    candidates = [s for s in spans if s.tool_call_id == tool_call_id]
    if not candidates:
        raise ContestedToolCallIdError(f"no spans for tool.call.id={tool_call_id!r}")

    terminal = [s for s in candidates if s.end_time is not None and s.status is not None]
    open_spans = [s for s in candidates if s.end_time is None or s.status is None]

    if not terminal:
        # A call may have succeeded server-side with a span that never closed.
        raise IndeterminateToolCallError(
            f"tool.call.id={tool_call_id!r} has {len(open_spans)} non-terminal span(s); "
            "cannot assume failure"
        )

    if len(terminal) > 1:
        # Retry boundary reused the id: multiple attempts, contested authority.
        raise ContestedToolCallIdError(
            f"tool.call.id={tool_call_id!r} has {len(terminal)} terminal spans "
            f"(span_ids={[s.span_id for s in terminal]}); id reused across retry boundary"
        )

    winner = terminal[0]
    # Supersession check: any span starting later than the winner's start invalidates
    # the winner as terminal for the logical call.
    later = [s for s in candidates if s.span_id != winner.span_id and s.start_time > winner.start_time]
    if later:
        raise ContestedToolCallIdError(
            f"tool.call.id={tool_call_id!r} terminal span {winner.span_id!r} is superseded "
            f"by later-starting span(s) {[s.span_id for s in later]}"
        )

    return winner
