# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-tool-call-child-spans-before-emitting-a-completed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-against-tool-call-child-spans-before-emitting-a-completed.warrant.json
# Markdown SHA-256:   33e8df1982869652e3d27777b0e1b5068c230a9e544d921e10f198ac55dc54a5
# Code AST SHA-256:   0918454e4e9839ff5c7cc88c6243cc40916a626d1c44f7decc02988623753fc7
# Verified Classes:   TokenReconciliationError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenReconciliationError(RuntimeError):
    """Raised when an agent span's token aggregate cannot be reconciled
    against its turn-identified child spans under the GenAI conventions."""


@dataclass
class Span:
    kind: str                      # "agent" | "chat" | "execute_tool"
    turn_id: str | None = None     # required on chat and execute_tool spans
    tool_call_id: str | None = None
    input_tokens: int = 0
    output_tokens: int = 0
    status: str = "UNSET"          # "UNSET" | "OK" | "ERROR"
    children: list = field(default_factory=list)


def reconcile_agent_span(agent: Span) -> int:
    """Verify turn-identity join invariant and return post-dedup token total.

    Enforces: distinct turn ids over token-bearing (chat) spans == distinct
    turn ids over tool-call spans (allowing one final no-tool turn), and no
    turn id appears more than once among token-bearing spans.
    """
    chat_turns: dict[str, int] = {}
    tool_turns: set[str] = set()

    for child in agent.children:
        if child.turn_id is None:
            raise TokenReconciliationError(
                f"{child.kind} span missing turn_id; flat fan-out without "
                "turn identity is unsound under retry"
            )
        if child.kind == "chat":
            if child.status == "ERROR":
                # failed attempts are excluded from the aggregate, not summed
                continue
            if child.turn_id in chat_turns:
                raise TokenReconciliationError(
                    f"duplicate token-bearing span for turn {child.turn_id!r}: "
                    "retry was not deduplicated before aggregation"
                )
            chat_turns[child.turn_id] = child.input_tokens + child.output_tokens
        elif child.kind == "execute_tool":
            tool_turns.add(child.turn_id)

    orphan_tools = tool_turns - set(chat_turns)
    if orphan_tools:
        raise TokenReconciliationError(
            f"tool-call turns {sorted(orphan_tools)} have no matching "
            "token-bearing span; tool span and chat span identity keys diverged"
        )

    # all but at most one chat turn must have produced a tool call in a
    # tool-using loop; the final turn is the no-tool termination turn
    unexplained = set(chat_turns) - tool_turns
    if len(unexplained) > 1:
        raise TokenReconciliationError(
            f"multiple chat turns {sorted(unexplained)} without tool calls; "
            "either topology or turn identity is misconfigured"
        )

    return sum(chat_turns.values())


def finalize_agent_span(agent: Span) -> None:
    try:
        total = reconcile_agent_span(agent)
    except TokenReconciliationError:
        agent.status = "ERROR"
        raise
    agent.input_tokens = total
    agent.status = "OK"
