# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-the-opentelemetry-genai-agent-span-silently-lose-tool-call-attribution-when-the-tool-invocation-outlives-the-enclosing-agent-s.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-the-opentelemetry-genai-agent-span-silently-lose-tool-call-attribution-when-the-tool-invocation-outlives-the-enclosing-agent-s.warrant.json
# Markdown SHA-256:   c2567992dec6f80bcb21052263a60e4c774c28744c07a9a760a0031570bf8128
# Code AST SHA-256:   b95064413c61b2203c1bbd120f55628fbcefbadadb6a92254f9d403782534a41
# Verified Classes:   AgentTelemetryInvariantError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AgentTelemetryInvariantError(RuntimeError):
    """Raised when an agent span's aggregate GenAI attributes disagree with its children."""
    pass


@dataclass
class SpanRecord:
    name: str
    operation: str                      # gen_ai.operation.name
    parent_id: Optional[str]
    span_id: str
    ended: bool = True
    attributes: dict = field(default_factory=dict)


def reconcile_agent_span(agent: SpanRecord, children: list[SpanRecord]) -> None:
    if agent.operation != "invoke_agent":
        return  # invariant only defined for agent spans

    tool_children = [c for c in children if c.operation == "execute_tool"]
    model_children = [
        c for c in children
        if c.operation in ("chat", "text_completion")
    ]

    declared_tools = agent.attributes.get("gen_ai.agent.tool_calls")
    if declared_tools is not None and declared_tools != len(tool_children):
        raise AgentTelemetryInvariantError(
            f"agent span {agent.span_id}: gen_ai.agent.tool_calls="
            f"{declared_tools} but {len(tool_children)} execute_tool children "
            f"present; agent span likely closed before async tool returned"
        )

    declared_in = agent.attributes.get("gen_ai.usage.input_tokens")
    declared_out = agent.attributes.get("gen_ai.usage.output_tokens")
    if declared_in is not None and declared_out is not None:
        child_in = sum(c.attributes.get("gen_ai.usage.input_tokens", 0) for c in model_children)
        child_out = sum(c.attributes.get("gen_ai.usage.output_tokens", 0) for c in model_children)
        if declared_in != child_in or declared_out != child_out:
            raise AgentTelemetryInvariantError(
                f"agent span {agent.span_id}: usage mismatch "
                f"(parent in/out={declared_in}/{declared_out}, "
                f"children sum in/out={child_in}/{child_out}); "
                f"a follow-up model call may be parented elsewhere"
            )

    for tool in tool_children:
        if tool.ended and not agent.ended:
            continue
        if tool.ended and agent.ended and tool.span_id not in agent.attributes.get(
            "_reconciled_children", []
        ):
            # child ended after parent: structurally legal, semantically suspect
            raise AgentTelemetryInvariantError(
                f"tool span {tool.span_id} ended after parent agent span "
                f"{agent.span_id}; aggregate attributes cannot include it"
            )
