# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-genai-semantic-convention-spans-are-closed-out-of-order-across-nested-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-genai-semantic-convention-spans-are-closed-out-of-order-across-nested-tool-calls.warrant.json
# Markdown SHA-256:   10f379ff8aad6dbd5a7e3e000fb5cc05c7ac2fc74a5c033440e5082b99ff307f
# Code AST SHA-256:   2bf390c92afde99148a94c5f1db193f999ef254c56fcf23b4dee0944f5b8190a
# Verified Classes:   GenAiUsageAggregationError, GenAiSpan, UsageAggregator
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Optional


class GenAiUsageAggregationError(RuntimeError):
    """Raised when GenAI token accounting violates the single-regime invariant."""


@dataclass
class GenAiSpan:
    span_id: str
    parent_id: Optional[str]
    name: str
    input_tokens: int = 0
    output_tokens: int = 0
    ended: bool = False
    # True if this span copied a descendant's usage into its own attributes.
    propagated_child_usage: bool = False
    children: list[str] = field(default_factory=list)


class UsageAggregator:
    """Enforces exactly one aggregation regime: live-tree OR export-time, never both."""

    def __init__(self, regime: str) -> None:
        if regime not in ("live_tree", "export_time"):
            raise GenAiUsageAggregationError(f"unknown regime {regime!r}")
        self.regime = regime
        self.spans: Dict[str, GenAiSpan] = {}

    def open(self, span: GenAiSpan) -> None:
        self.spans[span.span_id] = span
        if span.parent_id and span.parent_id in self.spans:
            self.spans[span.parent_id].children.append(span.span_id)

    def end(self, span_id: str) -> None:
        span = self.spans[span_id]
        if self.regime == "live_tree":
            # Invariant: every descendant must already be ended.
            for child_id in span.children:
                child = self.spans[child_id]
                if not child.ended:
                    raise GenAiUsageAggregationError(
                        f"span {span_id} ({span.name}) ended before descendant "
                        f"{child_id} ({child.name}); live-tree rollup would drop "
                        f"{child.input_tokens} input / {child.output_tokens} output tokens"
                    )
            if span.propagated_child_usage:
                raise GenAiUsageAggregationError(
                    f"span {span_id} ({span.name}) propagates child usage under "
                    f"live_tree regime; rollup would double-count"
                )
        else:  # export_time
            if span.propagated_child_usage:
                raise GenAiUsageAggregationError(
                    f"span {span_id} ({span.name}) pre-propagates child usage under "
                    f"export_time regime; export-time walk would double-count"
                )
        span.ended = True

    def rollup(self, root_id: str) -> tuple[int, int]:
        if self.regime == "live_tree":
            raise GenAiUsageAggregationError(
                "live_tree regime must not call export-time rollup; totals are "
                "snapshotted at end()"
            )
        total_in = total_out = 0
        stack = [root_id]
        while stack:
            sid = stack.pop()
            s = self.spans[sid]
            if not s.ended:
                raise GenAiUsageAggregationError(
                    f"rollup over unfinished span {sid} ({s.name})"
                )
            total_in += s.input_tokens
            total_out += s.output_tokens
            stack.extend(s.children)
        return total_in, total_out


def reproduce_orphan_case() -> None:
    agg = UsageAggregator(regime="live_tree")
    agg.open(GenAiSpan("A1", None, "agent.run"))
    agg.open(GenAiSpan("B2", "A1", "tool.retriever"))
    agg.open(GenAiSpan("C3", "B2", "gen_ai.inference", input_tokens=3495, output_tokens=612))
    agg.end("B2")  # tool returns before its spawned inference finishes
    agg.end("C3")
    agg.end("A1")


if __name__ == "__main__":
    reproduce_orphan_case()
