# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-token-accounting-spans-when-tool-call-retries-fork-the-trace-the-double-counting-invariant-at-the-span-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-token-accounting-spans-when-tool-call-retries-fork-the-trace-the-double-counting-invariant-at-the-span-emission.warrant.json
# Markdown SHA-256:   0a4b858ebf285434a98fdbaf0e1d9df2669e389ec3b32182202b575c0da2d73f
# Code AST SHA-256:   c2aeb825f52559b52cff25a6bf0e274cb4832fe88c80551417bc58432f77fa53
# Verified Classes:   UsageAggregationInvariantError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAggregationInvariantError(RuntimeError):
    """Raised when a wrapper span's usage does not reconcile with its children
    under the declared aggregation mode, or when a retried tool call emits
    usage-bearing spans without a stable logical call identifier."""
    pass


@dataclass
class Span:
    span_id: str
    name: str
    parent_id: Optional[str]
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    aggregation: str = "sum"          # "sum" | "none"
    call_id: Optional[str] = None     # stable across retries; None if not a tool call
    retry_attempt: Optional[int] = None


def reconcile(root: Span, descendants: list[Span]) -> int:
    """Return authoritative session token cost, or raise if the trace is
    under-determined by the GenAI conventions."""
    # 1. Retried tool calls MUST carry a stable logical call id, else the
    #    terminal attempt cannot be distinguished from abandoned ones.
    tool_spans = [s for s in descendants if s.name == "execute_tool"]
    for s in tool_spans:
        if s.retry_attempt is not None and s.call_id is None:
            raise UsageAggregationInvariantError(
                f"tool span {s.span_id} has retry_attempt={s.retry_attempt} "
                f"but no call_id; terminal attempt is under-determined"
            )

    # 2. Sum only terminal attempts per logical call, plus non-tool spans.
    terminal: dict[str, Span] = {}
    for s in tool_spans:
        if s.call_id is None:
            continue
        best = terminal.get(s.call_id)
        if best is None or (s.retry_attempt or 0) > (best.retry_attempt or 0):
            terminal[s.call_id] = s

    leaf_sum = 0
    for s in descendants:
        if s.aggregation == "none":
            continue  # pass-through wrapper: do not double-count
        if s.name == "execute_tool":
            if s.call_id is not None and terminal.get(s.call_id) is not s:
                continue  # abandoned attempt: excluded from cost
        leaf_sum += (s.input_tokens or 0) + (s.output_tokens or 0)

    # 3. If the root declares itself aggregating, it MUST equal leaf_sum.
    root_total = (root.input_tokens or 0) + (root.output_tokens or 0)
    if root.aggregation == "sum" and root_total != leaf_sum:
        raise UsageAggregationInvariantError(
            f"root usage {root_total} != reconciled leaf usage {leaf_sum}; "
            f"retry forks or pass-through copies have broken the invariant"
        )
    return leaf_sum
