# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-span-hierarchy-when-opentelemetry-genai-semantic-conventions-silently-drop-parent-child-links-across-an-agent-s-t.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-span-hierarchy-when-opentelemetry-genai-semantic-conventions-silently-drop-parent-child-links-across-an-agent-s-t.warrant.json
# Markdown SHA-256:   48a156a8caa3d8fa46427307f3cb6945770a338b468c05bc934faba4eee61a18
# Code AST SHA-256:   f3026e3f2c3c0fc28ae2464eec0569c4bb49bcf35e9ca373a76ea1d5e10de97b
# Verified Classes:   TraceTopologyError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TraceTopologyError(RuntimeError):
    """Raised when a tool span is not a descendant of the producing agent span,
    or when aggregate usage disagrees with the verified descendant tree."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    operation: str  # "invoke_agent" | "execute_tool" | "chat"
    attrs: dict = field(default_factory=dict)


def ancestors(span: Span, by_id: dict[str, Span]) -> list[str]:
    chain, cur = [], span.parent_id
    while cur is not None and cur in by_id:
        chain.append(cur)
        cur = by_id[cur].parent_id
    return chain


def verify_agent_tree(agent: Span, spans: list[Span],
                      dispatched_tool_calls: int) -> int:
    """Assert every execute_tool span descends from `agent`, and that the
    reachable tool-span count matches the dispatch ledger. Returns verified
    input-token total derived from the tree (not an independent tally)."""
    by_id = {s.span_id: s for s in spans}
    reachable_tools = [
        s for s in spans
        if s.operation == "execute_tool" and agent.span_id in ancestors(s, by_id)
    ]
    orphaned = [
        s for s in spans
        if s.operation == "execute_tool" and agent.span_id not in ancestors(s, by_id)
    ]
    if orphaned:
        raise TraceTopologyError(
            f"agent {agent.span_id}: {len(orphaned)} orphaned tool span(s) "
            f"{[s.span_id for s in orphaned]} not descended from agent; "
            f"usage aggregation would double-count"
        )
    if len(reachable_tools) != dispatched_tool_calls:
        raise TraceTopologyError(
            f"agent {agent.span_id}: reachable tool spans "
            f"{len(reachable_tools)} != dispatched {dispatched_tool_calls}; "
            f"dispatch ledger and trace tree diverged"
        )
    total = 0
    for s in spans:
        if s.operation == "chat" and agent.span_id in ancestors(s, by_id):
            total += s.attrs.get("gen_ai.usage.input_tokens", 0)
    return total


async def dispatch_tool(agent_ctx: Span, tool_name: str,
                        by_id: dict[str, Span], spans: list[Span],
                        make_span) -> None:
    # Context re-entry hazard: ambient context may have been reset here.
    tool = make_span(operation="execute_tool", parent=agent_ctx.span_id,
                     attrs={"gen_ai.tool.name": tool_name})
    if agent_ctx.span_id not in ancestors(tool, by_id):
        raise TraceTopologyError(
            f"tool span {tool.span_id} lost agent context across fan-out; "
            f"parent_id={tool.parent_id} expected chain through {agent_ctx.span_id}"
        )
    spans.append(tool)
