# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-token-accounting-diverges-from-the-model-s-own-usage-report.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-when-token-accounting-diverges-from-the-model-s-own-usage-report.warrant.json
# Markdown SHA-256:   d0f7f6521bab259c5490d87b4876529cfe56434b74a304cc3b960df122174b3c
# Code AST SHA-256:   c4a72f2d5109f9cfb0549f70bb56efaa4b02cde237c04bf45d27398fe757f41b
# Verified Classes:   TokenAccountingDivergence, AttemptSpan, InvocationSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional

class TokenAccountingDivergence(RuntimeError):
    """Raised when an invocation span's reconciled usage does not match the sum of its attempt spans."""
    pass

@dataclass
class AttemptSpan:
    attempt_id: str
    input_tokens: int = 0
    output_tokens: int = 0
    estimated: bool = False
    ended_clean: bool = False

@dataclass
class InvocationSpan:
    invocation_id: str
    attempts: list = field(default_factory=list)
    aborted_billed_tokens: int = 0

    def close_and_reconcile(self, provider_reported_total: Optional[int]) -> None:
        # Sum attempt truth, including estimated (aborted) usage.
        summed_input = sum(a.input_tokens for a in self.attempts)
        summed_output = sum(a.output_tokens for a in self.attempts)
        summed_total = summed_input + summed_output

        # Any attempt that ended without a terminal usage chunk contributes
        # estimated tokens that the provider may still bill. Those must be
        # carried into the invocation total, not dropped.
        estimated_total = sum(
            a.input_tokens + a.output_tokens for a in self.attempts if a.estimated
        )
        if estimated_total > 0 and provider_reported_total is None:
            # No provider reconciliation available: trust the estimate, but
            # mark the invocation so the governor applies a safety margin.
            self.reconciled_total = summed_total
            self.reconciled_estimated = True
        elif provider_reported_total is not None:
            # Provider reports total billed across all attempts. If our sum
            # diverges by more than the estimated portion, the instrumentation
            # is missing an attempt span and the governor cannot be trusted.
            if abs(provider_reported_total - summed_total) > estimated_total:
                raise TokenAccountingDivergence(
                    f"invocation {self.invocation_id}: span sum {summed_total} "
                    f"diverges from provider total {provider_reported_total} "
                    f"beyond estimated portion {estimated_total}"
                )
            self.reconciled_total = provider_reported_total
            self.reconciled_estimated = estimated_total > 0
        else:
            self.reconciled_total = summed_total
            self.reconciled_estimated = False

        if self.reconciled_estimated:
            # Governor must not treat an estimated total as authoritative
            # headroom; apply the documented safety margin before continuing.
            self.governor_headroom = max(0, self.reconciled_total - self.aborted_billed_tokens)
        else:
            self.governor_headroom = self.reconciled_total
