# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-double-counting-child-tool-call-tokens-during-mid-trace-context-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-double-counting-child-tool-call-tokens-during-mid-trace-context-handoff.warrant.json
# Markdown SHA-256:   01e2ce2006198eccce612f37fff822dd81d5184fcbba453a5b752be48737881e
# Code AST SHA-256:   e310c5a8bd5c625bcf657c504b204e81572707c3eb4673dd2aea374c00b43425
# Verified Classes:   UsageAttributionConflict, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UsageAttributionConflict(RuntimeError):
    """Raised when a trace mixes leaf and agent-rollup token attribution."""


@dataclass
class Span:
    name: str
    operation: str                      # gen_ai.operation.name
    attributes: dict = field(default_factory=dict)

    def usage(self) -> tuple[int, int]:
        return (
            int(self.attributes.get("gen_ai.usage.input_tokens", 0)),
            int(self.attributes.get("gen_ai.usage.output_tokens", 0)),
        )


def reconcile_trace_usage(spans: Iterable[Span]) -> tuple[int, int]:
    spans = list(spans)
    modes = {
        s.attributes.get("gen_ai.usage.attribution_mode")
        for s in spans
        if "gen_ai.usage.attribution_mode" in s.attributes
    }
    if len(modes) > 1:
        raise UsageAttributionConflict(
            f"trace mixes attribution modes {sorted(modes)}; "
            f"refusing to sum gen_ai.usage.*"
        )

    mode = next(iter(modes), "leaf")
    if mode == "leaf":
        contributing = [s for s in spans if s.operation == "chat"]
    elif mode == "agent_rollup":
        contributing = [s for s in spans if s.operation == "invoke_agent"]
    else:
        raise UsageAttributionConflict(f"unknown attribution mode {mode!r}")

    if not contributing:
        raise UsageAttributionConflict(
            f"mode={mode!r} but no contributing spans found in trace"
        )

    tin = sum(s.usage()[0] for s in contributing)
    tout = sum(s.usage()[1] for s in contributing)
    return tin, tout


# Reproduces the observed incident: orchestrator mirrors sub-agent usage.
trace = [
    Span("agent.orchestrator", "invoke_agent",
         {"gen_ai.usage.input_tokens": 14000,
          "gen_ai.usage.attribution_mode": "leaf"}),
    Span("agent.retriever", "invoke_agent",
         {"gen_ai.usage.input_tokens": 4200,
          "gen_ai.usage.attribution_mode": "agent_rollup"}),
    Span("chat.synthesis", "chat",
         {"gen_ai.usage.input_tokens": 9800,
          "gen_ai.usage.attribution_mode": "leaf"}),
]

try:
    reconcile_trace_usage(trace)
except UsageAttributionConflict as e:
    # Correct behavior: refuse to emit a number, surface the conflict.
    print(f"usage_attribution_conflict: {e}")
