# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-streaming-tool-call-is-retried-mid-argument-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-a-streaming-tool-call-is-retried-mid-argument-emission.warrant.json
# Markdown SHA-256:   6db56746f3ea22c1e2c588934b97946a176ef28b0a2132d7d1ed31116c572e12
# Code AST SHA-256:   93e797d41590568e2cd4d3dc5fd0418e28f28bfb0f344b387313660c277594ed
# Verified Classes:   SpanReconciliationError, ToolAttempt, GenAISpanLedger
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class SpanReconciliationError(RuntimeError):
    """Raised when GenAI span attributes cannot be reconciled with provider call IDs."""
    pass


@dataclass
class ToolAttempt:
    call_id: str
    fragments: List[str] = field(default_factory=list)
    dispatch_started: bool = False
    closed: bool = False
    superseded_by: Optional[str] = None
    output_tokens: int = 0


class GenAISpanLedger:
    """Enforces: chat-span token total == sum of provider-call token totals,
    and tool spans are in bijection with provider call IDs."""

    def __init__(self) -> None:
        self.attempts: Dict[str, ToolAttempt] = {}
        self.chat_output_tokens: int = 0
        self._chat_closed = False

    def begin_attempt(self, call_id: str) -> ToolAttempt:
        if call_id in self.attempts and not self.attempts[call_id].closed:
            raise SpanReconciliationError(
                f"attempt {call_id!r} begun while prior attempt is still open"
            )
        self.attempts[call_id] = ToolAttempt(call_id=call_id)
        return self.attempts[call_id]

    def append_fragment(self, call_id: str, fragment: str) -> None:
        att = self.attempts.get(call_id)
        if att is None:
            raise SpanReconciliationError(f"fragment for unknown call_id {call_id!r}")
        if att.closed:
            raise SpanReconciliationError(
                f"fragment appended to closed attempt {call_id!r}; "
                f"superseded_by={att.superseded_by!r}"
            )
        if att.superseded_by is not None:
            raise SpanReconciliationError(
                f"fragment appended to superseded attempt {call_id!r} "
                f"(superseded_by={att.superseded_by!r}); fragments must be discarded, "
                f"not concatenated"
            )
        att.fragments.append(fragment)

    def mark_dispatch(self, call_id: str) -> None:
        self.attempts[call_id].dispatch_started = True

    def retry(self, old_call_id: str, new_call_id: str) -> ToolAttempt:
        old = self.attempts.get(old_call_id)
        if old is None or old.closed:
            raise SpanReconciliationError(
                f"retry references unknown or closed attempt {old_call_id!r}"
            )
        old.superseded_by = new_call_id
        old.closed = True
        if old.dispatch_started:
            # compensating invocation: both attempts' tokens count
            self.chat_output_tokens += old.output_tokens
        # else: discardable; old attempt's tokens do NOT count toward parent
        return self.begin_attempt(new_call_id)

    def record_tokens(self, call_id: str, output_tokens: int) -> None:
        att = self.attempts.get(call_id)
        if att is None:
            raise SpanReconciliationError(f"token record for unknown call_id {call_id!r}")
        att.output_tokens = output_tokens

    def close_chat(self, reported_output_tokens: int) -> None:
        if self._chat_closed:
            raise SpanReconciliationError("chat span closed twice")
        committed = sum(
            a.output_tokens for a in self.attempts.values() if a.closed or a.dispatch_started
        ) + self.chat_output_tokens
        if reported_output_tokens != committed:
            raise SpanReconciliationError(
                f"chat span gen_ai.usage.output_tokens={reported_output_tokens} "
                f"!= reconciled provider-call sum={committed}; "
                f"attempts={ {k: (a.output_tokens, a.superseded_by) for k, a in self.attempts.items()} }"
            )
        self._chat_closed = True
