# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-span-attributes-as-authoritative-for-token-accounting-when-a-tool-calling-agent-re-enter.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-opentelemetry-genai-span-attributes-as-authoritative-for-token-accounting-when-a-tool-calling-agent-re-enter.warrant.json
# Markdown SHA-256:   8fb6125540928aa66b23f91571a87455539d5e4664ef6027e26a67a303008bb2
# Code AST SHA-256:   13c15c2e96067a297e3b9acbfd1495400494ec93c652b0b60962a570f59cd746
# Verified Classes:   TokenLedgerDivergence, CheckpointedLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field

TOKENIZER_DRIFT_TOLERANCE = 0.02  # 2% between rehydrated count and first-span input_tokens


class TokenLedgerDivergence(RuntimeError):
    """Raised when span-derived token accounting cannot be trusted across a resume boundary."""
    pass


@dataclass
class CheckpointedLedger:
    resume_epoch: int = 0
    tokens_consumed: int = 0        # cumulative billed tokens, checkpoint-persisted
    context_tokens: int = 0         # size of serialized history at checkpoint time
    model_id: str = ""


def resume_and_validate(ledger: CheckpointedLedger, first_span: dict) -> CheckpointedLedger:
    """
    Called immediately after rehydration, before the agent loop continues.
    first_span is the GenAI span emitted by the first post-resume model call.
    """
    span_in = first_span.get("gen_ai.usage.input_tokens")
    span_model = first_span.get("gen_ai.request.model")

    if span_in is None:
        raise TokenLedgerDivergence(
            "Resume span missing gen_ai.usage.input_tokens; cannot validate rehydrated context."
        )

    # Invariant: the resumed call must re-send exactly the checkpointed history.
    drift = abs(span_in - ledger.context_tokens) / max(ledger.context_tokens, 1)
    if drift > TOKENIZER_DRIFT_TOLERANCE:
        raise TokenLedgerDivergence(
            f"Resume re-sent {span_in} input tokens but checkpoint held "
            f"{ledger.context_tokens} ({drift:.1%} drift). Ledger is non-additive; "
            f"span sums must not be used to increment tokens_consumed."
        )

    if span_model and ledger.model_id and span_model != ledger.model_id:
        raise TokenLedgerDivergence(
            f"Model identity changed across resume: {ledger.model_id!r} -> {span_model!r}. "
            f"Per-model cost weighting across this boundary is invalid."
        )

    # Do NOT add span_in to tokens_consumed. Advance the epoch; the first span is a
    # baseline, not an increment. Only subsequent same-epoch spans increment.
    ledger.resume_epoch += 1
    ledger.model_id = span_model or ledger.model_id
    return ledger


def account_span(ledger: CheckpointedLedger, span: dict, span_epoch: int) -> CheckpointedLedger:
    if span_epoch != ledger.resume_epoch:
        raise TokenLedgerDivergence(
            f"Span epoch {span_epoch} != ledger epoch {ledger.resume_epoch}; "
            f"refusing to fold cross-boundary span into additive ledger."
        )
    ledger.tokens_consumed += span["gen_ai.usage.input_tokens"] + span["gen_ai.usage.output_tokens"]
    ledger.context_tokens = span["gen_ai.usage.input_tokens"] + span["gen_ai.usage.output_tokens"]
    return ledger
