# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-opentelemetry-genai-agent-span-silently-under-report-token-usage-when-a-tool-call-is-retried-after-a-partial-stream-flush.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-opentelemetry-genai-agent-span-silently-under-report-token-usage-when-a-tool-call-is-retried-after-a-partial-stream-flush.warrant.json
# Markdown SHA-256:   fada1267f93fc9bc29661cd740e7cd71cdd38f202ceafacce716785fab30981d
# Code AST SHA-256:   a1463dc5eda5bb8fc7a003c93793a43f061544ce5265b0e8679c953ce6eaa9c9
# Verified Classes:   TokenAccountingInvariantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TokenAccountingInvariantError(RuntimeError):
    """Raised when a span's accumulated GenAI usage diverges from the
    sum of its per-attempt usage deltas, indicating a retry-seam
    double-count or reset."""


def reconcile_span_usage(span_attrs: dict, attempt_deltas: list[int]) -> int:
    """Validate that the span's reported output tokens equal the sum of
    per-attempt deltas. Returns the authoritative total on success."""
    reported = int(span_attrs.get("gen_ai.usage.output_tokens", -1))
    if reported < 0:
        raise TokenAccountingInvariantError(
            "span missing gen_ai.usage.output_tokens attribute"
        )
    authoritative = sum(attempt_deltas)
    if reported != authoritative:
        raise TokenAccountingInvariantError(
            f"retry-seam accounting divergence: span reports {reported}, "
            f"attempt deltas sum to {authoritative} "
            f"(delta={reported - authoritative}); "
            f"likely accumulator reset or double-count across retry"
        )
    return authoritative
