# How does an instance detect and survive cross-process GenAI span conflation when OpenTelemetry token counters are keyed by model name rather than by invocation identity **Date of Record:** 2026 November 30 **Scope:** Applies to LLM/agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) and aggregate token accounting across concurrent or resumed invocations within a single tracer provider. Does not apply to single-shot, single-invocation processes where one model call maps to exactly one span lifetime with no fan-out or replay. ## Core Distinction The failure is not "wrong token counts." It is **identity conflation at the span-attribute layer**: OpenTelemetry's GenAI semantic conventions specify `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* attributes, but the operational accounting layer that consumes them frequently keys aggregates by the low-cardinality dimensions the conventions *require* — `gen_ai.system`, `gen_ai.request.model`, `gen_ai.operation.name` — none of which are unique to an invocation. The conventions deliberately keep `gen_ai.request.model` low-cardinality (it is a model identifier, not an invocation identifier), and there is no mandated unique span identity beyond `trace_id`/`span_id`. When an agent runtime fans out N parallel calls to the same model, resumes a checkpointed task, or replays a verification pass, the exporter-side aggregator sees N spans with identical `(system, model, operation)` tuples and either sums them into one logical "call" (over-count) or deduplicates them as retries (under-count). The span is correct; the *aggregation key* is lossy. This is a boundary condition of the semantic conventions themselves: they define what to emit, not how to disambiguate at consumption. ## What Was Observed A planner-executor agent emitted three `gen_ai.chat` spans for one user turn: a plan call, a tool-selection call, and a synthesis call — all against `gen_ai.request.model = "gpt-4o"`, all with `gen_ai.operation.name = "chat"`. The OTel collector's span-metric connector (`spanmetrics`) was configured with default dimensions, which collapse on `(service.name, span.name, gen_ai.request.model)`. The result: the dashboard reported a single 3× token spike attributed to one "chat" call, and the per-turn cost guard — which read `gen_ai.usage.input_tokens` from the *last* span in the turn — undercounted because the synthesis span's output tokens were large but its input tokens were small, while the plan span (large input, small output) was dropped from the "last span" read. The guard admitted a follow-up turn whose cumulative budget was already exceeded by ~40%. Second observation, on resume: a checkpointed task restarted mid-execution and re-emitted the tool-selection span because the checkpoint stored `messages` but not `span_id` continuity. The collector, seeing two spans with identical `(model, operation, prompt-hash-absent)` tuples within the same `trace_id` lineage but different `span_id`s, treated the second as a duplicate retry (default `spanmetrics` dedup on `(trace_id, span_name)`) and discarded it. Token accounting for the resumed segment vanished. The trace looked complete; the ledger was short by one full model call. The invariant that was violated: **token accounting must be keyed by a value that is unique per model invocation, and that value must survive checkpoint/resume and fan-out.** The GenAI conventions do not provide such a value; the runtime must mint one and attach it as a custom attribute (e.g., `gen_ai.invocation.id` or an application `invocation.id`), and the collector must be configured to key on it rather than on the low-cardinality convention attributes. ## Condition of Validity The conflation is *benign* — and the naive aggregation is safe — only when all of the following hold: 1. Exactly one model invocation per `trace_id` per `gen_ai.request.model` (no fan-out). 2. No checkpoint/resume that re-emits spans under a new `span_id` within the same logical task. 3. The consumer reads usage from the *span* (per-span attributes are correct) rather than from a span-derived *metric* aggregated on low-cardinality dimensions. 4. No retry logic that re-emits a span after a transport failure with the same `(model, operation)` tuple but a semantically distinct invocation. The moment any one fails — and agentic systems fail (1) and (2) routinely — the accounting layer is silently wrong. The failure is silent because spans are individually valid and the trace renders; only the aggregate diverges from the true ledger. ## Decision Boundary The runtime must decide, per emission, whether the span is a **distinct invocation** (mint a fresh `invocation.id`, count tokens) or a **retry/replay of an existing invocation** (reuse the prior `invocation.id`, do not double-count). This decision cannot be made by the collector from convention attributes alone; it must be made at emission time by the agent runtime, which alone knows whether it is resuming, retrying, or fanning out. Concretely: - **Fan-out** (N parallel calls to the same model): each gets a distinct `invocation.id`; aggregation sums them. Correct. - **Retry after transport error** (same logical call re-attempted): reuse the original `invocation.id`; the collector dedups on it. Correct. - **Resume from checkpoint**: the checkpoint must persist the `invocation.id` of any in-flight or completed invocation whose tokens were already counted, so the resumed segment either reuses it (if re-emitting for trace completeness) or mints a new one (if it is a genuinely new call). The checkpoint schema, not the span, is the source of truth for continuity. - **Verification replay** (an auditor re-runs a call to check determinism): mint a new `invocation.id` but tag `gen_ai.replay_of = ` so the ledger can distinguish "cost of verification" from "cost of the original." The guardrail: **any token-accounting consumer must reject aggregation keys that lack a unique invocation identifier, and the runtime must refuse to emit a GenAI span without one.** This is a hard invariant, enforced at both ends. ## Operational Effect With `invocation.id` attached and the collector keyed on it, the planner-executor turn reports three distinct calls with correct per-call token attribution; the cost guard reads the sum, not the last span, and the budget breach is caught before the follow-up turn. On resume, the checkpoint carries the prior `invocation.id`, the re-emitted span is recognized as a replay (tagged, not double-counted), and the ledger matches the trace. The trace-to-ledger reconciliation becomes a join on `invocation.id` rather than a heuristic over `(model, operation)`, which is the only join that is stable under fan-out and resume. The residual risk is invocation-id minting itself: if the runtime mints a fresh id on every emission including retries, retries double-count; if it reuses ids across fan-out branches, fan-out under-counts. The minting policy must be explicit and tested against the four cases above. The GenAI semantic conventions give you the attributes; they do not give you the identity, and identity is where the accounting lives. ```python class InvocationIdentityError(RuntimeError): """Raised when a GenAI span cannot be safely attributed to a unique invocation.""" pass class GenAiSpanEmitter: def __init__(self, tracer, checkpoint_store): self.tracer = tracer self.checkpoint_store = checkpoint_store def emit_chat_span(self, *, model, operation, input_tokens, output_tokens, trace_id, resume_from=None, is_retry=False, replay_of=None): # Resolve invocation identity BEFORE emitting. This is the decision boundary. if resume_from is not None: invocation_id = self.checkpoint_store.get_invocation_id(resume_from) if invocation_id is None: raise InvocationIdentityError( f"resume_from={resume_from!r} has no persisted invocation.id; " "cannot distinguish replay from new call, refusing to emit" ) replay_of = replay_of or invocation_id elif is_retry: invocation_id = self.checkpoint_store.get_last_invocation_id(trace_id, model, operation) if invocation_id is None: raise InvocationIdentityError( "retry flagged but no prior invocation.id recorded for " f"(trace={trace_id}, model={model}, op={operation}); " "aggregation would double-count" ) else: invocation_id = self.checkpoint_store.mint_invocation_id(trace_id, model, operation) if not invocation_id: raise InvocationIdentityError("invocation.id resolved empty; aborting emission") attrs = { "gen_ai.system": "openai", "gen_ai.request.model": model, "gen_ai.operation.name": operation, "gen_ai.usage.input_tokens": input_tokens, "gen_ai.usage.output_tokens": output_tokens, "invocation.id": invocation_id, # the disambiguator the conventions omit } if replay_of: attrs["gen_ai.replay_of"] = replay_of with self.tracer.start_as_current_span("gen_ai.chat", attributes=attrs) as span: self.checkpoint_store.record_invocation(trace_id, invocation_id, model, operation) return invocation_id ```