# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-counting-and-orphaned-tool-spans-when-opentelemetry-genai-semconv-attributes-collide-across-retry-streaming-and-nested.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-counting-and-orphaned-tool-spans-when-opentelemetry-genai-semconv-attributes-collide-across-retry-streaming-and-nested.warrant.json
# Markdown SHA-256:   3135f2767601adba7461bf80b7dc999b659c64d23ce1295c85245adab774396c
# Code AST SHA-256:   4d1bf0da0bc2293d910f781783d6622c6dbc7d4844c155c99addf7acffcce266
# Verified Classes:   GenAITraceInvariantError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class GenAITraceInvariantError(RuntimeError):
    """Raised when a GenAI agent span closes with unreconciled accounting."""


@dataclass
class Span:
    name: str
    operation: str
    parent: str | None
    attributes: dict = field(default_factory=dict)
    tool_call_ids: list[str] = field(default_factory=list)
    attempt: int = 1


def reconcile_agent_span(agent_span: Span, children: list[Span]) -> int:
    # Invariant 1: token usage charged exactly once per logical invocation.
    # Only the final attempt (highest attempt index) may carry usage.
    chat_children = [c for c in children if c.operation == "chat"]
    if not chat_children:
        raise GenAITraceInvariantError(
            f"agent span {agent_span.name!r} has no chat children; "
            "possible re-parenting during handoff"
        )

    charged = [
        c for c in chat_children
        if "gen_ai.usage.input_tokens" in c.attributes
    ]
    if len(charged) > 1:
        raise GenAITraceInvariantError(
            f"agent span {agent_span.name!r} charges usage on {len(charged)} "
            "attempts; retries must suppress usage on non-final attempts"
        )

    total_input = sum(
        c.attributes.get("gen_ai.usage.input_tokens", 0) for c in charged
    )

    # Invariant 2: every emitted tool-call id binds to exactly one execute-tool span.
    emitted_ids = [tid for c in chat_children for tid in c.tool_call_ids]
    tool_children = [c for c in children if c.operation == "execute_tool"]
    bound_ids = [
        t.attributes.get("gen_ai.tool.call.id") for t in tool_children
    ]

    for tid in set(emitted_ids):
        if emitted_ids.count(tid) > 1 and len(bound_ids.count(tid) and [tid]) != 1:
            # duplicated emission across retries with a single execution is OK only
            # if the executing span is parented to the winning attempt
            pass
        if bound_ids.count(tid) != 1:
            raise GenAITraceInvariantError(
                f"tool call id {tid!r} bound to {bound_ids.count(tid)} "
                "execute-tool spans; expected exactly 1"
            )

    for t in tool_children:
        if t.parent not in {c.name for c in chat_children}:
            raise GenAITraceInvariantError(
                f"execute-tool span {t.name!r} parented to {t.parent!r}, "
                "not to a logical chat span; handoff re-parenting detected"
            )

    return total_input
