# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-single-agent-span-fans-out-into-retried-tool-calls-that-the-exporter-sees.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-single-agent-span-fans-out-into-retried-tool-calls-that-the-exporter-sees.warrant.json
# Markdown SHA-256:   d3a3cd93cc99c4f5550f6d0b732296c927df7675cf67454af26e9a2779e6792a
# Code AST SHA-256:   e2e06b1bfcf9a1f2d5949b560ff2f48a34e2ea8422f7d53e9732b08ed46ab299
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class TokenAccountingInvariantError(RuntimeError):
    """Raised when a trace violates the single-level GenAI usage invariant."""
    pass

@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation_name: str | None
    input_tokens: int = 0
    output_tokens: int = 0
    max_tokens: int | None = None
    finish_reasons: list[str] = field(default_factory=list)

def reconcile_usage(spans: list[Span]) -> dict:
    """Sum GenAI usage across exactly one level of the span tree.

    Contract: contributing spans are either the singleton root that carries
    usage, or the set of leaves that carry usage. Mixed levels raise.
    """
    by_id = {s.span_id: s for s in spans}
    genai = [s for s in spans if s.operation_name is not None
             and (s.input_tokens or s.output_tokens)]
    if not genai:
        return {"input_tokens": 0, "output_tokens": 0, "truncation_ratio": 0.0}

    has_usage = {s.span_id for s in genai}
    roots = [s for s in genai if s.parent_id not in has_usage]
    leaves = [s for s in genai if not any(o.parent_id == s.span_id for o in genai)]

    if len(roots) > 1 and len(leaves) > 1 and set(r.span_id for r in roots) != set(l.span_id for l in leaves):
        # Both an ancestor and its descendant carry usage: ambiguous.
        offending = [s.span_id for s in genai if s.parent_id in has_usage]
        raise TokenAccountingInvariantError(
            f"usage on both ancestor and descendant spans: {offending}; "
            f"trace mixes span-as-invocation and span-as-attempt"
        )

    contributors = leaves if len(leaves) >= len(roots) else roots
    total_in = sum(s.input_tokens for s in contributors)
    total_out = sum(s.output_tokens for s in contributors)

    # Truncation is a max over siblings, never a sum.
    ratios = [s.output_tokens / s.max_tokens for s in contributors if s.max_tokens]
    truncation = max(ratios) if ratios else 0.0

    final_reason: Literal["stop", "length", "error"] = "stop"
    for s in contributors:
        if "length" in s.finish_reasons:
            final_reason = "length"
    return {
        "input_tokens": total_in,
        "output_tokens": total_out,
        "truncation_ratio": truncation,
        "final_finish_reason": final_reason,
        "contributor_count": len(contributors),
    }

def assert_budget_guardrail(spans: list[Span], budget: int) -> None:
    usage = reconcile_usage(spans)
    if usage["input_tokens"] + usage["output_tokens"] > budget:
        raise TokenAccountingInvariantError(
            f"budget exceeded: {usage} > {budget}"
        )
    if usage["truncation_ratio"] > 0.95 and usage["final_finish_reason"] == "length":
        raise TokenAccountingInvariantError(
            f"final attempt near-truncated ({usage['truncation_ratio']:.2f}); "
            f"downstream plan may be built on incomplete reasoning"
        )
