# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-single-tool-call-span-straddles-a-retry-boundary-and-the-gen-ai-usage-coun.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-single-tool-call-span-straddles-a-retry-boundary-and-the-gen-ai-usage-coun.warrant.json
# Markdown SHA-256:   4223ffb5606ee33a7f03a16b339966e674e7b43f3063cadc892755e0f4ce2f47
# Code AST SHA-256:   9e1ac32e3be7bf4f63429ac5b075dc105d07e7761054d5e52c378610b97b75f1
# Verified Classes:   GenAIUsageReconciliationError, SpanUsage
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional

class GenAIUsageReconciliationError(RuntimeError):
    """Raised when a span's usage attributes cannot be reconciled with its
    descendants under any declared billing rule."""
    pass


@dataclasses.dataclass
class SpanUsage:
    span_id: str
    parent_id: Optional[str]
    input_tokens: int
    output_tokens: int
    billing_rule: Optional[str]  # "leaf-billed" | "aggregate-billed" | None
    ended: bool


def reconcile_operation_usage(spans: dict[str, SpanUsage], root_id: str) -> int:
    """Return the single true billed token total for the logical operation
    rooted at root_id, or raise if the trace is ambiguous."""
    root = spans[root_id]
    if not root.ended:
        raise GenAIUsageReconciliationError(
            f"span {root_id} exported before end(); usage {root.input_tokens}/"
            f"{root.output_tokens} is a partial snapshot, not final"
        )

    descendants = [s for s in spans.values() if s.parent_id == root_id]
    root_total = root.input_tokens + root.output_tokens
    child_total = sum(s.input_tokens + s.output_tokens for s in descendants)

    if root.billing_rule is None:
        if root_total and child_total and root_total != child_total:
            raise GenAIUsageReconciliationError(
                f"span {root_id} has no billing_rule and root_total={root_total} "
                f"disagrees with child_total={child_total}; retry boundary "
                f"crossed inside span lifetime — cannot choose aggregator rule"
            )
        return root_total or child_total

    if root.billing_rule == "leaf-billed":
        if root_total:
            raise GenAIUsageReconciliationError(
                f"span {root_id} declared leaf-billed but carries its own "
                f"gen_ai.usage ({root_total}); would double-count against "
                f"children ({child_total})"
            )
        return child_total

    if root.billing_rule == "aggregate-billed":
        if descendants and root_total != child_total:
            raise GenAIUsageReconciliationError(
                f"span {root_id} declared aggregate-billed but root_total="
                f"{root_total} != child_total={child_total}; a semantic-level "
                f"retry was collapsed into one span and lost billed attempts"
            )
        return root_total

    raise GenAIUsageReconciliationError(
        f"unknown billing_rule {root.billing_rule!r} on span {root_id}"
    )
