# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-the-tool-call-span-to-the-wrong-agent-turn-and-the-genai-token-accounting-silently-double-counts-the-parent-s.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-the-tool-call-span-to-the-wrong-agent-turn-and-the-genai-token-accounting-silently-double-counts-the-parent-s.warrant.json
# Markdown SHA-256:   545d92ea22538d574b4bd6deaccb1107b95bae06a28a70519f3dfab2ae0b2d26
# Code AST SHA-256:   fc528f115969f146095ecb3b01e2bcb96a7b2336beafecebdf709be33d8d44cd
# Verified Classes:   UsageAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class UsageAttributionError(RuntimeError):
    """Raised when a span graph violates the leaf-only usage invariant."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    kind: str  # "agent.turn" | "gen_ai.chat" | "gen_ai.tool"
    output_tokens: int | None = None
    children: list[str] = field(default_factory=list)


def validate_usage_attribution(spans: dict[str, Span]) -> int:
    """Enforce leaf-only gen_ai.usage accounting and return true turn cost.

    Invariant: a span carrying output_tokens must have no gen_ai.chat descendant.
    A turn span that copies a descendant's usage is a rollup and must be rejected.
    """
    parent_count: dict[str, int] = {}
    for s in spans.values():
        if s.parent_id is not None:
            parent_count[s.parent_id] = parent_count.get(s.parent_id, 0) + 1

    def has_chat_descendant(span_id: str) -> bool:
        stack = list(spans[span_id].children)
        while stack:
            child = spans[stack.pop()]
            if child.kind == "gen_ai.chat":
                return True
            stack.extend(child.children)
        return False

    total = 0
    for s in spans.values():
        if s.kind == "gen_ai.tool" and parent_count.get(s.span_id, 0) > 1:
            raise UsageAttributionError(
                f"tool span {s.span_id} has multiple parents; "
                "tool results consumed by two model calls must not share a span"
            )
        if s.output_tokens is None:
            continue
        if s.kind != "gen_ai.chat" and has_chat_descendant(s.span_id):
            raise UsageAttributionError(
                f"rollup span {s.span_id} ({s.kind}) carries output_tokens="
                f"{s.output_tokens} while having a gen_ai.chat descendant; "
                "this double-counts the child's usage in trace-level sums"
            )
        total += s.output_tokens
    return total


# trace from the incident: turn span copies chat #2's usage
trace = {
    "t": Span("t", None, "agent.turn", output_tokens=340, children=["c1", "c2"]),
    "c1": Span("c1", "t", "gen_ai.chat", output_tokens=210, children=["tool1"]),
    "tool1": Span("tool1", "c1", "gen_ai.tool"),
    "c2": Span("c2", "t", "gen_ai.chat", output_tokens=340, children=["tool2"]),
    "tool2": Span("tool2", "c2", "gen_ai.tool"),
}

try:
    validate_usage_attribution(trace)
except UsageAttributionError as e:
    # correct behavior: reject the trace rather than report 890 vs true 550
    print(f"rejected: {e}")
