# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-double-count-tokens-when-a-tool-call-re-enters-the-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-double-count-tokens-when-a-tool-call-re-enters-the-agent-span.warrant.json
# Markdown SHA-256:   031710c057c69cdd9118d1d0df6f07ae0bde9be1477cc615c248dda74c11cce1
# Code AST SHA-256:   3233dd8bf3e5d2835d483128faed59cd7126ff68937b3d9bf073ddb1add8d8ad
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a trace's leaf-chat token sum cannot be reconciled."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str          # "chat", "execute_tool", "agent", ...
    input_tokens: int = 0
    output_tokens: int = 0
    status: str = "OK"
    retry_of: str | None = None


def reconcile_turn(spans: Iterable[Span], provider_billed_input: int,
                   tolerance: float = 0.02) -> int:
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}
    chat_ids = {s.span_id for s in spans if s.operation == "chat"}

    # A chat span is a leaf-inference iff it has no chat descendant.
    has_chat_child: set[str] = set()
    for s in spans:
        p = s.parent_id
        while p is not None and p in by_id:
            if p in chat_ids:
                has_chat_child.add(p)
            p = by_id[p].parent_id

    # Drop retries: keep only the last attempt per retry chain.
    superseded = {s.retry_of for s in spans if s.retry_of}

    leaf_input = 0
    for s in spans:
        if s.operation != "chat":
            continue
        if s.span_id in has_chat_child:
            continue  # rollup or ancestor inference, not a leaf
        if s.span_id in superseded:
            continue  # superseded by a retry
        leaf_input += s.input_tokens

    if provider_billed_input <= 0:
        raise TokenAccountingInvariantError(
            f"provider billed input is non-positive ({provider_billed_input}); "
            "cannot anchor reconciliation"
        )

    drift = abs(leaf_input - provider_billed_input) / provider_billed_input
    if drift > tolerance:
        raise TokenAccountingInvariantError(
            f"leaf-chat input {leaf_input} diverges from billed "
            f"{provider_billed_input} by {drift:.1%}; trace accounting graph "
            "is likely double-counting rollups or retries"
        )
    return leaf_input
