# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-until-child-tool-call-token-counts-are-reconciled-and-why-does-opentelemetry-s-gen-ai-usage.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-until-child-tool-call-token-counts-are-reconciled-and-why-does-opentelemetry-s-gen-ai-usage.warrant.json
# Markdown SHA-256:   eaf3f06bce66936adce510bd5485eb275090f52df41f7fbb2f08558b5480eb3d
# Code AST SHA-256:   fb9bf8f503989abdbb35950ad6d47e1fc2f800c858b50dbeaf91105bdff06caf
# Verified Classes:   UnreconciledSpanError, ChildSpan, AgentSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class UnreconciledSpanError(RuntimeError):
    """Raised when an agent span's token total cannot be reconciled against children."""
    pass


@dataclass
class ChildSpan:
    name: str
    input_tokens: int
    ended_at: Optional[float] = None
    is_retry: bool = False


@dataclass
class AgentSpan:
    name: str
    children: list = field(default_factory=list)
    retry_count: int = 0
    _token_attrs: Optional[dict] = None
    _committed_at: Optional[float] = None

    def add_child(self, child: ChildSpan) -> None:
        self.children.append(child)

    def snapshot_tokens(self, accumulator_input: int, accumulator_output: int) -> None:
        """Naive finalize: writes tokens immediately. This is the bug."""
        self._token_attrs = {
            "gen_ai.usage.input_tokens": accumulator_input,
            "gen_ai.usage.output_tokens": accumulator_output,
        }
        self._committed_at = time.time()

    def reconcile_and_commit(self, accumulator_input: int, accumulator_output: int,
                             barrier_timeout_s: float = 2.0) -> dict:
        """Correct finalize: refuses to commit until children are exported and retries matched."""
        deadline = time.time() + barrier_timeout_s

        # Barrier: all children must have ended.
        while any(c.ended_at is None for c in self.children):
            if time.time() > deadline:
                raise UnreconciledSpanError(
                    f"agent span {self.name!r}: child spans not exported before barrier timeout"
                )
            time.sleep(0.01)

        child_input = sum(c.input_tokens for c in self.children)
        distinct_children = [c for c in self.children if not c.is_retry]
        retry_children = [c for c in self.children if c.is_retry]

        # Retry reconciliation: retries must be individually spanned.
        if self.retry_count != len(retry_children):
            raise UnreconciledSpanError(
                f"agent span {self.name!r}: {self.retry_count} retries observed but "
                f"{len(retry_children)} retry spans emitted; retry tokens would be unattributable"
            )

        # Under-report guard: parent must not be cheaper than its children.
        if accumulator_input < child_input:
            raise UnreconciledSpanError(
                f"agent span {self.name!r}: parent input_tokens={accumulator_input} "
                f"< sum(children)={child_input}; under-report would defeat quota enforcement"
            )

        self._token_attrs = {
            "gen_ai.usage.input_tokens": accumulator_input,
            "gen_ai.usage.output_tokens": accumulator_output,
            "gen_ai.usage.reconciled": True,
            "gen_ai.usage.retry_spans": len(retry_children),
        }
        self._committed_at = time.time()
        return self._token_attrs


def finalize_agent_turn(span: AgentSpan, acc_in: int, acc_out: int) -> dict:
    try:
        return span.reconcile_and_commit(acc_in, acc_out)
    except UnreconciledSpanError:
        # Fail visible, not silent: unset tokens + marker is safer than wrong tokens.
        span._token_attrs = {
            "gen_ai.usage.reconciliation_failed": True,
            "gen_ai.usage.pending_children": sum(
                1 for c in span.children if c.ended_at is None
            ),
        }
        raise
