# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-token-accounting-diverges-from-parent-trace-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-token-accounting-diverges-from-parent-trace-propagation.warrant.json
# Markdown SHA-256:   52aebf9b1c79088dcd4b2c568fb59d408e973fa737d60eb174a3edba6aea9eff
# Code AST SHA-256:   bd97e5b4ad8958142cb7818ac83d01337d15a60f9eecfe7483814fcfabdddf01
# Verified Classes:   TraceAccountingDivergence, GenAISpan, TraceReconciler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceAccountingDivergence(RuntimeError):
    """Raised when a GenAI span subtree cannot be reconciled with billed usage."""
    pass


@dataclass
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    input_tokens: int = 0
    output_tokens: int = 0
    usage_finalized_at: Optional[float] = None   # parent response receipt time
    context_captured_at: Optional[float] = None  # when traceparent was minted
    reconciled: bool = True


class TraceReconciler:
    def __init__(self) -> None:
        self._seen: dict[tuple[str, str], GenAISpan] = {}
        self._pending: list[GenAISpan] = []

    def admit(self, span: GenAISpan) -> None:
        key = (span.trace_id, span.span_id)
        if key in self._seen:
            # Identity gate: duplicate span_id (retry wrapper reuse).
            raise TraceAccountingDivergence(
                f"duplicate span_id {span.span_id} in trace {span.trace_id}; "
                f"retry wrappers must mint a fresh span_id"
            )
        # Freshness gate: child context captured before parent finalized usage.
        if span.parent_span_id is not None:
            parent = self._seen.get((span.trace_id, span.parent_span_id))
            if parent is not None and parent.usage_finalized_at is not None:
                if (span.context_captured_at is not None
                        and span.context_captured_at < parent.usage_finalized_at):
                    span.reconciled = False
                    self._pending.append(span)
                    self._seen[key] = span
                    return
        self._seen[key] = span

    def subtree_usage(self, trace_id: str, root_span_id: str) -> tuple[int, int]:
        """Return reconciled (input, output) tokens for the subtree.

        Raises if any unreconciled span would have been attributed to this root.
        """
        children: dict[str, list[GenAISpan]] = {}
        root: Optional[GenAISpan] = None
        for span in self._seen.values():
            if span.trace_id != trace_id:
                continue
            if span.span_id == root_span_id:
                root = span
            if span.parent_span_id is not None:
                children.setdefault(span.parent_span_id, []).append(span)
        if root is None:
            raise TraceAccountingDivergence(f"root span {root_span_id} not found")

        in_tok = out_tok = 0
        stack = [root]
        while stack:
            cur = stack.pop()
            if not cur.reconciled:
                raise TraceAccountingDivergence(
                    f"span {cur.span_id} has unreconciled usage; "
                    f"route to pending_reconciliation bucket, do not bill to {root_span_id}"
                )
            in_tok += cur.input_tokens
            out_tok += cur.output_tokens
            stack.extend(children.get(cur.span_id, []))
        return in_tok, out_tok
