# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-token-metrics-from-silently-under-counting-agent-cost-across-provider-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-convention-token-metrics-from-silently-under-counting-agent-cost-across-provider-retries.warrant.json
# Markdown SHA-256:   7af6342b774a0eaa6a84c9bffa2b1964e4ed7b2a975cb0053e30038e28d3fd01
# Code AST SHA-256:   49184ec67d426b0c1a89753edb45ec79cfeedd2ec79de3555826f5d85e20a367
# Verified Classes:   TokenReconciliationError, PhysicalAttempt, LogicalStep
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenReconciliationError(RuntimeError):
    """Raised when logical-step token accounting diverges from summed physical attempts."""


@dataclass
class PhysicalAttempt:
    attempt_index: int
    input_tokens: int
    output_tokens: int
    finish_reason: str
    duration_ms: float


@dataclass
class LogicalStep:
    step_id: str
    model: str
    attempts: list[PhysicalAttempt] = field(default_factory=list)

    def record(self, attempt: PhysicalAttempt) -> None:
        self.attempts.append(attempt)

    def billable_input_tokens(self) -> int:
        # Every physical attempt is billed, including errored ones.
        return sum(a.input_tokens for a in self.attempts)

    def logical_duration_ms(self) -> float:
        return sum(a.duration_ms for a in self.attempts)

    def reconcile(self, reported_input_tokens: int, tolerance: int = 0) -> None:
        expected = self.billable_input_tokens()
        if abs(expected - reported_input_tokens) > tolerance:
            raise TokenReconciliationError(
                f"step={self.step_id} model={self.model} "
                f"attempts={len(self.attempts)} "
                f"expected_billed={expected} reported={reported_input_tokens} "
                f"drift={expected - reported_input_tokens}"
            )


def emit_step_metrics(step: LogicalStep, exporter_reported_tokens: int) -> dict:
    # Guardrail: enforce the additive invariant before any metric leaves the runtime.
    step.reconcile(exporter_reported_tokens)
    return {
        "gen_ai.request.model": step.model,
        "gen_ai.usage.input_tokens": step.billable_input_tokens(),
        "gen_ai.retry.attempt_count": len(step.attempts),
        "gen_ai.logical_step.duration_ms": step.logical_duration_ms(),
    }
