# Which invariants prevent span-attribute divergence from breaking token/cost correlation across agent tool-call traces **Date of Record:** 2026 November 25 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a parent agent span fans out to child `execute_tool` spans and LLM invocation spans, and where cost is reconstructed post-hoc by joining `gen_ai.usage.input_tokens`/`output_tokens` to a model-price table keyed on `gen_ai.request.model`. Does not cover single-shot, single-span inference where no fan-out or join occurs. ## Core Distinction The naive mental model treats a trace as a faithful ledger: every span carries its own token counts, sum the leaves, multiply by price, done. The real failure mode is **attribute provenance divergence** — the same logical attribute (model identity, token count, tool name) is populated at different points in the agent's execution graph by different code paths, and the join key used for cost correlation is *not* the key that was authoritative at generation time. Specifically: the agent's planner emits a child LLM span tagged `gen_ai.request.model = "gpt-4o"`, but the tool-call span that actually triggered the retry emits `gen_ai.request.model = "gpt-4o-mini"` because the fallback path re-stamped the attribute after a 429. The trace is syntactically valid — every span has the required attributes — but the cost join silently attributes mini-priced tokens to a 4o-priced parent, or worse, double-counts because the retry span and the original span share a `gen_ai.response.id`. This is not a telemetry bug; it is an *invariant violation at the agent layer*: the model that produced a token is not recoverable from the span that reports the token. ## What Was Observed A tool-augmented agent (planner → 3 parallel tool calls → synthesis) under a provider rate-limit produced the following trace fragment: ``` span_id=parent gen_ai.operation.name=chat gen_ai.request.model=gpt-4o span_id=t1 gen_ai.operation.name=execute_tool gen_ai.tool.name=search span_id=t1.llm gen_ai.request.model=gpt-4o gen_ai.usage.input_tokens=1802 span_id=t1.llm gen_ai.request.model=gpt-4o-mini gen_ai.usage.input_tokens=1802 # retry, SAME span_id span_id=t2 gen_ai.operation.name=execute_tool gen_ai.tool.name=lookup span_id=t2.llm gen_ai.request.model=gpt-4o gen_ai.usage.input_tokens=0 # failed, no usage emitted ``` Three distinct divergences surfaced: 1. **Retry re-stamping.** The retry reused the span object and overwrote `gen_ai.request.model` from `gpt-4o` to `gpt-4o-mini`. The exporter saw one span. The cost join priced 1802 input tokens at mini rates even though the first attempt was billed at 4o rates by the provider. The 4o attempt's tokens are *lost from telemetry but present on the invoice*. 2. **Zero-token failure spans.** `t2.llm` emitted `input_tokens=0` on a hard failure. A naive `SUM(input_tokens)` is correct here, but a naive `AVG` or a per-span "cost = tokens × price" produces a zero-cost span that masks the fact that a tool call *was attempted and billed for prompt processing* on some providers. 3. **Missing `gen_ai.response.id`.** The retry span carried a new response id but the same span id, so dedup-by-response-id and dedup-by-span-id disagree on whether this is one billable event or two. The observable symptom downstream: daily cost dashboards under-reported by 6–11%, and the error was **non-monotonic in traffic** — it vanished at low volume (retries rare) and at very high volume (rate limiter pre-empts, no retry), appearing only in the mid-band where retries actually fire. ## Condition of Validity The correlation invariant holds only when all three of the following are true: - **I1 — Attribute immutability per span.** Once a span is `Start`ed, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, and `gen_ai.usage.output_tokens` are write-once. A retry MUST create a new span (new `span_id`) with `gen_ai.operation.name` preserved and a link (`SpanLink`) back to the failed attempt, not overwrite. - **I2 — Model identity is co-located with usage.** The `gen_ai.request.model` attribute on the span that carries `gen_ai.usage.*` is the model that produced those tokens. If a fallback changed the model, the usage attributes MUST live on the fallback span, and the parent MUST NOT aggregate them under its own model key. - **I3 — Response-id uniqueness partitions billable events.** `gen_ai.response.id`, when present, is unique per provider-billed generation. Two spans sharing a response id are one billable event; two spans with different response ids and the same `span_id` are a corruption, not a dedup opportunity. When I1 is violated (retry overwrites in place), the trace is *lossy but not detectably so* — there is no marker that a prior model existed. When I2 is violated (usage aggregated to parent model key), cost is wrong by the price delta. When I3 is violated, dedup logic is ambiguous and different consumers (billing vs. latency) disagree. The invariant does **not** apply to streaming spans where usage is emitted on span end only; there, the "write-once" rule degrades to "write-once-at-end" and retries must still fork the span. ## Decision Boundary The boundary between "correlatable trace" and "silently mispriced trace" is crossed at the moment a retry or fallback mutates an attribute that a downstream join depends on, *without forking the span*. Operationally: - If your exporter is a **batching processor with attribute overwrite semantics** (the default OTel `BatchSpanProcessor` combined with a mutable span handle), you are on the wrong side of the boundary the first time a retry fires. Fork the span. - If your cost join keys on `(span_id, gen_ai.request.model)`, you are exposed to I2 violations. Key instead on `(gen_ai.response.id)` where present, falling back to `(span_id, gen_ai.request.model, gen_ai.usage.input_tokens)` — and *reject* rows where the same `span_id` appears with two different models. - If your agent framework's retry decorator wraps the LLM call *inside* the span scope, you are guaranteed to violate I1. The retry must wrap the span creation, not the call. The safe side of the boundary requires an explicit **span-fork-on-retry** policy and a **join-key validator** at the cost-aggregation layer that fails loudly on model-attribute divergence within a span id. ## Operational Effect Enforcing I1–I3 changes three things: 1. **Cost accuracy becomes bounded.** With forked retry spans, the sum of `gen_ai.usage.input_tokens` across all spans with distinct `gen_ai.response.id` matches the provider invoice to within rounding. The 6–11% mid-band under-report disappears because the 4o attempt is no longer overwritten. 2. **Trace cardinality increases on the retry path.** Expect ~1.05–1.15× span count under rate limiting. This is the price of provenance; budget your trace backend for it. 3. **The join becomes auditable.** A validator that asserts "no `span_id` carries two distinct `gen_ai.request.model` values" converts a silent mispricing into a hard failure at ingestion, which is the correct failure mode — it fails at the boundary where the invariant was broken, not three dashboards downstream. The deeper lesson: OTel GenAI semantic conventions specify *what* attributes to emit, not *when they may change*. The continuity invariant that makes cost telemetry trustworthy is not in the spec — it is the agent author's obligation to treat per-span attributes as immutable and to fork, never mutate, on any probabilistic retry path. ```python from dataclasses import dataclass, field from typing import Optional class SpanProvenanceViolation(RuntimeError): """Raised when a span's cost-relevant attributes diverge from the invariant required for token/cost correlation (I1-I3).""" pass @dataclass(frozen=True) class GenAISpan: span_id: str operation: str request_model: str input_tokens: int output_tokens: int response_id: Optional[str] = None parent_span_id: Optional[str] = None @dataclass class CostLedger: spans: list[GenAISpan] = field(default_factory=list) _seen_span_models: dict[str, set[str]] = field(default_factory=dict) _seen_response_ids: dict[str, str] = field(default_factory=dict) def record(self, span: GenAISpan) -> None: # I1: a span_id must map to exactly one request_model. models = self._seen_span_models.setdefault(span.span_id, set()) models.add(span.request_model) if len(models) > 1: raise SpanProvenanceViolation( f"I1 violated: span_id={span.span_id} carries multiple " f"gen_ai.request.model values {sorted(models)}; retry must " f"fork the span, not overwrite it." ) # I3: a response_id must map to exactly one span_id. if span.response_id is not None: prior = self._seen_response_ids.get(span.response_id) if prior is not None and prior != span.span_id: raise SpanProvenanceViolation( f"I3 violated: response_id={span.response_id} observed on " f"span_id={prior} and span_id={span.span_id}; billable " f"event is ambiguous for dedup." ) self._seen_response_ids[span.response_id] = span.span_id # I2: usage must be co-located with the model that produced it. if span.operation == "execute_tool" and span.input_tokens > 0: raise SpanProvenanceViolation( f"I2 violated: tool span {span.span_id} carries LLM usage; " f"usage must live on the child chat span, not the tool span." ) self.spans.append(span) def total_tokens(self) -> tuple[int, int]: return ( sum(s.input_tokens for s in self.spans), sum(s.output_tokens for s in self.spans), ) def ingest_retry_attempt(ledger: CostLedger, original: GenAISpan, fallback_model: str) -> GenAISpan: """Correct pattern: fork a new span for the retry, link to original.""" if fallback_model == original.request_model: raise SpanProvenanceViolation( "fallback_model equals original; retry would be indistinguishable " "from a duplicate and cannot be deduped by response_id." ) forked = GenAISpan( span_id=original.span_id + ".retry1", operation=original.operation, request_model=fallback_model, input_tokens=original.input_tokens, output_tokens=0, response_id=None, # populated on completion parent_span_id=original.parent_span_id, ) ledger.record(forked) return forked ```