# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-tokens-when-an-agent-span-and-its-child-tool-call-spans-both-emit-gen-ai-usage-under-opentelemetry-genai-s.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-tokens-when-an-agent-span-and-its-child-tool-call-spans-both-emit-gen-ai-usage-under-opentelemetry-genai-s.warrant.json
# Markdown SHA-256:   d2c8c7e243bff47602fb1e7686efb487fa5e13e61d085e12d0f848678b77e0c0
# Code AST SHA-256:   ee555f1a663600211bd45b9bc70e2f1ef00009c995253ea14d5f18e44a679040
# Verified Classes:   UsageRollupAmbiguity, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UsageRollupAmbiguity(RuntimeError):
    """Raised when a span carries gen_ai.usage.* while its descendants also do,
    without an explicit rollup marker. Aggregating such a trace double-counts."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str          # e.g. "invoke_agent", "chat", "execute_tool"
    attributes: dict        # flattened OTel attributes
    rollup_marker: bool = False


USAGE_KEYS = (
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.usage.total_tokens",
)


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


def enforce_usage_invariant(spans: list[Span]) -> int:
    """Return the additive token total under leaf-only accounting.

    Rejects any trace where a parent span restates child usage without the
    explicit rollup marker, because summing it alongside leaf usage double-counts.
    """
    by_id = {s.span_id: s for s in spans}

    def descendants(span: Span) -> list[Span]:
        out = []
        for cand in spans:
            p = cand.parent_id
            seen = set()
            while p is not None and p not in seen:
                seen.add(p)
                if p == span.span_id:
                    out.append(cand)
                    break
                p = by_id.get(p).parent_id if p in by_id else None
        return out

    total = 0
    for span in spans:
        if not _has_usage(span):
            continue
        if span.operation in ("invoke_agent", "execute_tool"):
            child_usage = [d for d in descendants(span) if _has_usage(d)]
            if child_usage and not span.rollup_marker:
                raise UsageRollupAmbiguity(
                    f"span {span.span_id} ({span.operation}) carries "
                    f"{[k for k in USAGE_KEYS if k in span.attributes]} while "
                    f"{len(child_usage)} descendant(s) also carry usage; "
                    f"summing would double-count. Set rollup_marker=True or drop "
                    f"parent usage attributes."
                )
        # Leaf-only accounting: only chat/text_completion contribute to the total.
        if span.operation in ("chat", "text_completion"):
            total += int(span.attributes.get("gen_ai.usage.total_tokens", 0))
    return total


# --- trace that reproduces the observed 2x failure ---
trace = [
    Span("root", None, "invoke_agent",
         {"gen_ai.usage.total_tokens": 4400}),
    Span("c1", "root", "chat", {"gen_ai.usage.total_tokens": 1200}),
    Span("c2", "root", "chat", {"gen_ai.usage.total_tokens": 800}),
    Span("c3", "root", "chat", {"gen_ai.usage.total_tokens": 2400}),
]

try:
    enforce_usage_invariant(trace)
except UsageRollupAmbiguity as e:
    # Expected: the rolled-up parent is rejected before it can be summed.
    print("rejected:", e)

# Drop the parent's usage attributes (leaf-only) and re-run.
for s in trace:
    if s.operation == "invoke_agent":
        s.attributes = {k: v for k, v in s.attributes.items() if k not in USAGE_KEYS}
assert enforce_usage_invariant(trace) == 4400
