# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-single-agent-step-emits-both-a-parent-execute-tool-span-and-a-child-provid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-a-single-agent-step-emits-both-a-parent-execute-tool-span-and-a-child-provid.warrant.json
# Markdown SHA-256:   1db1a5976d03d7546ed1486cf3dbfa5271d20520811fb9aa44db0e98fc26dbb5
# Code AST SHA-256:   0c0a63a99cba8003238713880a13e45fdc2d519f6f6e6429aa1edc30c999fbde
# Verified Classes:   TokenAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

INFERENCE_OPS = {"chat", "text_completion", "embeddings"}

class TokenAttributionError(RuntimeError):
    """Raised when a non-inference span carries gen_ai.usage.* attributes."""
    pass

@dataclass
class Span:
    name: str
    operation: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)

    def has_usage(self) -> bool:
        return any(k.startswith("gen_ai.usage.") for k in self.attributes)

    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(root: Span, strict: bool = True) -> tuple[int, int]:
    """Sum usage over leaf inference spans only; reject mis-attributed parents."""
    total_in = total_out = 0

    def walk(span: Span) -> None:
        nonlocal total_in, total_out
        if span.has_usage():
            if span.operation not in INFERENCE_OPS:
                if strict:
                    raise TokenAttributionError(
                        f"span '{span.name}' op='{span.operation}' carries "
                        f"gen_ai.usage.* but is not an inference span; "
                        f"tokens would be double-counted against its children"
                    )
                # non-strict: mark and ignore, defer to leaves
                span.attributes["gen_ai.usage.reconciliation"] = "reassigned"
            else:
                i, o = span.usage()
                total_in += i
                total_out += o
        for child in span.children:
            walk(child)

    walk(root)
    return total_in, total_out

def validate_step_span(span: Span) -> None:
    """Called at span close for execute_tool spans."""
    if span.operation == "execute_tool" and span.has_usage():
        raise TokenAttributionError(
            f"execute_tool '{span.attributes.get('gen_ai.tool.name')}' "
            f"must not carry gen_ai.usage.*; usage belongs to the deciding "
            f"chat span. Detected input={span.attributes.get('gen_ai.usage.input_tokens')}"
        )

# --- reproduction of the observed failure ---
chat = Span("chat", "chat", {
    "gen_ai.usage.input_tokens": 1840,
    "gen_ai.usage.output_tokens": 112,
})
tool = Span("execute_tool", "execute_tool", {
    "gen_ai.tool.name": "search_docs",
    "gen_ai.tool.call.id": "call_7f3a",
    "gen_ai.usage.input_tokens": 1840,   # poisoned: copied from chat
    "gen_ai.usage.output_tokens": 112,
}, children=[chat])

validate_step_span(tool)          # raises TokenAttributionError
# reconcile_trace(tool, strict=True) would also raise
