# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-tokens-across-nested-genai-spans-the-opentelemetry-gen-ai-usage-input-tokens-attribution-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-tokens-across-nested-genai-spans-the-opentelemetry-gen-ai-usage-input-tokens-attribution-boundary.warrant.json
# Markdown SHA-256:   5e1642785aa28ba6b61d88204d0313e23073f34e7e408da975886499513ac59a
# Code AST SHA-256:   847cf68b73950ca4c2b0229ec7cfc86f464640f69616d43d8e1c324c0291c279
# Verified Classes:   TokenAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

MODEL_INVOCATION_OPS = {"chat", "text_completion", "embeddings", "generate_content"}
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")


class TokenAttributionError(RuntimeError):
    """Raised when span-level token accounting violates the leaf-only invariant."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation_name: str | None
    attributes: dict = field(default_factory=dict)


def _has_usage(span: Span) -> bool:
    return any(k in span.attributes for k in USAGE_KEYS)


def sum_billable_input_tokens(spans: list[Span]) -> int:
    """
    Enforce: gen_ai.usage.* is authoritative only on leaf model-invocation spans.
    Any model-invocation span that carries usage AND has a descendant carrying
    usage is a rollup masquerading as a call -> reject the trace.
    """
    by_id = {s.span_id: s for s in spans}

    def descendants(span: Span):
        for cand in spans:
            p = cand.parent_id
            while p is not None:
                if p == span.span_id:
                    yield cand
                    break
                p = by_id[p].parent_id if p in by_id else None

    total = 0
    for span in spans:
        if span.operation_name not in MODEL_INVOCATION_OPS:
            if _has_usage(span):
                raise TokenAttributionError(
                    f"span {span.span_id} op={span.operation_name!r} carries "
                    f"gen_ai.usage.* but is not a model-invocation span; "
                    f"rollups must use a namespaced key, not the convention."
                )
            continue
        if not _has_usage(span):
            continue
        if any(_has_usage(d) for d in descendants(span)):
            raise TokenAttributionError(
                f"span {span.span_id} op={span.operation_name!r} carries "
                f"gen_ai.usage.* and has usage-bearing descendants; "
                f"this is a rollup and would double-count. Emit leaf usage only."
            )
        total += int(span.attributes.get("gen_ai.usage.input_tokens", 0))
    return total


# Trace from the incident: parent rollup + three leaf chat spans.
trace = [
    Span("p", None, "invoke_agent",
         {"gen_ai.usage.input_tokens": 4820, "gen_ai.usage.output_tokens": 610}),
    Span("c1", "p", "chat", {"gen_ai.usage.input_tokens": 1500}),
    Span("c2", "p", "chat", {"gen_ai.usage.input_tokens": 2100}),
    Span("c3", "p", "chat", {"gen_ai.usage.input_tokens": 1220}),
]

try:
    sum_billable_input_tokens(trace)
except TokenAttributionError as e:
    print(f"REJECTED trace: {e}")
    # Consumer must then trust leaf sum only:
    print("billable input =", sum(
        int(s.attributes["gen_ai.usage.input_tokens"])
        for s in trace if s.operation_name == "chat"
    ))
