# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-attributes-against-the-tool-call-span-tree-before-closing-an-age.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-attributes-against-the-tool-call-span-tree-before-closing-an-age.warrant.json
# Markdown SHA-256:   5f2999630695c5419935e58a5a6f912e4a9862b9c3474ffc43a1a40360c82340
# Code AST SHA-256:   086c71ef7ec6d19295b3894d0b0a50ddd1e12726130cfd1468c07549450c6914
# Verified Classes:   TokenAccountingReconciliationError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TokenAccountingReconciliationError(RuntimeError):
    """Raised when a GenAI agent span's aggregate cannot be validly reconciled."""


@dataclass
class Span:
    span_id: str
    name: str
    parent_id: str | None
    status: str  # "OK" | "ERROR" | "UNSET"
    input_tokens: int | None = None
    output_tokens: int | None = None
    ended: bool = True
    children: list["Span"] = field(default_factory=list)


def _walk_subtree(root: Span) -> Iterable[Span]:
    yield root
    for child in root.children:
        yield from _walk_subtree(child)


def reconcile_agent_tokens(
    agent_span: Span,
    *,
    include_failed_usage: bool,
    require_quiescence: bool = True,
) -> int:
    """Depth-first reconcile token usage for an invoke_agent span.

    Sums gen_ai.usage.input_tokens across the full subtree, honoring the
    local billability policy for ERROR spans. Fails closed on in-flight
    children or on any child lacking a usage attribute on a chat span.
    """
    total_input = 0
    for span in _walk_subtree(agent_span):
        if span.span_id == agent_span.span_id:
            continue
        if require_quiescence and not span.ended:
            raise TokenAccountingReconciliationError(
                f"child span {span.span_id} ({span.name}) still in-flight "
                f"at accounting time; parent aggregate would be incomplete"
            )
        if span.name not in ("chat", "generate_content"):
            continue
        if span.input_tokens is None:
            raise TokenAccountingReconciliationError(
                f"model span {span.span_id} missing gen_ai.usage.input_tokens; "
                f"cannot reconcile subtree"
            )
        if span.status == "ERROR" and not include_failed_usage:
            continue
        total_input += span.input_tokens
    if total_input == 0:
        raise TokenAccountingReconciliationError(
            f"agent span {agent_span.span_id} reconciled to zero input tokens; "
            f"refusing to write aggregate (likely instrumentation gap)"
        )
    return total_input
