# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-across-a-retried-tool-call-and-the-usage-counters-double-count.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-across-a-retried-tool-call-and-the-usage-counters-double-count.warrant.json
# Markdown SHA-256:   8dedff71c1dad0d703c5f0ec2182739a0285c8d79c1f106a1a96a920926764cf
# Code AST SHA-256:   8bbba8fb12c11e4502916398cb263b8ac996eeb5cc868c69d41b8aa5f8f15d4f
# Verified Classes:   RetryTelemetryInvariantError, AttemptSpan, LogicalInvocation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RetryTelemetryInvariantError(RuntimeError):
    """Raised when a logical invocation's telemetry cannot be reconciled
    against its retry structure without ambiguity."""


@dataclass
class AttemptSpan:
    span_id: str
    operation_id: str          # stable across retries of one logical invocation
    retry_attempt: int         # 0-indexed; must be unique per operation_id
    input_tokens: int
    output_tokens: int
    finish_reason: str
    committed: bool = False


@dataclass
class LogicalInvocation:
    operation_id: str
    trace_id: str
    attempts: list[AttemptSpan] = field(default_factory=list)
    budget_ceiling_input_tokens: int = 5000

    def record_attempt(self, span: AttemptSpan) -> None:
        if span.operation_id != self.operation_id:
            raise RetryTelemetryInvariantError(
                f"attempt {span.span_id} belongs to operation "
                f"{span.operation_id}, not {self.operation_id}"
            )
        seen = {a.retry_attempt for a in self.attempts}
        if span.retry_attempt in seen:
            raise RetryTelemetryInvariantError(
                f"duplicate retry_attempt={span.retry_attempt} for "
                f"operation {self.operation_id}; retry discriminator is not "
                f"monotonic, trace-aggregated usage is now ambiguous"
            )
        self.attempts.append(span)

    def committed_attempt(self) -> Optional[AttemptSpan]:
        committed = [a for a in self.attempts if a.committed]
        if len(committed) > 1:
            raise RetryTelemetryInvariantError(
                f"operation {self.operation_id} has {len(committed)} committed "
                f"attempts; commit boundary is not exclusive"
            )
        return committed[0] if committed else None

    def billed_input_tokens(self) -> int:
        # Every attempt that reached the provider is billed, committed or not.
        return sum(a.input_tokens for a in self.attempts)

    def logical_input_tokens(self) -> int:
        # Only the committed attempt answers "how big was this decision?"
        c = self.committed_attempt()
        if c is None:
            raise RetryTelemetryInvariantError(
                f"operation {self.operation_id} has no committed attempt; "
                f"cannot compute logical cost"
            )
        return c.input_tokens

    def assert_budget_gate_safe(self) -> None:
        """Budget gates MUST read billed tokens for hard ceilings and
        logical tokens for context-window decisions. Reading the raw
        trace-aggregated sum is the failure mode this guards against."""
        billed = self.billed_input_tokens()
        logical = self.logical_input_tokens()
        if billed == logical:
            return  # no retries; aggregation is unambiguous
        # A consumer reading the trace-aggregated sum would see `billed`.
        # If the gate is configured against a ceiling calibrated for
        # logical cost, it will falsely trip.
        if billed > self.budget_ceiling_input_tokens >= logical:
            raise RetryTelemetryInvariantError(
                f"operation {self.operation_id}: billed={billed} exceeds "
                f"ceiling={self.budget_ceiling_input_tokens} but logical="
                f"{logical} does not; trace-aggregated budget gate would "
                f"falsely abort a committed invocation"
            )


def finalize_invocation(inv: LogicalInvocation) -> None:
    # Enforce the invariant at the commit boundary, before any effect is
    # acknowledged to the agent's episodic store.
    inv.assert_budget_gate_safe()
    c = inv.committed_attempt()
    if c is None:
        raise RetryTelemetryInvariantError(
            f"cannot finalize {inv.operation_id}: no attempt marked committed"
        )
    if c.finish_reason != "tool_calls":
        raise RetryTelemetryInvariantError(
            f"committed attempt {c.span_id} has finish_reason="
            f"{c.finish_reason!r}; tool effect must not be committed on a "
            f"non-tool-call finish"
        )
