# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-attribute-token-cost-when-semantic-convention-spans-disagree-with-the-billing-meter.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-attribute-token-cost-when-semantic-convention-spans-disagree-with-the-billing-meter.warrant.json
# Markdown SHA-256:   abed2852a16f99c5a3d36224ef2e5a9e5aa3140c61d284cb50f54f8896166c2b
# Code AST SHA-256:   4b0e1f0ab28d4e195ba78355c06cb699491abefd1611f516ac9e5017127f7206
# Verified Classes:   AttributionInvariantError, SpanUsage, TaskCost
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a control decision would read unreconciled or incomplete token metrics."""
    pass


@dataclass
class SpanUsage:
    input_tokens: int
    output_tokens: int
    attempt_index: int = 0
    billing_dimension_complete: bool = False   # all billed dimensions mapped to attributes
    reasoning_tokens: Optional[int] = None     # None means provider billed but we didn't capture


@dataclass
class TaskCost:
    spans: list[SpanUsage] = field(default_factory=list)
    meter_tokens: Optional[int] = None        # authoritative, from provider meter
    drift_tolerance: float = 0.05

    def span_sum(self) -> int:
        # Sum of *all* attempts; deliberately not a partition of billed calls.
        return sum(s.input_tokens + s.output_tokens for s in self.spans)

    def reconciled(self) -> bool:
        return self.meter_tokens is not None

    def drift_ratio(self) -> float:
        if self.meter_tokens is None or self.meter_tokens == 0:
            raise AttributionInvariantError(
                "cannot compute drift without a reconciled meter value"
            )
        return (self.meter_tokens - self.span_sum()) / self.meter_tokens


def gate_budget(task: TaskCost, ceiling: int) -> bool:
    """Control-plane decision. Must never read raw span sums."""
    if not task.reconciled():
        raise AttributionInvariantError(
            "budget gate attempted on unreconciled span metrics; "
            "span tokens are a lower bound, not a cost basis"
        )
    if any(not s.billing_dimension_complete for s in task.spans):
        raise AttributionInvariantError(
            "span set has uncovered billing dimensions; cost attribution is provisional"
        )
    if abs(task.drift_ratio()) > task.drift_tolerance:
        raise AttributionInvariantError(
            f"span/meter drift {task.drift_ratio():.3f} exceeds tolerance "
            f"{task.drift_tolerance:.3f}; control decisions suspended"
        )
    return task.meter_tokens <= ceiling


# Trigger trace: retry loop with a dropped reasoning-token field.
task = TaskCost(
    spans=[
        SpanUsage(input_tokens=1842, output_tokens=210, billing_dimension_complete=True),
        SpanUsage(input_tokens=6900, output_tokens=88, attempt_index=1),
        SpanUsage(input_tokens=6900, output_tokens=88, attempt_index=2),
        SpanUsage(input_tokens=9120, output_tokens=640, reasoning_tokens=None),
    ],
    meter_tokens=24310,
)

try:
    gate_budget(task, ceiling=20000)
except AttributionInvariantError as err:
    # Correct behavior: refuse to throttle/unthrottle on an unreliable basis.
    print(f"control suspended: {err}")
