# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-streaming-tool-call-emits-usage-deltas-across-a-span-boundary-that.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-streaming-tool-call-emits-usage-deltas-across-a-span-boundary-that.warrant.json
# Markdown SHA-256:   35d02a76d6b8f65efcb19cdc86caedfd9f4f766a72cb3615a168e7ae4bb84136
# Code AST SHA-256:   10e3e21a049cdd76748c53f835f61c471167d808cafc667ab7c18219dd0c2d68
# Verified Classes:   UsageSpanBoundaryError, SpanRecord, GenAITraceGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

class UsageSpanBoundaryError(RuntimeError):
    """Raised when a span exports gen_ai.usage.output_tokens before the
    terminal usage chunk has been observed, or when the reconciling span
    closes before its descendants."""
    pass


@dataclass
class SpanRecord:
    name: str
    parent: str | None
    start: float
    end: float | None = None
    attrs: dict = field(default_factory=dict)
    children: list = field(default_factory=list)


class GenAITraceGuard:
    def __init__(self):
        self.spans: dict[str, SpanRecord] = {}
        self.terminal_usage_seen: bool = False
        self.reconciler_id: str | None = None

    def open(self, span_id: str, name: str, parent: str | None):
        self.spans[span_id] = SpanRecord(name, parent, time.monotonic())
        if parent and parent in self.spans:
            self.spans[parent].children.append(span_id)

    def mark_terminal_usage(self, reconciler_id: str):
        self.terminal_usage_seen = True
        self.reconciler_id = reconciler_id

    def close(self, span_id: str, attrs: dict | None = None):
        span = self.spans[span_id]
        span.end = time.monotonic()
        if attrs:
            span.attrs.update(attrs)

        carries_usage = "gen_ai.usage.output_tokens" in span.attrs
        if carries_usage and not self.terminal_usage_seen:
            raise UsageSpanBoundaryError(
                f"span {span_id} ({span.name}) exports output_tokens before "
                f"terminal usage chunk observed; value {span.attrs['gen_ai.usage.output_tokens']} "
                f"is a stale pre-terminal figure"
            )

        if carries_usage and span_id != self.reconciler_id:
            raise UsageSpanBoundaryError(
                f"span {span_id} ({span.name}) exports output_tokens but is not "
                f"the designated reconciler {self.reconciler_id}; double-count risk"
            )

        open_children = [c for c in span.children if self.spans[c].end is None]
        if open_children:
            raise UsageSpanBoundaryError(
                f"span {span_id} ({span.name}) closed with open children "
                f"{open_children}; child-before-parent invariant violated"
            )

    def reconcile(self) -> int:
        if not self.terminal_usage_seen:
            raise UsageSpanBoundaryError("cannot reconcile: no terminal usage chunk")
        rec = self.spans[self.reconciler_id]
        content = sum(
            self.spans[c].attrs.get("gen_ai.usage.content_tokens", 0)
            for c in rec.children
        )
        tool_args = sum(
            self.spans[c].attrs.get("gen_ai.usage.tool_argument_tokens", 0)
            for c in rec.children
        )
        billed = rec.attrs.get("gen_ai.usage.output_tokens", 0)
        if billed < content + tool_args:
            raise UsageSpanBoundaryError(
                f"reconciler billed={billed} < content={content}+args={tool_args}"
            )
        return billed
