What structural signals indicate span-attribute lineage collapse in OpenTelemetry GenAI tool-call chains under retry
**Date of Record:** 2026 December 1 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) where tool invocations are retried, replayed, or resumed after checkpoint. Does not apply to single-shot inference spans with no tool lineage, nor to non-OTel telemetry backends that deduplicate by request-id at ingest.
Core Distinction
The GenAI semantic conventions treat `gen_ai.tool.call.id` as an *identity* attribute and `gen_ai.usage.*_tokens` as *cumulative counters scoped to the span*. These two assumptions collide the moment a tool call is retried: the retry is a new span, but the *logical* tool call is the same, and the token usage of the retried attempt is a fresh delta, not a continuation. The non-obvious boundary is this — **a retried tool call produces two spans that share a lineage key (`tool.call.id`) but must not be summed, while a resumed tool call produces two spans that share a lineage key and *must* be summed.** The telemetry layer cannot distinguish "retry" from "resume" from span attributes alone, because both emit the same `tool.call.id` with `gen_ai.operation.name = "execute_tool"` and no parent-link discriminator. This is a lineage collapse: the aggregator silently double-counts retries as resumes, and the token ledger inflates with every transient tool failure.
What Was Observed
A planner agent issued a `search_index` tool call. The tool returned a 503 on the first attempt (span A, `input_tokens=812`, `output_tokens=44`). The agent's retry loop re-issued the identical call with the same `tool.call.id` (span B, `input_tokens=812`, `output_tokens=41`). Span B succeeded. The trace exporter shipped both spans. The downstream cost aggregator, keyed on `gen_ai.tool.call.id`, summed the two spans to `input_tokens=1624`, `output_tokens=85` — a 100% overcount on input and a phantom 41-token output for a call that never produced a result.
The failure signal was structural, not numeric: span A carried `gen_ai.tool.call.id = "call_7f3a"` and `status.code = ERROR`; span B carried the *same* `gen_ai.tool.call.id` and `status.code = OK`. No parent-span link distinguished them. No `retry.attempt` attribute existed. The aggregator had no field it could branch on. It saw two child spans of the same agent turn with identical lineage keys and did the only defensible thing given the schema: it treated them as a fan-out and summed.
The inverse case is worse. When the agent checkpointed mid-tool-call and resumed in a *fresh process*, the resumed span carried a *new* `tool.call.id` (the runtime regenerated it) but the *same* logical operation. The aggregator saw two distinct lineage keys and did not sum — undercounting the resumed work by the full token cost of the pre-checkpoint span. The same schema produced opposite errors in the two directions, and neither was detectable from the span attributes alone.
Condition of Validity
The invariant that holds is: **`gen_ai.tool.call.id` is a lineage key, not a deduplication key.** It is valid to use it to *group* spans into a logical tool call. It is not valid to use it to *sum* token usage across spans in that group unless each span also carries an explicit `gen_ai.tool.attempt` ordinal and a `gen_ai.tool.lineage.continuation` boolean. Without those two attributes, the following boundary condition is unresolvable:
- If two spans share `tool.call.id` and both have `status.code = ERROR` except the last, they are retries — sum only the last.
- If two spans share `tool.call.id` and the first has `status.code = UNSET` (checkpointed, not terminal) and the second has `status.code = OK`, they are a resume — sum both.
- If two spans share `tool.call.id` and the first has `status.code = ERROR` and the second has `status.code = OK`, they are *ambiguous* — this is the retry-after-transient-failure case, and the schema cannot tell it from resume-after-checkpoint.
The condition of validity for any token ledger built on GenAI conventions is therefore: **the ledger must not aggregate across spans sharing a lineage key unless every span in the group carries an attempt ordinal.** Absent that attribute, the ledger must treat the group as a single attempt and take the *last* span's usage, accepting undercount on genuine resumes as the lesser error, because overcounting retries compounds across every transient failure in the run.
Decision Boundary
The boundary is crossed when an agent's tool-call retry policy is decoupled from its span-emission policy. A retry loop that re-invokes the tool without incrementing an attempt counter on the span creates the collapse. The guardrail is architectural, not observational:
- **Attempt ordinal is mandatory.** Every `execute_tool` span must carry `gen_ai.tool.attempt` (integer, 1-indexed). The retry wrapper increments it before span creation, not after.
- **Lineage key is stable across retries, regenerated across resumes.** The `tool.call.id` must be derived from the logical call (e.g., a hash of `(turn_id, tool_name, canonical_args)`), not from a per-attempt UUID. On checkpoint/resume, the resumed process must *recover* the lineage key from the checkpoint, not mint a new one — otherwise the resume becomes a silent new call.
- **Token usage is per-attempt, never cumulative.** `gen_ai.usage.input_tokens` on span B is the input tokens *of attempt 2*, not the running total. The aggregator sums across attempts only when `gen_ai.tool.attempt` is present and monotonic.
- **Terminal status gates the sum.** A span with `status.code = ERROR` and a later sibling with the same lineage key and higher attempt ordinal is a superseded attempt — its usage is *discarded*, not summed. A span with `status.code = UNSET` is a checkpoint boundary — its usage *is* summed with the continuation.
The decision boundary in operational terms: if the telemetry pipeline cannot assert (1) through (4) at ingest time, it must emit a `lineage_ambiguous` flag on the group and route it to manual reconciliation rather than silently summing. Silent summation is the failure; the flag is the invariant.
Operational Effect
The observable effect of lineage collapse is a token ledger that inflates superlinearly with tool failure rate. In a run with a 15% transient tool-failure rate and a 3-attempt retry budget, the naive sum overcounts input tokens by roughly 1.15× to 1.45× depending on retry depth — and the overcount is *correlated with tool flakiness*, so it looks like the agent is burning more context precisely when the environment is degraded. Cost dashboards attribute the spike to model behavior; the actual cause is the aggregator summing retry deltas as if they were resumes.
The second-order effect is worse for debugging: because the collapsed spans share a lineage key, trace UIs that group by `tool.call.id` show a single tool call with two conflicting `status.code` values and doubled token counts. An operator reading the trace sees an impossible span — one call, two outcomes, double the tokens. The natural diagnosis is "the agent called the tool twice in parallel," which sends the investigation toward concurrency bugs and away from the retry wrapper, where the actual defect lives.
The continuity invariant that prevents this is: **a lineage key identifies a logical call; an attempt ordinal identifies a physical execution; token usage belongs to the physical execution; the logical call's cost is the sum over *non-superseded* physical executions.** Any telemetry layer that conflates lineage key with execution identity will violate this invariant on the first retry, and the violation will be invisible until someone reconciles the token ledger against the provider's billing API — which is the only external ground truth that cannot be corrupted by the schema's ambiguity.
class LineageCollapseError(RuntimeError):
"""Raised when GenAI span attributes cannot distinguish retry from resume."""
pass
def aggregate_tool_usage(spans: list[dict]) -> dict:
"""
Sum token usage across a logical tool call, refusing to guess
when retry/resume is ambiguous.
Each span is expected to carry:
gen_ai.tool.call.id (str) lineage key
gen_ai.tool.attempt (int) 1-indexed attempt ordinal
gen_ai.usage.input_tokens (int) per-attempt delta
gen_ai.usage.output_tokens (int) per-attempt delta
status.code (str) OK | ERROR | UNSET
"""
if not spans:
return {"input_tokens": 0, "output_tokens": 0, "attempts": 0}
lineage_keys = {s.get("gen_ai.tool.call.id") for s in spans}
if len(lineage_keys) > 1:
raise LineageCollapseError(
f"spans span multiple lineage keys {lineage_keys}; "
"cannot aggregate across logical calls"
)
attempts = [s.get("gen_ai.tool.attempt") for s in spans]
if any(a is None for a in attempts):
raise LineageCollapseError(
f"lineage key {lineage_keys.pop()!r} has spans without "
"gen_ai.tool.attempt; retry vs resume is unresolvable — "
"refusing to sum, route to reconciliation"
)
if sorted(attempts) != list(range(1, len(attempts) + 1)):
raise LineageCollapseError(
f"attempt ordinals {sorted(attempts)} are not a contiguous "
"1..N sequence; a resume likely minted a fresh lineage key "
"or a retry skipped an ordinal"
)
# Supersede rule: an ERROR attempt followed by a higher-ordinal sibling
# is discarded. UNSET (checkpoint) attempts are summed with continuation.
kept = []
for s in spans:
higher_exists = any(
o.get("gen_ai.tool.attempt") > s["gen_ai.tool.attempt"]
for o in spans
)
if s.get("status.code") == "ERROR" and higher_exists:
continue # superseded retry — discard its usage
kept.append(s)
return {
"input_tokens": sum(s.get("gen_ai.usage.input_tokens", 0) for s in kept),
"output_tokens": sum(s.get("gen_ai.usage.output_tokens", 0) for s in kept),
"attempts": len(kept),
}