# What happens when an instance commits an OpenTelemetry GenAI span before tool-call resolution: attribute-set divergence across parent/child spans and the token-accounting double-count **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) where a parent agent/invocation span and its child tool-call spans are written by different code paths, processes, or SDK versions. Does not apply to single-span, single-process instrumentation where the parent span's attributes are finalized after all children close. ## Core Distinction There are two distinct ways an agent span can "finish," and only one of them is visible to the OpenTelemetry collector: 1. **Logical completion** — the agent loop has decided it is done and the span object is `.end()`-ed. At this instant the attribute set is frozen and shipped. 2. **Semantic completion** — every child tool-call span has resolved, and the aggregate token usage for the turn is actually known. The GenAI conventions assume these coincide. In real agent runtimes they routinely do not, because the agent span is often ended by the orchestration loop *before* the last tool call's async result has been reconciled back into the parent's `gen_ai.usage.*` counters and `gen_ai.tool.name` list. The result is a parent span whose frozen attribute set describes an earlier state of the turn than its own children. This is not a clock-skew problem and not a sampling problem; it is an **attribute-set divergence** at the parent/child boundary, and it produces two concrete downstream corruptions: token double-counting and orphaned tool-call children. ## What Was Observed A tool-using agent loop (`plan → tool_call → observe → plan`) was instrumented so that: - The **agent span** (`gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name=...`) is opened at turn start and ended by the orchestration coroutine when the model returns a message with no further tool calls. - Each **tool-call span** (`gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=...`) is opened inside the tool executor and ended when the tool returns. - The **chat span** (`gen_ai.operation.name=chat`) is opened per model call and records `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` for that call. The failure trace, reproduced deterministically on a 4-tool turn: ``` t0 agent_span.start() t1 chat_span_1.start() ... chat_span_1.end() usage={in:1800, out:120} t2 tool_span_A.start() ... tool_span_A.end() t3 chat_span_2.start() ... chat_span_2.end() usage={in:2400, out:90} t4 tool_span_B.start() ... tool_span_B.end() t5 model returns final message (no tool calls) t6 agent_span.end() <-- FROZEN HERE t7 tool_span_B's usage reconciliation callback fires (async), attempts to add gen_ai.usage.* into agent_span --> span already ended, attributes dropped ``` Two observable corruptions followed: 1. **Token double-count.** The chat spans each carry their own `gen_ai.usage.*`. The agent span, per the convention's intent, is supposed to carry the *turn aggregate*. Because the aggregate was written at `t6` from a snapshot taken at `t5` that had not yet absorbed the final tool's follow-up model call, dashboards that sum `gen_ai.usage.input_tokens` across *all* spans in a trace (a common and tempting query) counted the chat spans plus a partial agent aggregate, over-reporting by the amount of the last chat call. Conversely, dashboards that read *only* the agent span under-reported. Neither query was wrong per the convention; the convention had been violated by ordering. 2. **Orphaned tool-call child.** `tool_span_B` was emitted with a valid `parent_span_id` pointing at the agent span, but the agent span's attribute set — frozen at `t6` — did not include `gen_ai.tool.name` for B in any aggregate field. A trace-based auditor that reconstructs "which tools did this agent invoke" by reading the parent span's attributes concluded the agent used one tool. The child span existed and was reachable by trace ID, but the parent's *semantic* description of the turn was incomplete. The key observation: **the trace was structurally valid** (correct parent/child links, no missing spans, monotonic timestamps) while being **semantically false** at the aggregate level. OpenTelemetry's structural invariants do not protect the GenAI semantic invariants. ## Condition of Validity The divergence is bounded and predictable under the following condition: > A parent GenAI agent span's attribute set is only semantically complete if, at the moment `.end()` is called, every child span that contributes to `gen_ai.usage.*` or to the aggregate tool inventory has already ended *and* its contribution has been synchronously folded into the parent. Equivalently, the invariant that must hold is: ``` ∀ child ∈ descendants(agent_span): child.end_time ≤ agent_span.attribute_freeze_time AND child.usage_contribution ∈ agent_span.usage_at_freeze ``` This is violated whenever the runtime uses one of three common but non-obvious patterns: - **Fire-and-forget tool execution** where the executor returns a handle and the result is reconciled on a later microtask, after the loop has already decided the turn is over. - **Streaming chat spans** where `gen_ai.usage.output_tokens` is only known after the stream closes, and the agent loop ends the parent on the "done" sentinel from the model rather than on stream close. - **Parallel tool fan-out** where N tool spans are opened concurrently and the agent span is ended by whichever branch sees the "no more tool calls" condition first — a classic baton race where the parent ends before the slowest sibling child. It does **not** apply to runtimes that buffer the full turn's usage in memory and write the agent span last, single-threaded, after all children are joined. Those runtimes are correct by construction and this record is silent on them. ## Decision Boundary The boundary is not "does the span have the right attributes" but **"is the parent's attribute set a function of the complete child set, or of a prefix of it?"** - If the runtime can guarantee the parent is the *last* span in the turn to end (children joined before parent `.end()`), the convention's aggregate semantics hold and no guardrail is needed. - If the runtime cannot guarantee that ordering — because tool results are async, streams close late, or siblings race — then the parent must **not** be trusted as the source of truth for aggregate token usage or tool inventory. Instead, the decision boundary is: *derive aggregates from the child spans by trace-ID join at query time, and treat the parent's `gen_ai.usage.*` as advisory only.* The subtle trap: the convention *encourages* writing aggregates on the agent span, so teams write them, and then build dashboards that read them, without realizing the write was racy. The decision boundary is therefore a **query-side** boundary, not just an emit-side one: any consumer that trusts parent aggregates must first verify the parent ended after all children. If it cannot, it must fall back to child-join semantics. ## Operational Effect Downstream, the divergence manifests as three concrete operational symptoms, each of which looks like a different bug: 1. **Cost dashboards drift upward over long turns.** Turn-level cost computed from parent spans under-reports on multi-tool turns; cost computed from all-span sums over-reports because chat spans and the parent aggregate overlap. The drift is proportional to the number of tool calls per turn, so it is invisible on single-tool traces and severe on long agentic runs. 2. **Tool-usage audits miss the last tool.** Auditors reconstructing tool inventory from parent attributes systematically drop the final tool of every turn — exactly the tool most likely to be the "final action" and therefore the most operationally interesting one. 3. **Replay/verification mismatches.** When an auditor agent replays a trace to verify an agent's claimed actions, it reads the parent's frozen tool list and concludes the agent did *less* than it did. The child span proves otherwise, but only if the auditor joins by trace ID rather than descending from the parent's attributes. This is a verification-replay discrepancy caused purely by span-end ordering. The guardrail that bounds it is a **parent-span finalization barrier**: the agent span must be ended only after a join over all child spans completes, and the aggregate `gen_ai.usage.*` must be computed from the joined child set at that moment, not from a live counter read at an arbitrary point. Where a barrier is impossible (streaming, fire-and-forget), the runtime must mark the parent's aggregates as provisional (e.g., a `gen_ai.usage.provisional=true` attribute or simply omit them) and force consumers onto child-join semantics. The invariant to enforce: **no parent GenAI span may carry aggregate usage or tool inventory unless its end-time is ≥ the max end-time of its contributing children.** ```python import time from dataclasses import dataclass, field class SpanFinalizationError(RuntimeError): """Raised when a GenAI agent span is ended before its contributing child spans (chat/tool) have resolved and been folded into the parent's aggregate attributes.""" @dataclass class GenAISpan: name: str operation: str # "invoke_agent" | "chat" | "execute_tool" start_time: float = field(default_factory=time.monotonic) end_time: float | None = None parent: "GenAISpan | None" = None children: list["GenAISpan"] = field(default_factory=list) attributes: dict = field(default_factory=dict) def end(self): self.end_time = time.monotonic() self.attributes["_frozen_at"] = self.end_time def add_child(self, child: "GenAISpan"): child.parent = self self.children.append(child) def finalize_agent_span(agent: GenAISpan, aggregate_usage: dict, tool_inventory: list[str]): """Enforce the parent-span finalization barrier before freezing the agent span's aggregate GenAI attributes.""" if agent.operation != "invoke_agent": raise SpanFinalizationError( f"finalize_agent_span called on non-agent span operation={agent.operation!r}" ) # Barrier check: every contributing child must have ended, and the # parent's freeze time must be >= the max child end time. unresolved = [c.name for c in agent.children if c.end_time is None] if unresolved: raise SpanFinalizationError( f"agent span {agent.name!r} attempted to end with unresolved " f"children {unresolved}; aggregate gen_ai.usage.* would describe " f"a prefix of the turn, not the full turn" ) max_child_end = max((c.end_time for c in agent.children), default=agent.start_time) freeze_time = time.monotonic() if freeze_time < max_child_end: raise SpanFinalizationError( f"agent span {agent.name!r} freeze_time {freeze_time:.6f} precedes " f"max child end_time {max_child_end:.6f}; token aggregate would " f"double-count or under-count against child chat spans" ) # Fold child contributions into the parent, then freeze. agent.attributes["gen_ai.usage.input_tokens"] = aggregate_usage.get("input_tokens", 0) agent.attributes["gen_ai.usage.output_tokens"] = aggregate_usage.get("output_tokens", 0) agent.attributes["gen_ai.tool_names"] = sorted(set(tool_inventory)) agent.end() # Post-condition: parent must end at or after every child. for c in agent.children: if agent.end_time < c.end_time: raise SpanFinalizationError( f"post-condition violated: child {c.name!r} ended after parent " f"{agent.name!r}; trace is structurally valid but semantically false" ) return agent ```