# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-usage-metric-corruption-when-opentelemetry-genai-agent-spans-are-closed-out-of-causal-order.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-usage-metric-corruption-when-opentelemetry-genai-agent-spans-are-closed-out-of-causal-order.warrant.json
# Markdown SHA-256:   dbbccff2bd30705d67900bf1597b603a1f0e35e7796a99360e32560e4254251e
# Code AST SHA-256:   d89cca5c1a20b839e4635f987da86464e2de36fdd569c004683520c38ec590bb
# Verified Classes:   SpanClosureViolation, UsageAggregationError, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SpanClosureViolation(RuntimeError):
    """Raised when an agent span with subtree aggregation closes with outstanding children."""
    pass


class UsageAggregationError(RuntimeError):
    """Raised when subtree token aggregation is not well-defined due to causal ordering."""
    pass


@dataclass
class GenAISpan:
    name: str
    parent_id: Optional[str]
    aggregation: str = "self-only"  # or "subtree"
    input_tokens: int = 0
    output_tokens: int = 0
    start_time: float = field(default_factory=time.monotonic)
    end_time: Optional[float] = None
    _outstanding_children: int = 0
    _closed: bool = False

    def open_child(self) -> None:
        if self._closed:
            raise SpanClosureViolation(
                f"span {self.name!r} is closed; cannot open child under a finalized parent"
            )
        self._outstanding_children += 1

    def close_child(self) -> None:
        if self._outstanding_children <= 0:
            raise SpanClosureViolation(
                f"span {self.name!r} has no outstanding children to close"
            )
        self._outstanding_children -= 1

    def end(self) -> None:
        if self.aggregation == "subtree" and self._outstanding_children > 0:
            raise SpanClosureViolation(
                f"span {self.name!r} declares aggregation=subtree but has "
                f"{self._outstanding_children} outstanding child handle(s); "
                f"subtree token usage would be truncated at end()"
            )
        self.end_time = time.monotonic()
        self._closed = True


def aggregate_subtree_usage(
    parent: GenAISpan, children: Dict[str, GenAISpan]
) -> Dict[str, int]:
    if parent.aggregation != "subtree":
        return {
            "input_tokens": parent.input_tokens,
            "output_tokens": parent.output_tokens,
        }
    if parent.end_time is None:
        raise UsageAggregationError(
            f"parent {parent.name!r} not yet ended; cannot aggregate"
        )
    total_in = parent.input_tokens
    total_out = parent.output_tokens
    for child in children.values():
        if child.end_time is None:
            raise UsageAggregationError(
                f"child {child.name!r} has no end_time; aggregation undefined"
            )
        if child.end_time > parent.end_time:
            raise UsageAggregationError(
                f"causal ordering violated: child {child.name!r} ended at "
                f"{child.end_time:.3f} after parent {parent.name!r} at "
                f"{parent.end_time:.3f}; subtree usage is truncated by "
                f"{child.input_tokens + child.output_tokens} tokens"
            )
        total_in += child.input_tokens
        total_out += child.output_tokens
    return {"input_tokens": total_in, "output_tokens": total_out}
