# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-agent-spans-when-tool-call-children-outlive-their-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-agent-spans-when-tool-call-children-outlive-their-parent-span.warrant.json
# Markdown SHA-256:   6efc1fb26a9cb29fcb9d018ea9c3b00391310be7b5fb14c2dace0e3464744315
# Code AST SHA-256:   72384bb59afc902a0bb66d6408910a19a8dbf6d4f8789d28bad242eaea0b2d51
# Verified Classes:   LateToolChildError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

class LateToolChildError(RuntimeError):
    """Raised when a tool span closes after its enclosing agent span."""
    pass

@dataclass
class Span:
    name: str
    operation: str
    start_ns: int
    end_ns: int | None = None
    usage_input: int = 0
    usage_output: int = 0
    children: list["Span"] = field(default_factory=list)

    def close(self, now_ns: int) -> None:
        self.end_ns = now_ns

def validate_agent_span(agent: Span) -> None:
    if agent.operation != "invoke_agent":
        raise LateToolChildError(f"not an agent span: {agent.operation}")
    if agent.end_ns is None:
        raise LateToolChildError("agent span never closed; cannot validate")
    for child in agent.children:
        if child.end_ns is None:
            raise LateToolChildError(
                f"tool child {child.name!r} still open at agent close"
            )
        if child.end_ns > agent.end_ns:
            raise LateToolChildError(
                f"tool child {child.name!r} closed {child.end_ns - agent.end_ns}ns "
                f"after parent agent span; token roll-up would be unsound"
            )

def aggregate_usage(agent: Span) -> tuple[int, int]:
    validate_agent_span(agent)
    total_in = agent.usage_input
    total_out = agent.usage_output
    for child in agent.children:
        total_in += child.usage_input
        total_out += child.usage_output
    return total_in, total_out

# Correct pattern: await all dispatched tools before closing the agent span.
def run_agent_turn(dispatch_tools, now_ns=lambda: time.monotonic_ns()) -> Span:
    agent = Span("agent.turn", "invoke_agent", start_ns=now_ns())
    futures = dispatch_tools()
    for fut in futures:          # hold the parent open until every child resolves
        child = fut.result()
        child.close(now_ns())
        agent.children.append(child)
    agent.close(now_ns())
    aggregate_usage(agent)       # raises LateToolChildError if invariant broken
    return agent
