# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-a-lossy-projection-of-agent-state-rather-than-a-faithful-record.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-a-lossy-projection-of-agent-state-rather-than-a-faithful-record.warrant.json
# Markdown SHA-256:   4ef104239b4ce768b25232e373f7d4f70c54e01da5efaf71225757a3e21ca815
# Code AST SHA-256:   46965f0e3da5c2fa2129de009e2dbfa2e9f451a67591f74cebd4f5d284762670
# Verified Classes:   TelemetryProjectionError, LogicalTurn, SpanRecord, Ledger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TelemetryProjectionError(RuntimeError):
    """Raised when a span-derived aggregate is used as a state record
    beyond the conditions under which the GenAI convention is exact."""


@dataclass
class LogicalTurn:
    turn_id: str
    billed_input_tokens: int
    billed_output_tokens: int
    retried: bool = False


@dataclass
class SpanRecord:
    turn_id: str
    span_id: str
    input_tokens: int
    output_tokens: int
    cached_input_tokens: Optional[int] = None


@dataclass
class Ledger:
    turns: dict = field(default_factory=dict)

    def record(self, t: LogicalTurn) -> None:
        # Ledger keys by logical turn; a retry replaces, never appends.
        self.turns[t.turn_id] = t

    def billed_input(self) -> int:
        return sum(t.billed_input_tokens for t in self.turns.values())


def reconcile(ledger: Ledger, spans: list, tolerance_ratio: float = 0.05) -> dict:
    """Spans are a reconciler, not a source of truth. Returns a divergence
    report; never raises on divergence alone, because the ledger governs."""
    span_sum = sum(s.input_tokens for s in spans)
    ledger_sum = ledger.billed_input()
    if ledger_sum == 0 and span_sum > 0:
        # Spans claim cost the ledger never recorded: a turn executed that
        # the agent did not commit. This IS a state-record failure.
        raise TelemetryProjectionError(
            f"spans report {span_sum} input tokens but ledger is empty; "
            "a turn executed outside the agent's commit path"
        )
    ratio = abs(span_sum - ledger_sum) / max(ledger_sum, 1)
    return {
        "span_sum": span_sum,
        "ledger_sum": ledger_sum,
        "ratio": ratio,
        "diverged": ratio > tolerance_ratio,
        "action": "log_and_continue" if ratio > tolerance_ratio else "none",
    }


def enforce_budget(ledger: Ledger, budget: int) -> None:
    """Budget enforcement reads ONLY the ledger. Spans cannot halt a task."""
    spent = ledger.billed_input()
    if spent > budget:
        raise TelemetryProjectionError(
            f"ledger-billed input {spent} exceeds budget {budget}; "
            "halt is ledger-authorized, not span-authorized"
        )
