# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-opentelemetry-genai-span-accounting-mid-execution-the-gen-ai-usage-double-count-invariant-under-retried-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-opentelemetry-genai-span-accounting-mid-execution-the-gen-ai-usage-double-count-invariant-under-retried-tool-calls.warrant.json
# Markdown SHA-256:   7679ba934904f83107b0175c1ab2df60fab0c13af7ad852d61c1902c622331bc
# Code AST SHA-256:   8fc2dad2bad2e583b5cc7cda2ff2fa3d708192b969080e02629ce987789040fa
# Verified Classes:   GenAIAccountingDivergence, LogicalStepAccountant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAIAccountingDivergence(RuntimeError):
    """Raised when trace-level gen_ai.usage sums diverge from the agent's
    logical-step counter beyond the retry budget, indicating retry/fan-out
    inflation in the OpenTelemetry GenAI span pipeline."""
    pass


RETRY_BUDGET = 3  # max attempts per logical step; divergence factor bound


class LogicalStepAccountant:
    def __init__(self, retry_budget: int = RETRY_BUDGET):
        self.retry_budget = retry_budget
        self.logical_input_tokens = 0
        self.logical_output_tokens = 0
        self.last_attempt_input_tokens = 0

    def record_attempt(self, attempt: int, input_tokens: int, output_tokens: int) -> None:
        # Only the final successful attempt counts toward logical consumption.
        # Earlier attempts are transmission waste, not context occupancy.
        self.last_attempt_input_tokens = input_tokens
        if attempt == 0:
            self.logical_input_tokens += input_tokens
            self.logical_output_tokens += output_tokens

    def reconcile(self, trace_input_sum: int, trace_output_sum: int) -> None:
        """Compare trace-derived sums against logical counter. Raise if the
        trace pipeline has inflated past the retry budget, because any
        compaction or budget decision derived from it would be wrong."""
        if self.logical_input_tokens == 0:
            return
        ratio = trace_input_sum / self.logical_input_tokens
        if ratio > self.retry_budget:
            raise GenAIAccountingDivergence(
                f"trace gen_ai.usage.input_tokens sum={trace_input_sum} is "
                f"{ratio:.2f}x logical counter={self.logical_input_tokens}; "
                f"exceeds retry_budget={self.retry_budget}. Abandon trace-derived "
                f"accounting; fall back to internal counter for compaction gating."
            )
        out_ratio = (
            trace_output_sum / self.logical_output_tokens
            if self.logical_output_tokens
            else 1.0
        )
        if out_ratio > self.retry_budget:
            raise GenAIAccountingDivergence(
                f"trace gen_ai.usage.output_tokens sum={trace_output_sum} is "
                f"{out_ratio:.2f}x logical counter={self.logical_output_tokens}; "
                f"possible fan-out double-count (parent+child usage attributes)."
            )


def gate_compaction(accountant: LogicalStepAccountant, trace_input_sum: int,
                    trace_output_sum: int, window: int, threshold: float = 0.8) -> bool:
    try:
        accountant.reconcile(trace_input_sum, trace_output_sum)
    except GenAIAccountingDivergence:
        # Trace pipeline is desynchronized; gate on internal counter only.
        return accountant.logical_input_tokens > window * threshold
    # Trace is consistent; either source is valid, prefer internal for determinism.
    return accountant.logical_input_tokens > window * threshold
