# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-replayed-tool-calls-in-token-accounting-and-silently-inflates-latency-slos.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-replayed-tool-calls-in-token-accounting-and-silently-inflates-latency-slos.warrant.json
# Markdown SHA-256:   007124e5dfd753e400531664310b3a1328e3bcdc3926eca53eaa83437205eafb
# Code AST SHA-256:   0470214b576003b0f1ed7b827ed01be92923c591cd78c75cd4aa15eeb28144c4
# Verified Classes:   ReplayAccountingError, ToolAttempt, LogicalOp
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ReplayAccountingError(RuntimeError):
    """Raised when a replayed tool attempt cannot be reconciled to a logical operation."""
    pass


@dataclass
class ToolAttempt:
    logical_op_id: str
    attempt_index: int
    started_at: float
    ended_at: float
    billable_tokens: int
    failed: bool = False


@dataclass
class LogicalOp:
    logical_op_id: str
    attempts: list = field(default_factory=list)

    def add_attempt(self, attempt: ToolAttempt) -> None:
        # Invariant: attempt_index must be strictly monotonic across resume boundaries.
        # A resumed process that resets its counter to 0 will violate this.
        if self.attempts:
            last_index = self.attempts[-1].attempt_index
            if attempt.attempt_index <= last_index:
                raise ReplayAccountingError(
                    f"non-monotonic attempt_index {attempt.attempt_index} "
                    f"after {last_index} for op {self.logical_op_id}; "
                    f"checkpoint resume likely reset the counter"
                )
        if attempt.logical_op_id != self.logical_op_id:
            raise ReplayAccountingError(
                f"attempt tagged {attempt.logical_op_id} added to op {self.logical_op_id}"
            )
        self.attempts.append(attempt)

    def token_total(self) -> int:
        # Sum across distinct attempts; replay may have different billable counts
        # due to prompt caching, so no single attempt is authoritative.
        return sum(a.billable_tokens for a in self.attempts)

    def user_perceived_latency_ms(self) -> float:
        if not self.attempts:
            raise ReplayAccountingError(f"no attempts recorded for op {self.logical_op_id}")
        first_start = min(a.started_at for a in self.attempts)
        last_end = max(a.ended_at for a in self.attempts)
        return (last_end - first_start) * 1000.0

    def attempt_count(self) -> int:
        return len(self.attempts)


def reconcile_resumed_op(op: LogicalOp, resumed_attempt: ToolAttempt) -> LogicalOp:
    """
    Called after checkpoint resume. The resumed process must carry forward the
    attempt counter; if it did not, we cannot safely merge and must fail closed
    rather than emit a double-counted span.
    """
    if resumed_attempt.attempt_index == 0 and op.attempts:
        raise ReplayAccountingError(
            f"resumed attempt for op {op.logical_op_id} reports index 0 but "
            f"{len(op.attempts)} attempts already exist; checkpoint did not "
            f"preserve attempt counter, refusing to emit ambiguous span"
        )
    op.add_attempt(resumed_attempt)
    return op
