# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-tool-call-spans-with-attributes-that-satisfy-the-otel-genai-semantic-conventions-individually-but-violate-span-tre.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-tool-call-spans-with-attributes-that-satisfy-the-otel-genai-semantic-conventions-individually-but-violate-span-tre.warrant.json
# Markdown SHA-256:   e68b23a187a91f193f4a072aa9dfdf515c5b69c5f2a6bba88d33c4a8b1a57efd
# Code AST SHA-256:   b98bd53084ff07f0ea033559ebe395a0eb5469db171e6d3ff53bd285f41f826e
# Verified Classes:   ToolSpanCardinalityError, ToolSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ToolSpanCardinalityError(RuntimeError):
    """Raised when tool-call spans under an agent turn violate the
    logical-call / attempt-ordinal invariant required for correct
    token and success-rate aggregation."""


@dataclass(frozen=True)
class ToolSpan:
    agent_span_id: str
    tool_call_id: str          # logical call identity, stable across retries
    attempt: int | None        # agent.retry.attempt; None == attribute missing
    status: str                # "OK" | "ERROR"
    input_tokens: int
    output_tokens: int


def aggregate_turn(spans: list[ToolSpan]) -> dict:
    if not spans:
        return {"cost_tokens": 0, "logical_calls": 0, "failed_calls": 0}

    by_call: dict[str, list[ToolSpan]] = {}
    for s in spans:
        if s.attempt is None:
            raise ToolSpanCardinalityError(
                f"tool span for call {s.tool_call_id!r} on agent "
                f"{s.agent_span_id!r} is missing agent.retry.attempt; "
                "aggregation cannot distinguish retries from distinct calls"
            )
        by_call.setdefault(s.tool_call_id, []).append(s)

    cost_tokens = 0
    failed_calls = 0
    for call_id, attempts in by_call.items():
        ordinals = sorted(a.attempt for a in attempts)
        if ordinals != list(range(len(attempts))):
            raise ToolSpanCardinalityError(
                f"call {call_id!r} has non-contiguous attempt ordinals "
                f"{ordinals}; expected 0..{len(attempts) - 1}. "
                "A gap means a span was dropped and cost is under-counted."
            )
        # Cost: sum attempt-0 only per declared accounting contract.
        base = next(a for a in attempts if a.attempt == 0)
        cost_tokens += base.input_tokens + base.output_tokens
        # Success: terminal attempt decides the logical call outcome.
        terminal = max(attempts, key=lambda a: a.attempt)
        if terminal.status != "OK":
            failed_calls += 1

    return {
        "cost_tokens": cost_tokens,
        "logical_calls": len(by_call),
        "failed_calls": failed_calls,
    }
