# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-opentelemetry-genai-token-accounting-has-silently-desynchronized-from-its-own-context-window-state-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-opentelemetry-genai-token-accounting-has-silently-desynchronized-from-its-own-context-window-state-mid-execution.warrant.json
# Markdown SHA-256:   1066ee7e318b80cfe9f703b286a1a5af268933d139c1248c2c3669f4ba39a322
# Code AST SHA-256:   3d473037f2929b291270cd708baf5a311797f300095d3cba687b92ae61a175b8
# Verified Classes:   ContextAccountingDivergence, ContextTracker
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ContextAccountingDivergence(RuntimeError):
    """Raised when provider-reported input_tokens diverges from the locally
    predicted context occupancy beyond the step's legitimate bound."""
    pass


@dataclass
class ContextTracker:
    context_tokens: int          # locally tracked occupancy
    safety_floor: int            # must exceed largest possible tool result
    hard_ceiling: int            # provider's context limit

    def predict_next_input(self, rendered_delta_tokens: int) -> int:
        return self.context_tokens + rendered_delta_tokens

    def reconcile(
        self,
        predicted: int,
        observed_provider_input_tokens: int,
        max_step_tool_result_tokens: int,
        retry_was_opaque: bool,
    ) -> str:
        gap = observed_provider_input_tokens - predicted
        bound = max_step_tool_result_tokens

        if retry_was_opaque and gap > 0:
            # Cannot distinguish retry re-send from real growth; widen or bail.
            raise ContextAccountingDivergence(
                f"opaque retry: gap={gap} unattributable; invariant disabled"
            )

        if abs(gap) <= bound:
            self.context_tokens = observed_provider_input_tokens
            return "reconciled"

        corrected = observed_provider_input_tokens
        if corrected >= self.hard_ceiling:
            raise ContextAccountingDivergence(
                f"hard ceiling breached: observed={corrected} "
                f"ceiling={self.hard_ceiling} gap={gap}"
            )
        if corrected >= self.safety_floor:
            # Unattributable drift inside the danger band: checkpoint.
            self.context_tokens = corrected
            return "checkpoint_required"

        self.context_tokens = corrected
        return "reconciled"
