# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-token-accounting-when-a-streaming-tool-call-span-is-closed-before-its-usage-delta-arrives.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-genai-semantic-convention-token-accounting-when-a-streaming-tool-call-span-is-closed-before-its-usage-delta-arrives.warrant.json
# Markdown SHA-256:   8a31eef6580407ed5434230f9f71af5bb0756ca23b68f9f130a6a5beaae0622b
# Code AST SHA-256:   1b5a313cb5e950cdb19d16b24a95c0f9be32cb90159855b23c993898deed56d7
# Verified Classes:   UsageReconciliationError, ModelSpanRecord, UsageReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class UsageReconciliationError(RuntimeError):
    """Raised when a late usage record cannot be bound to its model span."""
    pass

@dataclass
class ModelSpanRecord:
    span_id: str
    response_id: str
    finish_reason: Optional[str] = None
    output_tokens: Optional[int] = None
    usage_pending: bool = False
    closed: bool = False

class UsageReconciler:
    def __init__(self):
        self._open: dict[str, ModelSpanRecord] = {}

    def close_on_tool_ready(self, span_id: str, response_id: str) -> ModelSpanRecord:
        # Span ends at tool-call readiness, before the terminal usage chunk.
        rec = ModelSpanRecord(span_id=span_id, response_id=response_id,
                              finish_reason=None, output_tokens=None,
                              usage_pending=True, closed=True)
        self._open[response_id] = rec
        return rec

    def apply_usage_delta(self, response_id: str, output_tokens: int,
                          finish_reason: str) -> ModelSpanRecord:
        rec = self._open.get(response_id)
        if rec is None:
            raise UsageReconciliationError(
                f"orphan usage for response_id={response_id!r}: "
                f"no matching model span (trace flushed or wrong id)"
            )
        if not rec.usage_pending:
            raise UsageReconciliationError(
                f"double reconciliation for response_id={response_id!r}"
            )
        rec.output_tokens = output_tokens
        rec.finish_reason = finish_reason
        rec.usage_pending = False
        del self._open[response_id]
        return rec

    def sweep_gaps(self, timeout_ids: set[str]) -> list[str]:
        # Spans still pending past stream timeout are accounting gaps.
        return [rid for rid in timeout_ids if rid in self._open]
