# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-an-agent-turn-but-the-tool-call-events-are-recorded-on-a-child-span-that-outlives-th.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-an-agent-turn-but-the-tool-call-events-are-recorded-on-a-child-span-that-outlives-th.warrant.json
# Markdown SHA-256:   7e1e9779322047594cfacfc201a69dcdd7b7245a17dea65d17e1b7faddfb6519
# Code AST SHA-256:   3c7c3c1bac239243a8412e464270e3384cd1fdbd1d4da1be8c59bcb61eead3e4
# Verified Classes:   AccountingClosureViolation, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class AccountingClosureViolation(RuntimeError):
    """Raised when a trace's usage-bearing spans escape the turn's accounting boundary."""


@dataclass
class SpanRecord:
    span_id: str
    parent_span_id: str | None
    end_ns: int
    usage_tokens: int = 0  # >0 iff span carries gen_ai.usage.* attributes
    is_root: bool = False


def assert_accounting_closure(spans: list[SpanRecord]) -> int:
    """Verify the turn-root dominance invariant and return attributed token total.

    Invariant: every usage-bearing span in the trace subtree must end at or
    before its turn root's end timestamp. Violations are boundary escapes.
    """
    roots = [s for s in spans if s.is_root]
    if len(roots) != 1:
        raise AccountingClosureViolation(
            f"expected exactly one turn root, found {len(roots)}"
        )
    root = roots[0]

    # Build child adjacency to compute the subtree reachable from the root.
    children: dict[str, list[SpanRecord]] = {}
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.parent_span_id is not None:
            children.setdefault(s.parent_span_id, []).append(s)

    subtree: list[SpanRecord] = []
    stack = [root]
    while stack:
        cur = stack.pop()
        subtree.append(cur)
        stack.extend(children.get(cur.span_id, []))

    seen = {s.span_id for s in subtree}
    orphans = [s for s in spans if s.span_id not in seen]
    if orphans:
        raise AccountingClosureViolation(
            f"usage-bearing spans outside turn root subtree: "
            f"{[s.span_id for s in orphans if s.usage_tokens > 0]}"
        )

    escapes = [
        s for s in subtree
        if s.usage_tokens > 0 and s.end_ns > root.end_ns
    ]
    if escapes:
        raise AccountingClosureViolation(
            "accounting boundary escape: usage-bearing descendants end after "
            f"turn root {root.span_id} (root_end={root.end_ns}): "
            f"{[(s.span_id, s.end_ns, s.usage_tokens) for s in escapes]}"
        )

    return sum(s.usage_tokens for s in subtree)
