# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-drift-when-otel-genai-spans-decouple-from-the-model-s-own-usage-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-drift-when-otel-genai-spans-decouple-from-the-model-s-own-usage-ledger.warrant.json
# Markdown SHA-256:   dfb00a6de93973723bbb91b873768ba4892b24405a0269c769c3852bd94014bc
# Code AST SHA-256:   d589f22e0a01765c32a5a8e772f41ac5b66e8940fb21619dd96c1aaf558bda85
# Verified Classes:   DriftSignature, TokenAccountingDriftError, SpanUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class DriftSignature(Enum):
    TEMPLATE_OVERHEAD = "template_overhead"   # actual > reported, correlates with schema width
    STALE_SERIALIZATION = "stale_serialization"  # sign flips or actual < reported
    UNDECIDABLE = "undecidable"               # no independent count available


class TokenAccountingDriftError(RuntimeError):
    """Raised when a GenAI span's usage attributes cannot be reconciled
    with the independent usage ledger within tolerance."""

    def __init__(self, span_id: str, reported: int, actual: int,
                 signature: DriftSignature, epsilon: int):
        self.span_id = span_id
        self.reported = reported
        self.actual = actual
        self.residual = actual - reported
        self.signature = signature
        self.epsilon = epsilon
        super().__init__(
            f"span {span_id}: reported={reported} actual={actual} "
            f"residual={self.residual} signature={signature.value} eps={epsilon}"
        )


@dataclass
class SpanUsage:
    span_id: str
    input_tokens: int
    output_tokens: int
    estimated: bool = False

    @property
    def total(self) -> int:
        return self.input_tokens + self.output_tokens


def classify_residual(residual: int, schema_width: int, prior_residuals: list[int]) -> DriftSignature:
    if residual > 0 and schema_width > 0:
        return DriftSignature.TEMPLATE_OVERHEAD
    if residual < 0 or (prior_residuals and (residual > 0) != (prior_residuals[-1] > 0)):
        return DriftSignature.STALE_SERIALIZATION
    return DriftSignature.UNDECIDABLE


def reconcile_span(
    span: SpanUsage,
    ledger_actual: Optional[int],
    schema_width: int,
    prior_residuals: list[int],
    epsilon: int = 64,
) -> int:
    """Enforce per-span residual bounding. Returns the residual if within
    tolerance; raises TokenAccountingDriftError otherwise.

    Aggregate-only reconciliation is deliberately NOT performed here: a
    zero-sum trace with per-span drift is still rejected."""
    if span.estimated or ledger_actual is None:
        # Undecidable is a distinct state from measured-zero; never coalesce.
        raise TokenAccountingDriftError(
            span.span_id, span.total, -1,
            DriftSignature.UNDECIDABLE, epsilon,
        )

    residual = ledger_actual - span.total
    if abs(residual) > epsilon:
        signature = classify_residual(residual, schema_width, prior_residuals)
        raise TokenAccountingDriftError(
            span.span_id, span.total, ledger_actual, signature, epsilon,
        )
    return residual


def enforce_trace(span_usages: list[SpanUsage],
                  ledger_totals: list[Optional[int]],
                  schema_widths: list[int],
                  epsilon: int = 64) -> list[int]:
    residuals: list[int] = []
    for i, (span, actual) in enumerate(zip(span_usages, ledger_totals)):
        r = reconcile_span(span, actual, schema_widths[i], residuals, epsilon)
        residuals.append(r)
    # Aggregate check is advisory only; per-span already bounded.
    return residuals
