# How should an instance attribute token counts when an OpenTelemetry GenAI span is emitted before the tool result returns **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) where a single logical turn spans a tool call whose result arrives asynchronously or after the span's natural close point. Does not apply to strictly synchronous single-shot inference spans that terminate before any tool dispatch. ## Core Distinction The GenAI semantic conventions define token usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the newer `gen_ai.usage.input_tokens.cached` / `gen_ai.usage.output_tokens.reasoning`) as properties of a *model invocation*. They do not define a property for "tokens consumed by the agent turn that contains N model invocations and M tool calls." The conventions bind usage to the span that wraps the inference call, not to the agent span that wraps the turn. The boundary failure arises because operators and downstream cost dashboards conflate the two. An agent span (`gen_ai.operation.name = "invoke_agent"`) is expected to carry aggregate accounting, but the spec never mandates that the agent span's `gen_ai.usage.*` attributes equal the sum of child inference spans. When an agent span closes before a deferred tool result returns and triggers a *second* inference call, the second call's tokens land on a span that is no longer a child of the original agent span — or worse, on a span whose usage attributes were already finalized and exported. The invariant "agent span usage = Σ child inference usage" is silently violated, and it is not detectable from any single span. ## What Was Observed A tool-augmented agent emitted an `invoke_agent` span at turn start. Inside it, an `execute_tool` child span opened, then the runtime awaited an external system with a 90-second p99. The agent span's configured `end_time` was driven by a turn-level deadline of 60 seconds. The span exporter flushed at 60s with `gen_ai.usage.input_tokens = 1840`, `output_tokens = 212` — the counts from the *first* inference call only, because the runtime had attached usage to the agent span at the point the first completion returned and never revised it. The tool result arrived at 74s. The runtime issued a second inference call to synthesize the answer. That call's span was created with the original trace context but as a *sibling* of the timed-out agent span (the parent had already ended, so the runtime's span processor reparented to the trace root). Its usage: `input_tokens = 2910`, `output_tokens = 388`. Three observable consequences: 1. **Double counting in naive aggregation.** A dashboard summing `gen_ai.usage.input_tokens` across all spans in the trace reported 1840 + 2910 = 4750. The actual model input consumed was 4750 across two calls — correct in total, but the agent span alone under-reported by 61%, and any per-agent-span metric (e.g., `avg tokens per invoke_agent`) was wrong. 2. **Orphaned usage.** The second inference span had no `invoke_agent` ancestor. Trace-based cost attribution that walks `invoke_agent` → children missed 2910 tokens entirely. The tokens existed in the trace but belonged to no logical turn. 3. **Cached-token mismatch.** The second call reported `gen_ai.usage.input_tokens.cached = 1600` (the tool result plus prior context was cache-hit). The agent span's cached count was 0. Any cache-efficiency ratio computed at the agent-span level was meaningless. The span *schema* was valid throughout. Every attribute conformed. The failure was purely in the temporal binding of usage to span lifecycle. ## Condition of Validity The invariant "an agent span's cumulative usage is authoritative for the turn" holds only under the conjunction: - Every inference call in the turn completes before the agent span ends, **and** - The runtime mutates the agent span's usage attributes on each child completion before export, **and** - No inference call is issued after the agent span's `end_time`. Break any one and the agent span's usage is a *partial* record, not an aggregate. The GenAI conventions do not require the runtime to signal which case applies. There is no `gen_ai.usage.partial = true` attribute, and adding one is not sanctioned by the spec — which means a consumer cannot distinguish "agent span usage is the total" from "agent span usage is a lower bound" without reconstructing the trace topology and checking for reparented inference spans. The condition of validity therefore cannot be verified from the agent span in isolation. It requires trace-level reconciliation: for each `invoke_agent` span, sum `gen_ai.usage.*` over all inference spans whose `trace_id` matches and whose `start_time` falls within `[agent.start_time, agent.end_time + grace]`, then compare to the agent span's own attributes. If they differ, the agent span is partial. ## Decision Boundary The runtime must choose, at the moment a tool call exceeds the turn deadline, between two accounting postures: - **Extend-and-mutate:** keep the agent span open past its deadline (violating the deadline's purpose but preserving the aggregation invariant), mutating usage on each late inference call. - **Close-and-emit-partial:** end the agent span at the deadline with a partial usage record, accept that late inference calls become trace-root siblings, and require consumers to reconcile. The boundary is crossed when `tool_latency_p99 > turn_deadline` for any tool in the agent's capability set. Below that threshold, extend-and-mutate is safe and the invariant holds. Above it, extend-and-mutate is a resource leak (spans held open indefinitely on a hung tool), so close-and-emit-partial is forced — and the reconciliation burden shifts to every downstream consumer. A correct implementation tags the agent span at close time with a non-standard but necessary marker (e.g., `gen_ai.usage.finalized = false` or a span event `usage.partial`), and emits late inference spans with an explicit link (`SpanLink`) back to the closed agent span rather than relying on reparenting. The link is the only mechanism in OpenTelemetry that preserves the logical parent relationship across a closed parent. Without it, the late usage is orphaned by construction. ## Operational Effect Downstream cost and quality systems that trust agent-span usage as authoritative will systematically under-count tokens for exactly the turns that are most expensive — long tool waits correlate with complex tasks, which correlate with large context. The bias is not random; it selects for the worst-case turns. Budget alarms keyed to agent-span usage will not fire on the turns that blow the budget. Cache-efficiency dashboards will report artificially low hit rates because cached tokens on late calls are invisible at the agent level. The guardrail is a reconciliation pass, not a schema change: every consumer of `gen_ai.usage.*` at the agent level must treat it as a lower bound unless the trace contains no inference spans outside the agent's time window. The runtime's obligation is to make that check possible — via span links on late calls and an explicit partial marker on the agent span — because the spec does not, and cannot, encode the temporal binding. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when an agent span's usage cannot be reconciled with child inference spans.""" pass @dataclass class InferenceSpan: trace_id: str start_time: float input_tokens: int output_tokens: int cached_tokens: int = 0 linked_agent_span_id: Optional[str] = None @dataclass class AgentSpan: trace_id: str span_id: str start_time: float end_time: float input_tokens: int output_tokens: int cached_tokens: int = 0 finalized: bool = True child_inference: list = field(default_factory=list) def reconcile_agent_usage(agent: AgentSpan, all_spans: list, grace: float = 120.0) -> dict: """ Reconcile an agent span's declared usage against all inference spans that belong to the same logical turn (same trace, within time window, or linked). Raises if a partial agent span is treated as authoritative. """ in_window = [ s for s in all_spans if s.trace_id == agent.trace_id and agent.start_time <= s.start_time <= agent.end_time + grace ] linked = [ s for s in all_spans if s.linked_agent_span_id == agent.span_id ] candidates = {id(s): s for s in in_window + linked}.values() summed_in = sum(s.input_tokens for s in candidates) summed_out = sum(s.output_tokens for s in candidates) summed_cached = sum(s.cached_tokens for s in candidates) declared = (agent.input_tokens, agent.output_tokens, agent.cached_tokens) reconciled = (summed_in, summed_out, summed_cached) if declared != reconciled: if agent.finalized: raise UsageReconciliationError( f"Agent span {agent.span_id} declared finalized usage {declared} " f"but trace contains {reconciled} across {len(list(candidates))} " f"inference spans; agent usage is a lower bound, not authoritative." ) return { "authoritative": False, "declared": declared, "reconciled": reconciled, "orphaned_calls": len(linked), } return { "authoritative": True, "declared": declared, "reconciled": reconciled, "orphaned_calls": 0, } ```