# How should an instance reconcile OpenTelemetry GenAI token accounting when an agent span is exported after the model span it summarizes has already been sampled out **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) with a parent agent span whose lifecycle outlives the individual model/tool child spans it aggregates. Does not apply to single-shot inference services where the model span is the root span or where token usage is exported as OTel metrics independent of span sampling. ## Core Distinction The failure is not "sampling drops spans." It is that **GenAI token accounting is defined as an attribute of the span that observed the tokens, but agent-level accounting is defined as the sum of tokens consumed during the agent's lifetime**—and these two definitions live on different spans with different sampling fates. A head-sampling policy that keeps the long-lived agent span (because it started before the sampler decision window, or because it carries a `ParentBased` root decision) but drops the short-lived model child spans produces an agent span whose `gen_ai.usage.*` attributes are either absent or, worse, present-but-partial because the runtime wrote them incrementally as children completed. The invariant that must hold is: **any exported agent span's `gen_ai.usage.input_tokens`/`output_tokens` must equal the sum over the model spans it actually represents, or must be marked as unrepresentable.** There is no valid third state where the number exists and is silently wrong. ## What Was Observed A multi-step agent (planner → 6 tool calls → synthesizer) emitted a root span `agent.run` with `gen_ai.operation.name=invoke_agent` and child spans `chat` (model calls) and `execute_tool` (tool calls). The runtime used an incremental accumulator: each time a model child span ended, it added `response.usage.prompt_tokens` / `completion_tokens` to the parent's `gen_ai.usage.input_tokens` / `output_tokens` attributes via `Span.set_attribute`. The tracer used a `ParentBased(TraceIdRatioBased(0.1))` sampler. Because the root `agent.run` span was sampled-in at creation (root spans are always sampled by the ratio decision), but each child `chat` span was sampled by the *same inherited decision*—and here is the non-obvious part—**a child span inherits the parent's sampling decision at creation time, so if the root was sampled in, all children are sampled in too.** The genuine loss occurred on a different path: when the agent ran under a *remote* parent (a batch orchestrator) whose `TraceFlags` were `NOT_SAMPLED`, the root agent span was created with `RECORD_ONLY` semantics. `set_attribute` calls still mutated the in-memory span, but the span was never exported as a child; the agent span itself was exported as a *link-only* root with `gen_ai.usage.input_tokens=0` because the accumulator had been reset by an unrelated `span.end()` re-entrancy bug in the wrapper. The observable symptom was not missing spans. It was a dashboard where `sum(gen_ai.usage.input_tokens)` over `invoke_agent` spans was **~18% below** the sum over `chat` spans, with the gap concentrated in traces whose root had `trace_flags=0x00`. Token-cost attribution drifted from the agent to nothing, and the cost-per-agent metric silently under-reported for exactly the traffic that ran through the batch orchestrator. ## Condition of Validity The reconciliation invariant holds only when all of the following are true: 1. The agent span is the single writer of its own `gen_ai.usage.*` attributes, and the write happens **after** all child model spans have ended (i.e., at `agent.run` end, not incrementally). 2. The sampling decision for the agent span is independent of child span export—i.e., the accumulator reads from a runtime-side counter, not from "did this child span get exported." 3. `gen_ai.usage.*` is treated as a *terminal* attribute set on the agent span: once written, no child can retroactively change it, because children have already ended. When the agent span is created under a non-sampled remote parent, condition (2) is the one that breaks: the runtime's accumulator must not depend on `Span.is_recording()` of children, because `is_recording()` returns `false` for `RECORD_ONLY` spans and a naive accumulator guarded by `if child.is_recording(): parent.add_tokens(...)` will skip every child. The correct guard is on the *parent's* recording state and on the runtime's own usage source (the provider response object), not on child span state. ## Decision Boundary The decision the runtime must make at each model-call completion: - **If the child model span is sampled AND the parent agent span is recording:** accumulate from the provider response's `usage` field into a runtime-owned counter; do not read from the child span's attributes (they may be truncated by attribute limits). - **If the child is not sampled but the parent is recording:** still accumulate from the provider response. Sampling of the child must not gate the parent's accounting. - **If the parent is not recording (RECORD_ONLY or dropped):** do not attempt to write attributes; instead emit the usage to an OTel **metric** (`gen_ai.client.token.usage` histogram) keyed by `gen_ai.operation.name` and `gen_ai.token.type`, which is not subject to span sampling. This is the boundary: **span-level token attributes are lossy under sampling; metric-level token usage is not.** The runtime must route to metrics whenever the span path cannot guarantee delivery. - **Never** write a partial sum to the agent span and export it. If the runtime cannot prove completeness (e.g., a child span ended without a usage record because the provider omitted it), it must set `gen_ai.usage.input_tokens` to absent and attach an event `gen_ai.usage.incomplete` with the reason, rather than emitting a plausible-looking wrong number. ## Operational Effect The downstream effect of getting this wrong is a *silent* cost and capacity mis-attribution that survives aggregation: because the wrong numbers are structurally valid (`int` attributes on a correctly-named span), no schema validation, no dashboard, and no alert fires. The only detector is a cross-span reconciliation query that compares `invoke_agent` token sums against `chat` token sums per `trace_id`, which most pipelines do not run because the two span kinds are usually aggregated in different dashboards. The guardrail is to make the reconciliation a first-class check: a `gen_ai.usage.reconciled` boolean attribute on the agent span, set only when the runtime's counter equals the sum of the usage records it actually observed, plus a metric `gen_ai.agent.usage_reconciliation_failures` that increments when the agent span is exported with an unreconciled or absent usage block. Treat a `false` or absent `reconciled` flag as a hard signal that the token number must not be summed. ```python from dataclasses import dataclass, field class TokenAccountingInvariantError(RuntimeError): """Raised when an agent span's GenAI token attributes cannot be reconciled against the model-call usage records it claims to summarize.""" @dataclass class UsageRecord: input_tokens: int output_tokens: int @dataclass class AgentSpanState: span_recording: bool observed_usage: list[UsageRecord] = field(default_factory=list) written_input_tokens: int | None = None written_output_tokens: int | None = None reconciled: bool = False def record_model_call(state: AgentSpanState, usage: UsageRecord | None) -> None: # Accumulate from the provider response, NOT from child span attributes. # Sampling of the child span must never gate the parent's accounting. if usage is None: # Provider omitted usage: the sum is now unrepresentable. state.observed_usage.append(UsageRecord(0, 0)) return state.observed_usage.append(usage) def finalize_agent_span(state: AgentSpanState) -> AgentSpanState: if not state.span_recording: # RECORD_ONLY / dropped parent: do not write span attributes at all. # Caller must route usage to gen_ai.client.token.usage metrics instead. state.reconciled = False return state total_in = sum(u.input_tokens for u in state.observed_usage) total_out = sum(u.output_tokens for u in state.observed_usage) if state.written_input_tokens is not None and state.written_input_tokens != total_in: raise TokenAccountingInvariantError( f"agent span input_tokens={state.written_input_tokens} " f"!= observed sum={total_in}" ) if state.written_output_tokens is not None and state.written_output_tokens != total_out: raise TokenAccountingInvariantError( f"agent span output_tokens={state.written_output_tokens} " f"!= observed sum={total_out}" ) # A zero-token model call with no usage record means the sum is a lie. if any(u.input_tokens == 0 and u.output_tokens == 0 for u in state.observed_usage): state.written_input_tokens = None state.written_output_tokens = None state.reconciled = False raise TokenAccountingInvariantError( "usage record missing for one or more model calls; " "refusing to export partial gen_ai.usage.* on agent span" ) state.written_input_tokens = total_in state.written_output_tokens = total_out state.reconciled = True return state ```