# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-completed-agent-span-when-nested-tool-call-token-telemetry-violates-the-genai-semantic-convent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-completed-agent-span-when-nested-tool-call-token-telemetry-violates-the-genai-semantic-convent.warrant.json
# Markdown SHA-256:   81c94713ab6759e961f7c2d3a5150656663c3d30932ff19ccca824488886fac2
# Code AST SHA-256:   98d81340686c5f38369c3a8e16f70a27a221efc38cc27261589a6351ff486162
# Verified Classes:   UnreconciledUsageError, ChildUsage, AgentSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class UnreconciledUsageError(RuntimeError):
    """Raised when a parent span carrying gen_ai.usage.* cannot prove its
    aggregated counters equal the sum over its closed child set."""


@dataclass
class ChildUsage:
    logical_call_id: str
    input_tokens: int
    output_tokens: int
    arrived: bool = True


@dataclass
class AgentSpan:
    name: str
    declared_input_tokens: int = 0
    declared_output_tokens: int = 0
    expected_children: Set[str] = field(default_factory=set)
    observed_children: Dict[str, ChildUsage] = field(default_factory=dict)
    closed: bool = False

    def register_child(self, usage: ChildUsage) -> None:
        if self.closed:
            # Orphaned-close failure: a child arrived after the parent was
            # exported as complete. The parent's usage attributes are now
            # immutable and can never be reconciled.
            raise UnreconciledUsageError(
                f"child {usage.logical_call_id!r} arrived after parent "
                f"{self.name!r} was closed; parent usage is unreconcilable"
            )
        if usage.logical_call_id not in self.expected_children:
            # Unexpected child (e.g. duplicate retry span). Must be reconciled
            # by logical call id before it may contribute to the sum.
            raise UnreconciledUsageError(
                f"child {usage.logical_call_id!r} not in expected set "
                f"{sorted(self.expected_children)}; reconcile by logical call id"
            )
        self.observed_children[usage.logical_call_id] = usage

    def close(self) -> None:
        """Close the parent span, enforcing the parent-sum invariant."""
        missing = self.expected_children - set(self.observed_children)
        if missing:
            # Do not emit a clean sum over a partial child set. Either the
            # child is still in flight (do not close) or it is lost (close
            # with reconciled=false). Here we refuse the clean close.
            raise UnreconciledUsageError(
                f"parent {self.name!r} cannot close: children {sorted(missing)} "
                f"still in flight or lost; refusing to emit clean usage sum"
            )

        summed_input = sum(c.input_tokens for c in self.observed_children.values())
        summed_output = sum(c.output_tokens for c in self.observed_children.values())

        if (summed_input, summed_output) != (
            self.declared_input_tokens,
            self.declared_output_tokens,
        ):
            raise UnreconciledUsageError(
                f"parent {self.name!r} declared "
                f"(in={self.declared_input_tokens}, out={self.declared_output_tokens}) "
                f"but children sum to (in={summed_input}, out={summed_output})"
            )

        self.closed = True


def emit_agent_span(span: AgentSpan) -> AgentSpan:
    span.close()
    return span
