# What happens when an instance double-counts replayed tool calls in token accounting and silently inflates latency SLOs **Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit per-span token and tool-latency telemetry, where tool invocations may be retried, replayed from a checkpoint, or re-executed after a partial failure, and where those spans are aggregated into SLO dashboards. Does not apply to single-shot, non-retried inference calls with no checkpoint/resume semantics. ## Core Distinction There are two fundamentally different things an observability pipeline can count when it sees a tool span: the *logical operation* (one intended tool call in the agent's plan) and the *physical attempt* (one actual execution, which may be the 1st, 2nd, or 3rd try after a timeout or a checkpoint replay). Token accounting and latency SLOs are conventionally defined over *logical operations*, but the emitter almost always sees *physical attempts*. The boundary failure is that when an agent resumes from a mid-task checkpoint and replays a tool call that had already partially succeeded, the runtime emits a fresh span with fresh token counts and fresh wall-clock latency, and the aggregator — which has no idempotency key tying attempts to a logical operation — sums them. The result is a token total that exceeds the model's actual consumption and a p99 latency that reflects retry storms rather than user-perceived latency. This is not a generic "deduplicate your metrics" problem. The replay is *semantically necessary*: the agent genuinely re-invoked the tool because its in-memory state was lost at checkpoint. The physical work happened. The question is which layer owns the reconciliation, and the failure is that no layer does. ## What Was Observed An agent executing a 14-step plan with a checkpoint every 3 steps hit a context-window saturation event at step 9. The runtime's resume logic reloaded the last checkpoint (end of step 6) and re-executed steps 7, 8, and 9. Steps 7 and 8 each called a `search_documents` tool. The tool is idempotent in effect but not in emission: each invocation returned a full result set and logged `prompt_tokens=1840, completion_tokens=310` for the tool-calling turn, plus a `tool_latency_ms` of 2100 and 2400 respectively. On resume, the same two tool calls re-executed with `tool_latency_ms` of 2250 and 2600 (the backend was warmer but the retry payload was larger). The span emitter had no `logical_op_id`; it used a per-process monotonic counter for `span_id`. The aggregator summed all four tool spans. The observed deltas, comparing the dashboard against the model provider's billing export for the same window: - **Token total:** dashboard reported 8,940 tool-turn tokens; provider billed 5,120. The 3,820-token gap is exactly the sum of the two replayed tool turns (1840+310 + 1840+310 = 4300, minus a 480-token difference from prompt caching on the replay turns). The dashboard over-reported by ~75%. - **Tool latency p99:** the SLO was defined as "p99 `tool_latency_ms` < 3000ms over 5-minute windows." The retry spans (2250, 2600) sat below threshold individually, but because the aggregator counted 4 samples instead of 2, the p99 computation over a small sample set shifted the tail. During a separate incident where a single tool timed out at 6100ms and was retried successfully at 1800ms, the aggregator recorded both the 6100ms failure and the 1800ms success as valid latency samples, producing a p99 of 6100ms and paging on-call — even though the user-perceived latency for that logical operation was 7900ms (timeout + retry), which *also* breached SLO but for a different reason and required a different remediation. The critical observation: the two failure signals (token inflation and latency misattribution) came from the *same* replay event but pointed operators at *different* root causes. Token inflation looked like a model misbehaving; latency p99 breach looked like a slow backend. Neither was true. The actual cause was checkpoint replay without attempt reconciliation. ## Condition of Validity The invariant that must hold for SLOs to be meaningful is: > For any logical operation `op`, the aggregated `token_total(op) = sum over distinct physical attempts that produced billable tokens` and `latency(op) = wall_clock from first attempt start to last attempt end`, and `attempt_count(op)` is recorded separately. This invariant is *valid* only when the emitter attaches a stable `logical_op_id` that survives checkpoint serialization and resume. It is *violated* whenever: 1. The checkpoint serializes agent state but not the in-flight span context (trace ID, span ID, logical op ID), so resume generates a new trace root. 2. The tool-calling layer treats a retry as a new operation rather than a new attempt of the same operation. 3. The aggregator deduplicates on `span_id` (unique per attempt) rather than on `(logical_op_id, attempt_index)`. Condition (2) is the subtle one. A retry after a *transient* error (timeout, 429) is conventionally a new attempt of the same logical op. A replay after *checkpoint resume* is semantically identical but is almost never tagged as such, because the resume path is a different code path than the retry path, and the two were built by different teams. The invariant breaks at the seam between the retry subsystem and the checkpoint subsystem. ## Decision Boundary The decision an operator must make is: **do you reconcile at emit time or at aggregation time?** - **Emit-time reconciliation** requires the checkpoint to carry span context and the tool layer to accept an injected `logical_op_id`. This is correct but invasive: every checkpoint serializer and every tool wrapper must cooperate. It is the only option if you need per-operation latency (first-start to last-end) because that quantity cannot be reconstructed from independent attempt spans after the fact unless attempts carry ordering metadata. - **Aggregation-time reconciliation** requires attempts to carry `(logical_op_id, attempt_index, attempt_started_at, attempt_ended_at)` and the aggregator to group by `logical_op_id`. This is cheaper to retrofit but fails when the checkpoint does not preserve `logical_op_id` across resume — which is exactly the case that triggered the incident. The boundary is crossed when `attempt_index` is not monotonic across a resume boundary. If the resumed process restarts its attempt counter at 0, the aggregator sees two `attempt_index=0` spans for the same `logical_op_id` and either double-counts or, worse, deduplicates the *wrong* one (keeping the replayed span and discarding the original's token count, under-reporting). Token accounting has an additional wrinkle: replayed attempts may produce *fewer* billable tokens due to prompt caching, so naive deduplication that keeps "the first attempt" over-reports, while keeping "the last attempt" under-reports the original's uncached cost. The correct token total for a logical op is the sum over attempts of `billable_tokens`, not the token count of any single attempt. ## Operational Effect The practical consequence is that token dashboards and latency SLOs drift in *opposite directions* under replay pressure, and the drift is invisible because both metrics look plausible in isolation. Token totals creep up during any period of high checkpoint activity (long tasks, context saturation, aggressive checkpointing), which operators misread as "the model is getting more verbose" or "prompt caching stopped working." Latency p99 spikes during retry storms, which operators misread as backend degradation. The two signals never get correlated because they live on different dashboards owned by different teams. The guardrail is a single mandatory field on every tool span: `logical_op_id`, generated once at plan-compile time, serialized into every checkpoint, and re-injected on resume. Attempts are numbered with a resume-aware counter (carried in the checkpoint, not reset per process). The aggregator groups by `logical_op_id`, sums `billable_tokens` across attempts for token SLOs, and computes latency as `max(attempt_ended_at) - min(attempt_started_at)` for the user-perceived SLO, while separately tracking `attempt_count` and `failure_count` for reliability SLOs. Without the field, no downstream reconciliation is sound, because the information required to group attempts was destroyed at checkpoint time. ```python 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 ```