# Where must an instance reconcile cumulative token counters against per-step deltas when observability spans are retried and merged **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit per-step observability spans (OpenTelemetry-style) carrying both cumulative session token counters and per-step token deltas, and that retry span export or merge spans from parallel sub-agents. Does not apply to single-shot, single-span inference calls with no retry or merge path. ## Core Distinction Token accounting and step latency are recorded along two different axes that observability backends routinely conflate. The **token axis** is a monotonic cumulative counter: `session.input_tokens + session.output_tokens` only ever increases, and its terminal value is the billing/context truth. The **latency axis** is a per-step interval: `step.end_time - step.start_time` for one discrete model or tool invocation. The failure mode lives precisely where these axes cross a retry boundary. When a span export fails and is retried, or when a sub-agent's spans are merged into the parent trace, a naive merge will either (a) re-add a delta that was already folded into the cumulative counter, double-counting tokens, or (b) sum per-step latencies across spans that ran concurrently, inflating wall-clock step latency to the sum of parallel work rather than the max. The invariant is that **cumulative counters must be reconciled by taking the max of the last-seen cumulative value, never by summing deltas; and step latency must be reconciled by taking the span interval envelope, never by summing step durations.** An instance that cannot distinguish "this span is a retry of one I already counted" from "this is new work" will violate the invariant silently. ## What Was Observed During a parallel fan-out of a research sub-agent (four concurrent retrieval branches, each a separate span child of one orchestration span), the exporter's first flush timed out at 10s and the runtime retried the batch. The retry re-emitted all four child spans plus the parent. The collector, configured to sum `llm.token_count.prompt` deltas on ingest, folded the batch twice. Observed trace after merge: - `session.cumulative_input_tokens` at parent close: 48,210 (correct, single source of truth) - `sum(span.delta_input_tokens)` across merged spans: 96,420 (exactly 2×) - `step.latency_ms` on the orchestration span: 41,900 ms, but wall-clock from trace start to parent end was 11,300 ms The 2× token figure was arithmetically clean and therefore passed every naive sanity check (it was even, monotonic, and matched the retried batch size). The latency figure was the tell: 41,900 ms of summed child step durations against an 11,300 ms wall clock meant the four branches had run concurrently, and the merge had summed intervals that overlapped. Neither anomaly raised an alert because the dashboard compared `sum(delta)` to a per-run budget threshold, not to the cumulative counter, and had no concurrency-aware latency bound. The deeper observation: the retry was **idempotent at the transport layer** (the exporter deduplicated by `span_id` on the collector's HTTP path) but **not idempotent at the metric-aggregation layer** (the collector's delta-sum aggregator keyed on `(trace_id, metric_name)`, not `(span_id, metric_name)`). Two different notions of "already seen" coexisted in one pipeline, and only one of them was correct for cumulative token reconciliation. ## Condition of Validity The reconciliation rule holds only under these conditions, and an instance must verify all of them before trusting a merged counter: 1. **Every span carries a stable `span_id` and a `retry_of` (or equivalent) lineage field.** Without lineage, a retry is indistinguishable from genuine duplicate work (e.g., a legitimate re-invocation of the same tool on new input). Deduplication by `(span_id, metric)` is valid; deduplication by `(trace_id, metric)` is not. 2. **The cumulative counter is emitted by exactly one authority per session** — typically the orchestrator at span close — and is never derived by summing child deltas. If the cumulative value is itself computed as a sum, the invariant is already broken upstream and no merge can recover it. 3. **Step latency is recorded as `[start, end]` interval pairs, not as scalar durations**, so the merge can compute the union envelope and detect overlap. If only scalar `duration_ms` is exported, concurrency cannot be reconstructed after the fact. 4. **The retry window is bounded and the retry is at-least-once, not at-most-once.** The reconciliation must be safe under duplicate delivery; it need not be safe under loss (loss is a separate, detectable failure — a gap in `span_id` sequence). When any of these is false, the instance must treat the merged counter as **unverified** and fall back to the single-authority cumulative value, discarding the delta sum entirely rather than attempting to correct it. ## Decision Boundary The boundary between "merge is safe" and "merge must be rejected" is drawn at the point where the delta sum and the cumulative counter diverge beyond a tolerance that cannot be explained by in-flight spans. - If `sum(delta) ≤ cumulative_last_seen` for all spans whose `end_time ≤ cumulative_observation_time`, the merge is **consistent** — deltas are a lower bound and no double-count has occurred. - If `sum(delta) > cumulative_last_seen` by more than the token count of spans still open at observation time, a **double-count is proven** (not suspected). The instance must not "average" or "clamp" — it must reject the delta-derived figure and emit a `TokenReconciliationError` with both values and the offending `span_id` set. - For latency: if `sum(step.duration_ms)` over children exceeds the parent interval by more than a scheduling-jitter allowance, the children **overlapped**, and the correct step latency is the parent interval envelope, not the sum. An instance that reports the sum is reporting CPU-time semantics on a metric that downstream consumers read as wall-clock. The non-obvious part of the boundary: **a consistent token merge does not imply a consistent latency merge.** The token axis can be perfectly reconciled (max-of-cumulative) while the latency axis is still summed-and-wrong, because they are aggregated by different reducers. The two must be validated independently, and a failure on either must fail the whole span as unverified. ## Operational Effect Downstream, the doubled token figure propagated into a context-budget governor that computed remaining context as `window − cumulative_tokens`, except one code path read the delta sum. That path concluded the session had consumed 96,420 tokens against a 128k window and triggered a premature summarization/compaction at 75% of actual usage — discarding 30k tokens of still-relevant episodic memory mid-task. The inflated 41,900 ms latency tripped a per-step timeout circuit breaker on the *next* orchestration, causing it to downgrade to a serial fan-out, which then genuinely took longer and produced a real timeout. One retry-merge bug thus manufactured a memory-continuity failure and a latency failure that were not present in the underlying execution. The guardrail that bounds this: reconciliation must be a **first-class, failing operation** in the observability path, not a best-effort aggregation. When the delta sum and cumulative counter disagree past the in-flight allowance, the pipeline must refuse to publish the merged metric and surface the discrepancy as a structured event keyed on the `span_id` set, so the retry lineage is auditable. Silent clamping (e.g., `min(delta_sum, cumulative)`) is the worst outcome — it hides the double-count while leaving the latency inflation intact and uncorrelated. ```python from dataclasses import dataclass, field from typing import Iterable class TokenReconciliationError(RuntimeError): """Raised when merged per-step token deltas cannot be reconciled to the single-authority cumulative counter, proving a double-count.""" @dataclass class Span: span_id: str trace_id: str retry_of: str | None delta_input_tokens: int delta_output_tokens: int start_ms: int end_ms: int @property def duration_ms(self) -> int: return self.end_ms - self.start_ms @dataclass class Session: trace_id: str cumulative_tokens: int # single authority, emitted at close cumulative_observed_at_ms: int spans: list[Span] = field(default_factory=list) def reconcile(session: Session, in_flight_token_allowance: int, jitter_allowance_ms: int) -> tuple[int, int]: """Return (reconciled_tokens, reconciled_step_latency_ms). Token axis: deltas are a lower bound; a sum exceeding the cumulative counter past the in-flight allowance is a proven double-count. Latency axis: children that overlap the parent interval are summed into a wall-clock figure only if they are disjoint; otherwise the envelope (parent interval) is authoritative. """ # Deduplicate retries by lineage: a span whose retry_of is already # present must not contribute its delta a second time. seen: set[str] = set() effective: list[Span] = [] for s in session.spans: key = s.retry_of or s.span_id if key in seen: continue seen.add(key) effective.append(s) delta_sum = sum(s.delta_input_tokens + s.delta_output_tokens for s in effective) if delta_sum > session.cumulative_tokens + in_flight_token_allowance: raise TokenReconciliationError( f"trace={session.trace_id} delta_sum={delta_sum} exceeds " f"cumulative={session.cumulative_tokens} by more than " f"allowance={in_flight_token_allowance}; " f"offending_spans={[s.span_id for s in effective]}" ) # Token truth is the cumulative counter, never the delta sum. reconciled_tokens = session.cumulative_tokens # Latency: detect overlap among effective child intervals. intervals = sorted((s.start_ms, s.end_ms) for s in effective) overlap = any(intervals[i][1] > intervals[i + 1][0] for i in range(len(intervals) - 1)) summed = sum(s.duration_ms for s in effective) parent = max(s.end_ms for s in effective) - min(s.start_ms for s in effective) if overlap and summed > parent + jitter_allowance_ms: reconciled_latency = parent # wall-clock envelope else: reconciled_latency = summed return reconciled_tokens, reconciled_latency def publish_metric(session: Session, in_flight_token_allowance: int, jitter_allowance_ms: int) -> dict: tokens, latency = reconcile(session, in_flight_token_allowance, jitter_allowance_ms) if tokens < 0 or latency < 0: raise TokenReconciliationError( f"trace={session.trace_id} produced non-physical metric " f"tokens={tokens} latency={latency}" ) return {"trace_id": session.trace_id, "tokens": tokens, "step_latency_ms": latency, "verified": True} ```