# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-divergence-when-opentelemetry-genai-span-attributes-are-aggregated-across-a-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-divergence-when-opentelemetry-genai-span-attributes-are-aggregated-across-a-tool-call-fan-out.warrant.json
# Markdown SHA-256:   355791e4f6a82d727b4b835dcc7ab5b537f62195c01e07b67e1455794688b0cd
# Code AST SHA-256:   c67092976d46ec5a7568bc0a0a3713b231ceef58b9a59d502fde2b7b3a5cf113
# Verified Classes:   TokenAccountingDivergence, SpanRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingDivergence(RuntimeError):
    """Raised when GenAI span token aggregation cannot be reconciled."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_id: str | None
    operation: str          # "invoke_agent" | "chat" | "execute_tool"
    input_tokens: int | None
    ended: bool


def reconcile_agent_tokens(
    root: SpanRecord,
    spans: list[SpanRecord],
    rounding_tolerance: int = 1,
) -> int:
    """
    Returns authoritative input-token count for an agent trace.
    Raises TokenAccountingDivergence when the trace is not safe to reconcile.
    """
    if not root.ended:
        raise TokenAccountingDivergence(
            f"root span {root.span_id} not closed; partial sums are invalid"
        )

    children = [s for s in spans if s.parent_id is not None]
    open_children = [s for s in children if not s.ended]
    if open_children:
        raise TokenAccountingDivergence(
            f"{len(open_children)} child span(s) still open under "
            f"{root.span_id}; defer reconciliation"
        )

    chat_spans = [s for s in spans if s.operation == "chat"]
    if not chat_spans:
        raise TokenAccountingDivergence(
            f"no chat spans under {root.span_id}; cannot reconstruct usage"
        )

    missing = [s for s in chat_spans if s.input_tokens is None]
    if missing:
        raise TokenAccountingDivergence(
            f"{len(missing)} chat span(s) lack gen_ai.usage.input_tokens"
        )

    child_sum = sum(s.input_tokens for s in chat_spans)  # type: ignore[arg-type]
    parent_total = root.input_tokens or 0

    if child_sum > parent_total + rounding_tolerance:
        # parent counter lagged; leaf spans are ground truth
        return child_sum

    if child_sum < parent_total - rounding_tolerance:
        raise TokenAccountingDivergence(
            f"ACCOUNTING_GAP: chat spans sum to {child_sum} but parent "
            f"reports {parent_total}; {parent_total - child_sum} tokens "
            f"are unobserved (dropped span or bypassed model call)"
        )

    return parent_total
