# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-when-a-tool-call-span-closes-before-its-parent-agent-span-and-how-do-you-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-when-a-tool-call-span-closes-before-its-parent-agent-span-and-how-do-you-bound-it.warrant.json
# Markdown SHA-256:   8a4be005ca437cafc4d974dea0896bb017e6e4cc6d29e5d60fe0fb1fcbf01a12
# Code AST SHA-256:   9daadefedcb8a1232eb36b04533e8d5eb50fa735ae8c74e048d2ba6eaba3cd2a
# Verified Classes:   UsageAttributionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class UsageAttributionError(RuntimeError):
    """Raised when GenAI usage attributes violate the span-tree accounting invariant."""

@dataclass
class Span:
    name: str
    parent_id: str | None
    operation: str | None = None          # gen_ai.operation.name
    usage_out: int | None = None          # gen_ai.usage.output_tokens
    closed: bool = False
    children: list["Span"] = field(default_factory=list)

def assert_usage_invariant(root: Span) -> None:
    """
    Enforce: (1) usage only on chat/embeddings spans, (2) parent total >= sum of descendants,
    (3) no usage written on a span whose descendants closed after it.
    """
    def walk(s: Span, ancestors_closed_early: bool) -> int:
        if s.usage_out is not None and s.operation not in (None, "chat", "embeddings"):
            raise UsageAttributionError(
                f"span {s.name!r} carries usage_out={s.usage_out} but "
                f"operation={s.operation!r}; usage must live on a chat/embeddings span"
            )
        if s.usage_out is not None and not s.closed:
            raise UsageAttributionError(
                f"span {s.name!r} has usage written before close; eager aggregation "
                f"cannot see late-closing descendants"
            )
        child_total = 0
        for c in s.children:
            child_total += walk(c, ancestors_closed_early or (s.closed and not c.closed))
        if s.usage_out is not None and s.usage_out < child_total:
            raise UsageAttributionError(
                f"span {s.name!r} usage_out={s.usage_out} < descendant sum={child_total}; "
                f"monotonicity violated (nested model call undercounted)"
            )
        return (s.usage_out or 0) + child_total

    walk(root, False)

def emit_agent_usage(agent: Span, deferred: bool) -> None:
    if not deferred:
        # Eager path: only legal if every descendant is already closed.
        if any(not d.closed for d in _descendants(agent)):
            raise UsageAttributionError(
                f"eager aggregation on {agent.name!r} while descendants still open; "
                f"switch to deferred processor or flatten nested model calls"
            )
    assert_usage_invariant(agent)

def _descendants(s: Span):
    for c in s.children:
        yield c
        yield from _descendants(c)
