# Where must an instance reconcile OpenTelemetry GenAI token accounting when a tool-call span is re-parented mid-execution? **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) and that can re-parent or re-emit spans when a tool call is retried, resumed from checkpoint, or handed off to a sub-agent. Does not apply to single-shot inference calls with no tool loop and no span mutation. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* measurements of a single model invocation, and `gen_ai.operation.name` as the discriminator between `chat`, `execute_tool`, and `invoke_agent`. The convention implicitly assumes a span is emitted exactly once, by the component that performed the work, with token counts that belong to that span's own operation. That assumption breaks the moment an agent re-parents a tool-call span. Re-parenting is not a cosmetic trace-tree edit: it moves the span under a new `invoke_agent` / `execute_tool` parent, and downstream collectors that aggregate tokens by walking parent-child edges will now sum the same `gen_ai.usage.*` values into *both* the old and new ancestor chains. The distinction that matters operationally is between **token attribution** (which span *owns* the count) and **token aggregation** (which ancestor *sums* it). The conventions specify the former and are silent on the latter, so re-parenting silently double-counts. ## What Was Observed A tool-calling agent executed `search_corpus`. The `execute_tool` span carried `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search_corpus`, and — incorrectly but commonly — the token usage of the *model call that decided to invoke the tool*: `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=96`. The tool call timed out at the transport layer. The runtime retried it under a `resume` path and, because the retry was orchestrated by a different supervisor instance, re-parented the span: the original span kept its `trace_id` but its `parent_span_id` was rewritten from the planning agent's span to the supervisor's `invoke_agent` span. The retry *also* re-emitted a fresh `execute_tool` span with the same `gen_ai.tool.name` and a *new* model-decision token count (`input_tokens=2103`). Three observable consequences: 1. **Double attribution across the trace tree.** A collector summing `gen_ai.usage.input_tokens` over all descendants of the root reported 3943 input tokens for a task that consumed 2103 — the original 1840 persisted on the re-parented span and the retry added 2103. 2. **Tool spans masquerading as model spans.** Because the `execute_tool` span carried `gen_ai.usage.*`, any consumer that filters "spans with token usage" to compute cost treated a tool execution as a billable model invocation. The `gen_ai.operation.name` discriminator was ignored by the aggregator, which is the common case. 3. **Orphaned usage on resume.** The checkpointed state recorded `span_id` of the pre-timeout span. On resume, the runtime emitted the retry span but the checkpoint still referenced the dead span id; the resumed `invoke_agent` span's `gen_ai.usage.*` was never populated because the runtime assumed the child tool span "carried" the tokens. Net: the resumed agent invocation reported zero tokens while its child reported two sets. ## Condition of Validity The double-count is only bounded — not eliminated — under the following conjunction, and collapses to unbounded double-counting when any conjunct fails: - The `execute_tool` span MUST NOT carry `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Per the conventions, usage belongs to the model-invocation span (`chat`), not the tool span. The token cost of *deciding* to call a tool belongs to the `chat` span that produced the tool-call; the tool span's own cost is `gen_ai.tool.call.*` duration, not tokens. - Re-parenting MUST preserve a stable `gen_ai.tool.call.id` (or equivalent idempotency key) so that a collector can deduplicate a re-emitted span against its predecessor by key rather than by span id. - The resumed `invoke_agent` span MUST recompute its own `gen_ai.usage.*` from the model calls it actually performed after resume, never inherit them from the checkpointed child. When the tool span carries usage attributes (as observed), the invariant is violated at emit time and no downstream dedup can recover correct attribution, because the two usage values are attached to spans with different `span_id` and only one shared `gen_ai.tool.name`. ## Decision Boundary The boundary is: **does the re-parenting event move a span that owns `gen_ai.usage.*`, or a span that does not?** - If the re-parented span is a `chat` span that legitimately owns usage, re-parenting is safe *only if* the collector aggregates by `gen_ai.operation.name` and the span is not re-emitted. Re-emission without idempotency key ⇒ double count. - If the re-parented span is an `execute_tool` span, it must carry no `gen_ai.usage.*`; if it does, the runtime is already non-conformant and re-parenting compounds the error. - If the resume path re-emits a span, the decision is governed by `gen_ai.tool.call.id` presence: present ⇒ dedupe and keep the latest; absent ⇒ the runtime must *not* re-parent, and must instead close the original span with `status=ERROR` and open a sibling under the same parent. The guardrail: a span may be re-parented only if it carries no `gen_ai.usage.*` attributes, OR it carries a stable idempotency key that the collector uses to collapse duplicates before aggregation. Any span with usage attributes and no idempotency key is non-re-parentable. ## Operational Effect Enforcing the boundary changes three things: (1) cost dashboards stop inflating on retries, because tool spans no longer contribute tokens and re-emitted chat spans collapse by key; (2) resume paths must explicitly re-derive `gen_ai.usage.*` on the resumed `invoke_agent` span from post-resume model calls, which surfaces the previously silent zero-token resume; (3) the trace tree becomes a faithful attribution graph rather than a mutable one, because re-parenting is gated on the absence of owned usage. The residual risk is collectors written against the pre-convention assumption that "any span with usage counts" — those must be migrated to filter on `gen_ai.operation.name` before re-parenting is enabled anywhere in the fleet. ```python class GenAiSpanAttributionError(RuntimeError): """Raised when a span re-parent/re-emit would corrupt GenAI token attribution.""" pass USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") def assert_reparentable(span: dict, *, idempotency_key: str | None) -> None: """Guard: a span may be re-parented only if it owns no usage, or carries a dedup key.""" owns_usage = any(k in span.get("attributes", {}) for k in USAGE_KEYS) op = span.get("attributes", {}).get("gen_ai.operation.name") if owns_usage and op == "execute_tool": raise GenAiSpanAttributionError( f"execute_tool span {span['span_id']} carries gen_ai.usage.*; " "usage belongs to the chat span that emitted the tool call. " "Strip usage before re-parenting." ) if owns_usage and not idempotency_key: raise GenAiSpanAttributionError( f"span {span['span_id']} owns gen_ai.usage.* but has no idempotency key; " "re-parenting would double-count on aggregation. " "Close with status=ERROR and open a sibling instead." ) def reparent(span: dict, new_parent_id: str, *, idempotency_key: str | None = None) -> dict: assert_reparentable(span, idempotency_key=idempotency_key) span = dict(span) span["parent_span_id"] = new_parent_id return span def aggregate_usage(spans: list[dict]) -> dict[str, int]: """Sum usage only over spans that legitimately own it, deduped by idempotency key.""" seen: set[str] = set() total = {k: 0 for k in USAGE_KEYS} for s in spans: if s.get("attributes", {}).get("gen_ai.operation.name") == "execute_tool": continue key = s.get("attributes", {}).get("gen_ai.tool.call.id") or s["span_id"] if key in seen: continue seen.add(key) for k in USAGE_KEYS: total[k] += int(s.get("attributes", {}).get(k, 0) or 0) return total ```