# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-silent-tool-span-orphan-when-a-genai-agent-aborts-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-silent-tool-span-orphan-when-a-genai-agent-aborts-mid-tool-call.warrant.json
# Markdown SHA-256:   c9bbadf5a47495711a6a7301c1c3cf1dcbc507f7f091e27528c4eadbe64fd7da
# Code AST SHA-256:   aed03af6e51e61b38848b97262e7648a7b18bc796d86dfbf5af551bcc7add298
# Verified Classes:   OrphanedToolSpanError, ToolCall, AgentSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class OrphanedToolSpanError(RuntimeError):
    """Raised when an agent span claims success but a referenced tool call
    has no terminated child execute_tool span."""
    pass


@dataclass
class ToolCall:
    call_id: str
    terminated: bool
    output_tokens: int


@dataclass
class AgentSpan:
    span_id: str
    status_ok: bool
    reported_output_tokens: int
    referenced_call_ids: list[str]
    children: dict[str, ToolCall]


def reconcile_agent_span(span: AgentSpan) -> int:
    """Return the true output-token total, or raise if the span is a phantom success."""
    missing = [
        cid for cid in span.referenced_call_ids
        if cid not in span.children or not span.children[cid].terminated
    ]
    if missing and span.status_ok:
        raise OrphanedToolSpanError(
            f"agent span {span.span_id} reports OK but tool calls {missing} "
            f"have no terminated child span; reported tokens "
            f"{span.reported_output_tokens} are not reconcilable"
        )
    return sum(c.output_tokens for c in span.children.values() if c.terminated)
