# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-agent-span-whose-tool-call-children-were-emitted-by-a-different-tracer-provider-than-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-agent-span-whose-tool-call-children-were-emitted-by-a-different-tracer-provider-than-th.warrant.json
# Markdown SHA-256:   b52d2634b5a99fe1ffc616396763827b20e7b1a83d7fc71ad97336d582ccfdf8
# Code AST SHA-256:   6cd7bd452ba44f7b241b828cda7daafbd1b15f0dd1aed88cff65e8cd2282c1c4
# Verified Classes:   UnreconciledToolChildrenError, ToolCallRecord, AgentSpanClosureBarrier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnreconciledToolChildrenError(RuntimeError):
    """Raised when an agent span is asked to end while tool-call children
    it dispatched have not produced a terminal observation."""


@dataclass
class ToolCallRecord:
    call_id: str
    dispatched_at: float
    terminal: bool = False
    usage_output_tokens: int = 0


@dataclass
class AgentSpanClosureBarrier:
    span_id: str
    deadline_s: float = 30.0
    children: Dict[str, ToolCallRecord] = field(default_factory=dict)
    accumulated_output_tokens: int = 0
    last_call_output_tokens: int = 0

    def dispatch_tool(self, call_id: str) -> None:
        self.children[call_id] = ToolCallRecord(
            call_id=call_id, dispatched_at=time.monotonic()
        )

    def observe_tool_completion(self, call_id: str, output_tokens: int) -> None:
        rec = self.children.get(call_id)
        if rec is None:
            raise UnreconciledToolChildrenError(
                f"completion for unknown tool call {call_id!r} on span {self.span_id!r}"
            )
        rec.terminal = True
        rec.usage_output_tokens = output_tokens
        self.accumulated_output_tokens += output_tokens

    def record_chat_usage(self, output_tokens: int) -> None:
        # Buffer on the agent span; do NOT rely on last-write-wins.
        self.accumulated_output_tokens += output_tokens
        self.last_call_output_tokens = output_tokens

    def end_span(self) -> dict:
        now = time.monotonic()
        pending = [c for c in self.children.values() if not c.terminal]
        if pending:
            expired = [c for c in pending if now - c.dispatched_at > self.deadline_s]
            if expired:
                # Cannot reconcile: end degraded, do not silently drop.
                return {
                    "otel.status_code": "ERROR",
                    "otel.status_description": "unreconciled_tool_children",
                    "gen_ai.tool.pending.count": len(pending),
                    "gen_ai.usage.output_tokens": self.accumulated_output_tokens,
                    "gen_ai.usage.output_tokens.lower_bound": True,
                }
            raise UnreconciledToolChildrenError(
                f"span {self.span_id!r} has {len(pending)} pending tool children "
                f"within deadline; cannot end"
            )
        return {
            "otel.status_code": "OK",
            "gen_ai.usage.output_tokens": self.accumulated_output_tokens,
        }
