# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-opentelemetry-genai-spans-double-count-retried-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-opentelemetry-genai-spans-double-count-retried-tool-calls.warrant.json
# Markdown SHA-256:   bf448c75c84c3c908ec2bcb1e5633fe294ba66a82bbd3171af30b0adf2a06564
# Code AST SHA-256:   d85d1af0b2e7da7a35fd86946b8e3f122948e18e004544033f0e6c075cf674c0
# Verified Classes:   TokenAccountingDriftError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class TokenAccountingDriftError(RuntimeError):
    """Raised when span-derived resident context diverges from the runtime's
    prompt-assembly record beyond tolerance, indicating retry/fallback
    double-counting or rebuild under-counting."""


@dataclass
class GenAISpan:
    span_id: str
    lineage_id: str
    model: str
    input_tokens: int
    output_tokens: int
    status: Literal["OK", "ERROR"]
    prompt_mode: Literal["initial", "superset", "rebuild"]


def reconcile_resident_context(
    spans: list[GenAISpan],
    runtime_resident_tokens: int,
    tolerance: int = 512,
) -> int:
    """Compute resident context from spans and assert it matches the runtime's
    own prompt-assembly counter. Returns the span-derived resident estimate."""
    if not spans:
        raise TokenAccountingDriftError("no spans to reconcile")

    by_lineage: dict[str, list[GenAISpan]] = {}
    for s in spans:
        by_lineage.setdefault(s.lineage_id, []).append(s)

    span_resident = 0
    for lineage, group in by_lineage.items():
        accepted = [s for s in group if s.status == "OK"]
        if not accepted:
            raise TokenAccountingDriftError(
                f"lineage {lineage} has no accepted attempt; cannot account"
            )
        last = accepted[-1]
        # Resident = accepted prompt + all appended completions in this lineage.
        # Prior ERROR attempts contribute 0 unless their output was appended.
        span_resident += last.input_tokens + sum(s.output_tokens for s in accepted)

        # Detect the superset-retry double-count trap explicitly.
        prior_inputs = sum(s.input_tokens for s in group if s is not last)
        if prior_inputs and last.prompt_mode == "superset" and prior_inputs >= last.input_tokens:
            raise TokenAccountingDriftError(
                f"lineage {lineage}: superset retry would double-count "
                f"{prior_inputs} tokens against accepted {last.input_tokens}"
            )

    drift = abs(span_resident - runtime_resident_tokens)
    if drift > tolerance:
        raise TokenAccountingDriftError(
            f"resident context drift {drift} tokens exceeds tolerance {tolerance}: "
            f"spans say {span_resident}, runtime says {runtime_resident_tokens}"
        )
    return span_resident
