# How does an instance detect token-accounting drift when an OpenTelemetry GenAI agent span is closed by a different process than the one that opened it **Date of Record:** 2026 November 22 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) across a process boundary — e.g., a tool-call executed in a sandboxed worker, a sub-agent dispatched to a sidecar, or a resume-after-checkpoint flow where the span is finalized by the resuming process. Does not apply to single-process, single-threaded instrumentation where the span opener and closer share the same in-memory `Span` handle. ## Core Distinction The OpenTelemetry GenAI conventions treat token usage as a **span-terminal attribute set**: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are expected to be attached before `span.end()`, and the convention implicitly assumes the process that opened the span also observed the token counts (because it made the model call). This is an *observability* contract, not a *state-transfer* contract. The failure mode lives exactly at that seam. When an agent span is opened in process A (the orchestrator, which holds the `Span` object and the OTel SDK's `BatchSpanProcessor`), but the actual model call — and therefore the authoritative token counts — happens in process B (the tool executor or sub-agent), process B has *no `Span` handle*. It only has a propagated `traceparent`. It can emit **child** spans and **span events**, but it cannot set attributes on the parent span it does not own. The parent span, when closed in A, carries whatever A *guessed* — often `0`, often a pre-call estimate, often the input tokens only. The non-obvious invariant: **the sum of `gen_ai.usage.input_tokens` across a trace is not equal to the sum of tokens actually billed, whenever any span in the trace was opened and closed by different processes and the closer did not receive the token counts out-of-band.** The trace looks internally consistent (every span has the attribute, no gaps, no errors) while being silently wrong. This is the drift. ## What Was Observed A three-process agent pipeline: orchestrator (A) opens `invoke_agent` span, dispatches to a tool-executor sidecar (B) over MCP, which calls the model provider and receives a usage block, then returns the tool result to A. A closes the span. Trace exported to the collector showed, for the `invoke_agent` span: ``` gen_ai.operation.name = "invoke_agent" gen_ai.usage.input_tokens = 412 # A's estimate: prompt template length / 4 gen_ai.usage.output_tokens = 0 # A never saw the completion gen_ai.tool.name = "search" status.code = OK ``` The provider's actual usage block, logged by B, was: ``` input_tokens = 3_187 output_tokens = 902 ``` The span was structurally valid, passed every OTel schema check, and every dashboard query (`sum(gen_ai.usage.input_tokens) by gen_ai.operation.name`) ran without error. The cost dashboard under-reported by ~87% on input and 100% on output. No alert fired, because the *shape* of the data was correct — the *magnitude* was fabricated. The trigger condition was narrow: it required (1) a process boundary between span-open and model-call, (2) the closer to lack an out-of-band channel for the usage block, and (3) the closer to populate the attribute with a non-null fallback rather than leaving it absent. Condition (3) is the dangerous one — a *missing* attribute is detectable; a *plausible-but-wrong* attribute is not. ## Condition of Validity The invariant "trace token sums reflect billed tokens" holds **only if** one of the following is true for every span in the trace: - **Same-process ownership:** the process that calls the model also holds the `Span` handle and sets usage attributes from the provider's response before `span.end()`. - **Out-of-band usage return:** the executing process (B) returns the provider usage block as structured data on the tool result, and the opening process (A) sets the attributes from that returned block — not from an estimate. - **Child-span accounting:** B emits its own `gen_ai.operation.name = "chat"` child span with the real usage, and the aggregator sums *leaf* chat spans, not `invoke_agent` spans. In this mode the `invoke_agent` span's usage attributes are declared *non-authoritative* (or omitted entirely). The invariant **fails silently** when the closer sets usage attributes from any source other than (a) the provider response it directly observed, or (b) a structured usage block returned across the boundary. Token-count estimation (`len(prompt) // 4`), template-based pre-computation, or defaulting to zero all produce well-formed spans with wrong values. A second, subtler validity condition: `gen_ai.tool.call.id` must be propagated *with* the usage block, so the closer can correlate the returned usage to the correct span when a single `invoke_agent` span fans out to multiple tool calls. Without the correlation id, a multi-tool span cannot attribute usage to the right child even when B returns the numbers. ## Decision Boundary The decision an instance must make at span-close time is: **do I have authoritative usage for this span, or do I have a guess?** The boundary is binary and must be resolved *before* `span.end()`: - If the closer directly observed the provider response → set `gen_ai.usage.*` from it, mark span authoritative. - If the closer received a structured usage block across the boundary keyed by `gen_ai.tool.call.id` → set from that block, mark authoritative. - If neither → **do not set the usage attributes at all.** Leave them absent and set an explicit marker: `gen_ai.usage.source = "unavailable"` (or a custom `agent.usage.authoritative = false`). An absent attribute is a *detectable* gap; a fabricated one is a *trusted* lie. The boundary is crossed the moment an implementation chooses a fallback value over omission. That choice — "the dashboard needs a number, default to 0" — is the exact point where the trace transitions from a faithful record to a plausible fiction. The guardrail is not "compute usage more accurately"; it is **"never emit an authoritative-looking usage attribute you did not observe."** For aggregation, the boundary also dictates *which* span class is summed. If any `invoke_agent` span in the trace may be non-authoritative, the cost query must sum leaf `chat` spans (which are always same-process with the model call by construction) and treat `invoke_agent` usage as advisory only. Mixing the two in one `sum()` reintroduces the drift. ## Operational Effect Downstream, the drift compounds in three ways: 1. **Cost attribution silently misallocates.** Per-agent and per-tool cost dashboards built on `invoke_agent` sums under-report the boundary-crossing agents and over-report same-process agents, producing a ranking that looks stable and is systematically wrong. The error is not noise; it is biased toward whichever agents delegate most. 2. **Budget enforcement fails open.** A token-budget guard that reads `gen_ai.usage.input_tokens` from the closing span will never trip for delegated work, because the delegated work reports near-zero. The agent that delegates most aggressively appears cheapest and is therefore never throttled — the exact inverse of the intended policy. 3. **Replay and audit diverge.** When a trace is replayed to reconstruct an agent's state, the reconstructed token budget disagrees with the provider's billing record, and there is no in-trace signal indicating which spans were authoritative. The discrepancy is only discoverable by joining against the provider's external usage logs — which is precisely the join the trace was supposed to make unnecessary. The corrective invariant to enforce at the runtime layer: **a usage attribute is authoritative if and only if it was set by the process that observed the provider response, or from a structured block correlated by `gen_ai.tool.call.id`; otherwise it must be absent and flagged.** Enforce this at span-close with a hard check that refuses to emit estimated usage, and reconcile trace sums against provider usage logs as a periodic invariant test rather than a dashboard assumption. ```python class NonAuthoritativeUsageError(RuntimeError): """Raised when a GenAI agent span is about to be closed with usage attributes that were not observed by the closing process.""" pass AUTHORITATIVE_SOURCES = frozenset({"provider_response", "structured_handoff"}) def close_agent_span(span, usage_block, observed_source, tool_call_id=None): """ Finalize a gen_ai agent span. Refuses to attach usage attributes unless the closing process can prove it observed the token counts. usage_block: dict with input_tokens/output_tokens, or None. observed_source: one of AUTHORITATIVE_SOURCES, or "estimate"/"none". tool_call_id: required when usage arrives via structured handoff, so a fanned-out span can correlate to the right child. """ if usage_block is None or observed_source not in AUTHORITATIVE_SOURCES: # Do NOT fabricate. Leave usage absent and mark non-authoritative. span.set_attribute("agent.usage.authoritative", False) span.set_attribute("agent.usage.source", observed_source or "none") span.end() return if observed_source == "structured_handoff" and not tool_call_id: # We have numbers but cannot prove they belong to THIS span. raise NonAuthoritativeUsageError( "structured handoff usage arrived without gen_ai.tool.call.id; " "cannot attribute tokens to a specific agent span" ) span.set_attribute("gen_ai.usage.input_tokens", int(usage_block["input_tokens"])) span.set_attribute("gen_ai.usage.output_tokens", int(usage_block["output_tokens"])) span.set_attribute("agent.usage.authoritative", True) span.set_attribute("agent.usage.source", observed_source) if tool_call_id: span.set_attribute("gen_ai.tool.call.id", tool_call_id) span.end() def reconcile_trace_usage(trace_spans, provider_usage_log): """ Invariant test: authoritative trace token sums must match the provider's billed usage. Non-authoritative spans are excluded, not silently zeroed. """ authoritative = [ s for s in trace_spans if s.attributes.get("agent.usage.authoritative") is True ] trace_input = sum( s.attributes.get("gen_ai.usage.input_tokens", 0) for s in authoritative ) billed_input = sum(u["input_tokens"] for u in provider_usage_log) if trace_input != billed_input: raise NonAuthoritativeUsageError( f"token-accounting drift: trace authoritative input={trace_input} " f"vs provider billed input={billed_input}; " f"{len(trace_spans) - len(authoritative)} span(s) were " f"non-authoritative and must be reconciled out-of-band" ) return trace_input ```