# Why does an instance's cost attribution silently collapse when a retried tool call is re-tagged under a new span ID **Date of Record:** 2026 November 21 **Scope:** Applies to observability pipelines that derive per-agent, per-tool, and per-step cost and latency attribution from span trees emitted by LLM agent runtimes, specifically when tool-call retries or mid-execution checkpoint resumes generate fresh span IDs for logically identical work. Does not apply to pipelines that key attribution on a stable, runtime-supplied idempotency token rather than on span lineage. ## Core Distinction The failure is not "missing telemetry" and it is not "duplicate spans." It is a **lineage break in the retry chain** that causes the same logical unit of work to be counted as two independent units while simultaneously severing the parent link that would have let the aggregator deduplicate them. Most observability pipelines assume a span tree is a forest of *causal* edges: a child span's `parent_span_id` points at the span that caused it. Agent runtimes violate this assumption on retry. When a tool call times out and the orchestrator re-issues it, the runtime typically emits a *new* tool span with a fresh `span_id` and — critically — a `parent_span_id` that points at the *orchestrator step*, not at the failed attempt. The failed attempt's span is left as an orphan or is closed with status `ERROR` but retains no forward pointer to its successor. The aggregator, walking parent edges, sees two sibling tool spans under one step: one `ERROR`, one `OK`. It has no mechanical way to know they are the same logical call. The distinction that matters: **deduplication by span identity is not the same as deduplication by work identity.** A pipeline that keys on `span_id` will double-count. A pipeline that keys on `(step_id, tool_name, normalized_args_hash)` will deduplicate correctly — but only if the runtime emits `step_id` stably across the retry, which is exactly the field most runtimes regenerate. ## What Was Observed A single agent task — "summarize the three attached PDFs and post the result to Slack" — executed through a runtime that retried the `pdf_extract` tool twice on timeout (30s SLO, tool p99 ≈ 34s) before succeeding on the third attempt. The emitted span tree, as received by the collector: ``` step_span step_id=s7f2 span_id=A1 parent=ROOT tool_span span_id=B1 parent=A1 tool=pdf_extract status=ERROR dur=30012ms tool_span span_id=B2 parent=A1 tool=pdf_extract status=ERROR dur=30008ms tool_span span_id=B3 parent=A1 tool=pdf_extract status=OK dur=1180ms tool_span span_id=B4 parent=A1 tool=slack_post status=OK dur=240ms ``` Three concrete downstream effects were measured in the attribution store: 1. **Cost triple-counted.** The billing join summed token cost across all `tool=pdf_extract` spans under `A1`. Two of those spans carried zero tokens (they timed out before the model sub-call), but the runtime's token accounting attached the *retry's* prompt tokens to each attempt's span because the retry re-sent the full prompt. Net effect: 3× the true extraction cost attributed to step `s7f2`. 2. **Latency SLO corrupted in the optimistic direction.** The SLO calculator computed tool p95 over *completed* spans only, filtering `status=ERROR`. The two 30s timeouts were excluded, leaving `B3` at 1180ms. The tool appeared to meet its 30s SLO with enormous headroom, when in fact the task's wall-clock wait for `pdf_extract` was 61.2s — a 2× SLO breach. The failures that *defined* the breach were the ones filtered out of the SLO population. 3. **Failure taxonomy mis-tagged.** The taxonomy tagger classified `B1` and `B2` as `TOOL_TIMEOUT` and `B3` as `SUCCESS`. Because the tags were computed per-span with no cross-span correlation, the task-level rollup saw one `SUCCESS` and closed the incident as healthy. The *task* had a failure signature — `RETRY_EXHAUSTION_NEAR_MISS` (succeeded only on final attempt) — that no individual span carried, and the tagger had no rule that could synthesize it from siblings. The invariant that was violated: **a task's cost, latency, and failure class must be a function of its logical work units, not of its physical span emissions.** Every physical retry re-emits; the logical unit does not. ## Condition of Validity The double-counting is *bounded and correct* only when all three of the following hold: - The runtime emits a stable `step_id` (or `idempotency_key`) on the orchestrator span that is preserved across retries, and the collector joins on it rather than on `parent_span_id`. - The collector computes cost from a **work-unit ledger** keyed on `(step_id, tool_name, args_hash)`, applying a "last-writer-wins" or "sum-once" policy, not a "sum-all-spans" policy. - The SLO population includes *attempted* spans, not just *completed* spans — i.e., the denominator is "tool invocations attempted" and the numerator is "invocations that completed within SLO," with retries counted as separate invocations for the SLO but collapsed for the cost. When any of these is absent, the pipeline is in the observed failure mode. Note the asymmetry: cost wants **deduplication** (one logical call = one cost), while latency SLO wants **inclusion** (each physical attempt is a real wait the user experienced). A single "sum over spans" rule cannot satisfy both; the pipeline must carry two distinct aggregation policies over the same span set, and must know which policy applies to which metric. ## Decision Boundary The pipeline must decide, per metric, whether it aggregates over **logical work units** or **physical attempts**: | Metric | Aggregation unit | Retry policy | |---|---|---| | Token cost | logical work unit | sum-once (last successful attempt, or first if none succeed) | | Wall-clock latency | physical attempt | include all attempts; report task-level wait as sum of attempt durations | | Tool SLO | physical attempt | include `ERROR` attempts in population; exclude only `CANCELLED_BEFORE_START` | | Failure taxonomy | logical work unit | synthesize task-level tag from attempt sequence; do not tag on last span alone | The boundary condition that flips the decision: if the runtime *reuses* the same `span_id` across retries (some do, mutating the span in place), then `span_id`-keyed deduplication is safe and the work-unit ledger is redundant. But span-ID reuse breaks trace backends that assume immutability, so most runtimes regenerate — which is precisely why the collector cannot assume either behavior and must key on the runtime-supplied `step_id`/`idempotency_key`, treating `span_id` as opaque and non-unique across attempts. A second boundary: retries that are **not** causally linked (e.g., a user re-runs the task) must *not* be collapsed. The `step_id` must be scoped to a single task execution, not to the task definition, or the ledger will merge independent runs. ## Operational Effect The guardrail is a **work-unit ledger with attempt-sequence tagging**, enforced at ingest, not at query time. The collector, on receiving a tool span, looks up the ledger by `(task_execution_id, step_id, tool_name, args_hash)`. If absent, it creates a work-unit record and records the attempt. If present, it appends the attempt to the record's attempt sequence and applies the metric-specific policy above. The failure taxonomy tagger then reads the *attempt sequence* — `[ERROR:TIMEOUT, ERROR:TIMEOUT, OK]` — and emits `RETRY_EXHAUSTION_NEAR_MISS` at the work-unit level, which rolls up to the task. Without this, the three observed effects compound: cost is inflated (budget alarms fire late or never), SLOs read healthy while users wait (the most dangerous direction — silent breach), and failure taxonomy reports green on tasks that are one attempt away from total failure (the near-miss class that should drive capacity planning is invisible). The near-miss case is the one that hurts most in practice: a tool that succeeds only on its final retry looks identical to a tool that succeeds first try, so the retry budget is never tuned and the next timeout is the one that exhausts. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class AttributionLineageError(RuntimeError): """Raised when a span cannot be safely attributed to a logical work unit.""" pass class AttemptStatus(Enum): OK = "OK" ERROR_TIMEOUT = "ERROR_TIMEOUT" ERROR_OTHER = "ERROR_OTHER" CANCELLED_BEFORE_START = "CANCELLED_BEFORE_START" @dataclass class ToolSpan: span_id: str parent_span_id: str task_execution_id: str step_id: Optional[str] # runtime-supplied; may be None if runtime regenerates tool_name: str args: dict status: AttemptStatus duration_ms: int token_cost: float @dataclass class WorkUnit: key: str attempts: list = field(default_factory=list) def add_attempt(self, span: ToolSpan) -> None: self.attempts.append(span) def token_cost(self) -> float: # sum-once: charge the first attempt that actually consumed tokens for a in self.attempts: if a.status is AttemptStatus.OK and a.token_cost > 0: return a.token_cost return 0.0 def wall_clock_wait_ms(self) -> int: # physical: every attempt is real wait the user experienced return sum(a.duration_ms for a in self.attempts) def slo_population(self) -> list: # physical attempts, excluding only pre-start cancellations return [a for a in self.attempts if a.status is not AttemptStatus.CANCELLED_BEFORE_START] def taxonomy_tag(self) -> str: seq = [a.status for a in self.attempts] if all(s is AttemptStatus.ERROR_TIMEOUT for s in seq): return "RETRY_EXHAUSTION_TOTAL_FAILURE" if seq[-1] is AttemptStatus.OK and len(seq) > 1: return "RETRY_EXHAUSTION_NEAR_MISS" if seq[-1] is AttemptStatus.OK: return "SUCCESS" return "FAILURE_OTHER" def args_hash(args: dict) -> str: return hashlib.sha256( repr(sorted(args.items())).encode() ).hexdigest()[:16] class WorkUnitLedger: def __init__(self) -> None: self._units: dict = {} def ingest(self, span: ToolSpan) -> WorkUnit: if span.step_id is None: raise AttributionLineageError( f"span {span.span_id} has no stable step_id; cannot deduplicate " f"retries for task {span.task_execution_id}. Runtime must emit " f"step_id or idempotency_key across retry attempts." ) key = f"{span.task_execution_id}:{span.step_id}:{span.tool_name}:{args_hash(span.args)}" unit = self._units.get(key) if unit is None: unit = WorkUnit(key=key) self._units[key] = unit unit.add_attempt(span) return unit def task_rollup(self, task_execution_id: str) -> dict: units = [u for u in self._units.values() if u.key.startswith(task_execution_id + ":")] if not units: raise AttributionLineageError( f"no work units found for task {task_execution_id}; " f"attribution would be silently zero" ) return { "task_execution_id": task_execution_id, "total_token_cost": sum(u.token_cost() for u in units), "total_wall_clock_ms": sum(u.wall_clock_wait_ms() for u in units), "taxonomy": [u.taxonomy_tag() for u in units], "near_miss": any(u.taxonomy_tag() == "RETRY_EXHAUSTION_NEAR_MISS" for u in units), } ```