# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-tool-call-event-is-emitted-after-its-parent-agent-span-has-already.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-tool-call-event-is-emitted-after-its-parent-agent-span-has-already.warrant.json
# Markdown SHA-256:   c0ffcf18ab61542e4331eaeb8adc81cb4100571a7447f40f797a36002d7e498e
# Code AST SHA-256:   1f0be6a3f8b946fa54c9dace19eb23dbfa6ccb414aea41e2c6f7896d31e2dfbe
# Verified Classes:   TokenAttributionError, GenAISpan, ToolEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAttributionError(RuntimeError):
    """Raised when a tool-call event cannot be attributed to a live parent span."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    operation: str
    parent_span_id: Optional[str]
    input_tokens: int = 0
    output_tokens: int = 0
    closed: bool = False


@dataclass
class ToolEvent:
    span_id: str
    parent_span_id: str
    emitted_at_parent_closed: bool


def reconcile_trace(spans: list[GenAISpan], tool_events: list[ToolEvent]) -> dict:
    by_id = {s.span_id: s for s in spans}
    attributed = 0

    for ev in tool_events:
        parent = by_id.get(ev.parent_span_id)
        if parent is None:
            raise TokenAttributionError(
                f"tool event {ev.span_id} references unknown parent {ev.parent_span_id}"
            )
        if parent.closed or ev.emitted_at_parent_closed:
            raise TokenAttributionError(
                f"tool event {ev.span_id} emitted after parent {parent.span_id} "
                f"({parent.operation}) was closed; token attribution is unrecoverable"
            )
        # parent must remain open to accept the follow-up turn's input tokens
        attributed += parent.input_tokens

    total_input = sum(s.input_tokens for s in spans)
    residual = total_input - attributed
    if residual != 0:
        raise TokenAttributionError(
            f"token-attribution residual {residual} != 0; trace is incomplete, "
            f"not merely lossy — do not use for cost or replay"
        )
    return {"total_input_tokens": total_input, "attributed": attributed, "residual": residual}
