# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-orphaned-tool-call-attribution-and-the-parent-token-double-count-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-orphaned-tool-call-attribution-and-the-parent-token-double-count-invariant.warrant.json
# Markdown SHA-256:   970f42f50c9e3f1352bfdd5b3dffae0278bc4a797af2100f37364b9dce0e5402
# Code AST SHA-256:   2766f155ce62c47ea5dc4fa133894b308981540578d28c896164b4578bd09e10
# Verified Classes:   UnclosedChildSpanError, AgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class UnclosedChildSpanError(RuntimeError):
    """Raised when an agent span attempts to seal final usage while a
    descendant tool-call span has not reached Span.end()."""
    pass


@dataclass
class AgentSpan:
    span_id: str
    trace_id: str
    own_input_tokens: int = 0
    own_output_tokens: int = 0
    attribution_complete: bool = False
    children: dict = field(default_factory=dict)  # span_id -> ended: bool
    ended: bool = False

    def register_child(self, child_id: str) -> None:
        self.children[child_id] = False

    def mark_child_ended(self, child_id: str) -> None:
        if child_id not in self.children:
            # child arrived after parent attempted close; must be late-bound
            self.children[child_id] = True
        else:
            self.children[child_id] = True

    def _children_all_ended(self) -> bool:
        return all(self.children.values())

    def end(self, step_budget_exhausted: bool) -> None:
        if self.ended:
            return
        if not self._children_all_ended():
            # Boundary condition: budget fired while a tool call is retrying.
            # Do NOT seal final usage. Mark incomplete; reconciler fills later.
            if step_budget_exhausted:
                self.attribution_complete = False
                self.ended = True
                self._emit_incomplete()
                return
            raise UnclosedChildSpanError(
                f"agent span {self.span_id} cannot seal: unresolved children "
                f"{[k for k, v in self.children.items() if not v]}"
            )
        self.attribution_complete = True
        self.ended = True
        self._emit_final()

    def _emit_final(self) -> None:
        # write gen_ai.usage.* as final; safe for rollup
        ...

    def _emit_incomplete(self) -> None:
        # write own usage only; set attribution_complete=false
        ...


def reconcile(span: AgentSpan, child_usage: dict) -> int:
    """Idempotent subtree reconciler keyed on (trace_id, span_id)."""
    if span.attribution_complete:
        # already final; re-adding children would double-count
        return span.own_input_tokens
    total = span.own_input_tokens + sum(child_usage.values())
    span.attribution_complete = True
    return total


def seal_agent_run(span: AgentSpan, step_budget_exhausted: bool) -> None:
    try:
        span.end(step_budget_exhausted=step_budget_exhausted)
    except UnclosedChildSpanError as e:
        # escalate: parent must wait for gather() of child futures
        raise UnclosedChildSpanError(
            f"refusing to seal trace {span.trace_id}: {e}"
        ) from e
