# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-mutates-its-own-token-accounting-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-tool-call-mutates-its-own-token-accounting-mid-execution.warrant.json
# Markdown SHA-256:   7afe3bab3ada8dc1565907f680a095f3b9bc02271b7849f86210b8c5be160f26
# Code AST SHA-256:   d96cc5cd2a15db6ca60300ed487a3f1a129823b83aedc9fbac9e70957c7ed2e0
# Verified Classes:   TornUsageAggregate, LlmChild, AgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import threading
from dataclasses import dataclass, field


class TornUsageAggregate(RuntimeError):
    """Raised when a parent agent span would publish partial token totals."""
    pass


@dataclass
class LlmChild:
    span_id: str
    input_tokens: int
    output_tokens: int
    finalized: bool = False


@dataclass
class AgentSpan:
    span_id: str
    children: list = field(default_factory=list)
    _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)

    def register_child(self, child: LlmChild) -> None:
        with self._lock:
            self.children.append(child)

    def finalize_child(self, span_id: str) -> None:
        with self._lock:
            for c in self.children:
                if c.span_id == span_id:
                    c.finalized = True
                    return
        raise TornUsageAggregate(f"unknown child span {span_id}")

    def end_and_aggregate(self) -> dict:
        with self._lock:
            open_children = [c for c in self.children if not c.finalized]
            if open_children:
                # Do NOT publish partial totals; the reducer will reconstruct.
                raise TornUsageAggregate(
                    f"parent {self.span_id} has {len(open_children)} unfinalized "
                    f"LLM children: {[c.span_id for c in open_children]}"
                )
            total_in = sum(c.input_tokens for c in self.children)
            total_out = sum(c.output_tokens for c in self.children)
            return {
                "gen_ai.usage.input_tokens": total_in,
                "gen_ai.usage.output_tokens": total_out,
                "gen_ai.agent.child_count": len(self.children),
            }


def safe_end(span: AgentSpan) -> dict:
    try:
        return span.end_and_aggregate()
    except TornUsageAggregate:
        # Fall back: emit parent without usage attrs; reducer sums by trace_id.
        return {"gen_ai.agent.child_count": len(span.children), "_usage_deferred": True}
