# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-a-coherent-span-tree-yet-lose-the-parent-child-linkage-between-an-agent-invocation-span-and-its-tool-call-child-spans-when-t.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-a-coherent-span-tree-yet-lose-the-parent-child-linkage-between-an-agent-invocation-span-and-its-tool-call-child-spans-when-t.warrant.json
# Markdown SHA-256:   85a618d718d2d0ebeab8ab3312637169c4d98ebc33f705644a2a2eda2a6bfef7
# Code AST SHA-256:   e8e28a3dbb0f62a2f3e062a544a9bc803161a1f6d018a0b868f56d26d2c04992
# Verified Classes:   OrphanedToolCallError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class OrphanedToolCallError(RuntimeError):
    """Raised when a gen_ai.tool.call span cannot be attributed to an invoking agent span."""
    pass

@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    operation: str  # e.g. "invoke_agent", "tool_call"

def validate_tool_call_parentage(span: Span, index: dict[str, Span]) -> None:
    if span.operation != "tool_call":
        return
    if span.parent_span_id is None:
        raise OrphanedToolCallError(
            f"tool_call span {span.span_id} in trace {span.trace_id} has no parent "
            f"(context lost at async boundary); cannot attribute token usage"
        )
    parent = index.get(span.parent_span_id)
    if parent is None:
        raise OrphanedToolCallError(
            f"tool_call span {span.span_id} references missing parent "
            f"{span.parent_span_id}; span tree is incomplete"
        )
    if parent.operation != "invoke_agent":
        raise OrphanedToolCallError(
            f"tool_call span {span.span_id} parented to {parent.operation} "
            f"({parent.span_id}), not an invoke_agent span; "
            f"re-parenting occurred across context re-entry"
        )

def audit_trace(spans: list[Span]) -> None:
    index = {s.span_id: s for s in spans}
    for s in spans:
        validate_tool_call_parentage(s, index)
