# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-silently-under-accounting-tokens-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-silently-under-accounting-tokens-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   2bdce6ae9939a874a22bd24de4a68f6cd77a3c0682f7b13f4f527e238eb019c6
# Code AST SHA-256:   ec9107e5692bcb7e625f0ee5d74caaa7009af2e4077ebd1f57713504c72cc929
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a turn's span-tree token total diverges from provider billing."""


@dataclass
class Span:
    name: str
    operation: str
    input_tokens: int = 0
    output_tokens: int = 0
    tool_call_id: str | None = None
    children: list["Span"] = field(default_factory=list)


def reconcile_turn(parent: Span, provider_billed_total: int, provider_request_ids: list[str]) -> int:
    """Sum all inference spans under parent and assert equality with provider billing.

    Fails loudly on retry-hidden, post-close-mutation, or id-mismatch under-counts.
    """
    if parent.operation != "invoke_agent":
        raise TokenAccountingInvariantError(
            f"reconcile_turn requires an invoke_agent parent, got {parent.operation!r}"
        )

    total = 0
    seen_tool_ids: set[str] = set()
    inference_count = 0

    def walk(span: Span) -> None:
        nonlocal total, inference_count
        if span.operation == "chat":
            inference_count += 1
            total += span.input_tokens + span.output_tokens
        if span.operation == "execute_tool":
            if span.tool_call_id is None:
                raise TokenAccountingInvariantError(
                    f"execute_tool span {span.name!r} missing gen_ai.tool.call.id; "
                    "downstream attribution will be lost"
                )
            if span.tool_call_id in seen_tool_ids:
                raise TokenAccountingInvariantError(
                    f"duplicate tool_call_id {span.tool_call_id!r}; client/server id minting collision"
                )
            seen_tool_ids.add(span.tool_call_id)
        for child in span.children:
            walk(child)

    walk(parent)

    if inference_count == 0:
        raise TokenAccountingInvariantError(
            f"turn {parent.name!r} has no chat spans; tokens billed but unattributed"
        )

    if total != provider_billed_total:
        deficit = provider_billed_total - total
        raise TokenAccountingInvariantError(
            f"turn {parent.name!r} under-counted by {deficit} tokens "
            f"(span_tree={total}, provider={provider_billed_total}, "
            f"request_ids={provider_request_ids}); likely a retry below the "
            f"instrumentation boundary or a prompt mutated after span close"
        )

    return total
