# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-is-retried-and-why-does-the-naive-span-per-attempt-convent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-is-retried-and-why-does-the-naive-span-per-attempt-convent.warrant.json
# Markdown SHA-256:   0e2b645738e06294920a4e456d02497c4c0d7225e524f716df0e6a433b14b0f7
# Code AST SHA-256:   a18e2eadb1d8ba2488d81bc5b0052a4871ff20d07da5a33f6aa212ef9c5f6f96
# Verified Classes:   GenAiUsageAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAiUsageAttributionError(RuntimeError):
    """Raised when a span subtree carries gen_ai.usage.* on both a parent
    and its children, making subtree cost ambiguous to any aggregator."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation_name: str
    tool_name: Optional[str] = None
    usage_input_tokens: Optional[int] = None
    usage_output_tokens: Optional[int] = None
    children: list["Span"] = field(default_factory=list)

    def carries_usage(self) -> bool:
        return (
            self.usage_input_tokens is not None
            or self.usage_output_tokens is not None
        )


def assert_usage_attribution(root: Span) -> None:
    """Enforce: within a subtree, usage lives on EITHER the root OR the
    leaves, never both. Called at span-close before export."""
    root_has_usage = root.carries_usage()
    leaf_has_usage = any(
        child.carries_usage() and not child.children
        for child in root.children
    )
    if root_has_usage and leaf_has_usage:
        raise GenAiUsageAttributionError(
            f"span {root.span_id} ({root.operation_name}) carries "
            f"gen_ai.usage.* AND has usage-bearing leaf children; "
            f"subtree cost is ambiguous. Emit usage on leaves only, "
            f"or on the aggregating root with leaf usage suppressed."
        )
    for child in root.children:
        assert_usage_attribution(child)


def close_tool_span(span: Span) -> Span:
    """Close a tool-call span, enforcing the attribution invariant."""
    if span.operation_name == "execute_tool" and span.carries_usage():
        # Aggregating parent: children must not also carry usage.
        for attempt in span.children:
            if attempt.carries_usage():
                raise GenAiUsageAttributionError(
                    f"aggregating parent {span.span_id} and attempt "
                    f"{attempt.span_id} both carry usage; "
                    f"double-count on subtree sum."
                )
    assert_usage_attribution(span)
    return span
