# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-gen-ai-usage-tokens-after-the-parent-agent-span-has-already-ended.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-gen-ai-usage-tokens-after-the-parent-agent-span-has-already-ended.warrant.json
# Markdown SHA-256:   b54caf12ec165ad1ef044ceffe18ad1a8898be4e41b1eb2b4bd7d9553316e379
# Code AST SHA-256:   907094754a969afefb25df60e3037cbcbd1e28b0ab0955c1d7851c5176b21491
# Verified Classes:   UsageAttributionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UsageAttributionError(RuntimeError):
    """Raised when token usage is summed in a way that cannot be reconciled
    against asynchronous delegated children."""


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    agent_name: str | None
    input_tokens: int
    output_tokens: int
    ended: bool = True
    children: list["Span"] = field(default_factory=list)


def sum_subtree_usage(root: Span) -> tuple[int, int]:
    """Correct accounting: sum usage over the subtree rooted at an agent span.

    A flat sum over all spans double-counts nothing but undercounts the parent
    when delegated children report usage after the parent ended. The subtree
    sum is the only reading valid under asynchronous delegation.
    """
    total_in = root.input_tokens
    total_out = root.output_tokens
    for child in root.children:
        ci, co = sum_subtree_usage(child)
        total_in += ci
        total_out += co
    return total_in, total_out


def enforce_closed_sum(agent_span: Span, subtree_sum: tuple[int, int]) -> None:
    """Refuse to treat an agent span's own usage as a closed sum when its
    subtree contains token-consuming descendants that outlived the parent.

    The GenAI conventions do not define a completeness attribute, so a
    consumer that reads gen_ai.usage.* off a single span is making an
    unstated assumption. This guard makes the assumption explicit and fails
    loudly when it is violated.
    """
    own = (agent_span.input_tokens, agent_span.output_tokens)
    if subtree_sum != own:
        raise UsageAttributionError(
            f"agent span {agent_span.span_id} ({agent_span.agent_name}) reports "
            f"own usage {own} but subtree usage {subtree_sum}; the span's "
            f"gen_ai.usage.* attributes are a lower bound, not a closed sum. "
            f"Sum over the subtree rooted at the agent span, or emit a "
            f"namespaced reconciled flag — do not read the span attribute as "
            f"the turn's total."
        )


def attribute_turn(agent_span: Span) -> tuple[int, int]:
    subtree = sum_subtree_usage(agent_span)
    enforce_closed_sum(agent_span, subtree)
    return subtree
