# In what scenarios must an instance reject a GenAI tool-call span whose token accounting is split across a parent-agent envelope and a child-tool envelope **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) where a single logical tool invocation is represented as a nested parent (agent/`invoke_agent`) span and child (`execute_tool`) span, and where token usage is attributed via `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to flat single-span agents, or to runtimes that aggregate usage only at the trace root after export. ## Core Distinction The GenAI semantic conventions define usage attributes as *per-model-invocation* quantities: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are meant to describe the tokens consumed by the model call that the span represents. They are **not** defined as additive counters that roll up across a span tree. This distinction is the entire failure surface. An agent that performs a tool call typically makes *two* model invocations around it: one to decide to call the tool (reasoning tokens + the tool-call emission), and one to interpret the tool result and continue. A naive instrumentation layer frequently does one of two things: 1. Attributes the *decision* invocation's tokens to the parent `invoke_agent` span, then attributes the *interpretation* invocation's tokens to the child `execute_tool` span — because the tool span is opened around the tool execution and the follow-up model call happens while it is "current" in the context manager. 2. Attributes the *entire* round-trip token cost to the parent and *also* records the tool's own internal model cost (if the tool itself invokes an LLM) on the child. Both produce a trace where summing `gen_ai.usage.*` over all spans double-counts or mis-attributes tokens. A backend that computes cost by `sum(usage over spans)` will overbill; a backend that computes cost by `root.usage` will underbill. The invariant that breaks is: **for any trace, the per-span usage attributes must be a partition of the true model-token consumption, not an overlapping cover.** ## What Was Observed A three-step agent (plan → `search_docs` tool → synthesize) exported a trace with this span tree: ``` invoke_agent (gen_ai.usage.input_tokens=1840, output_tokens=210) └── execute_tool search_docs (gen_ai.usage.input_tokens=1840, output_tokens=95) └── chat gpt-4o (gen_ai.usage.input_tokens=1840, output_tokens=95) ``` The `execute_tool` span inherited the parent's `input_tokens` value because the instrumentor copied the *current* model-call context onto the tool span at `start_as_current_span` time, and the tool span's context manager was still active when the follow-up `chat` span opened. The `chat` child then recorded the *same* input tokens again. Summing usage across the trace yields `1840 × 3` input tokens against a true consumption of `1840` (prompt) `+ ~95` (tool-result re-injection) for the decision turn, plus a separate synthesis turn not shown. The failure is silent: every span validates against the schema, every attribute is a non-negative integer, and the trace renders cleanly in Jaeger. Only a reconciliation against the provider's billing API exposes the 3× discrepancy. In a second incident, the inverse occurred: the tool span was opened *before* the decision model call returned, so the decision tokens landed on the child and the parent `invoke_agent` span carried `0` usage — a downstream cost dashboard treated the agent as free. The trigger condition is precise: **a tool span is made "current" (entered into the OTel context) across a model invocation boundary that belongs to the parent's reasoning loop.** This happens whenever the tool executor and the follow-up model call share a context manager, which is the default shape of `with tracer.start_as_current_span("execute_tool"): result = tool(); next = llm(result)`. ## Condition of Validity The following invariant must hold for a trace to be admissible for cost accounting: > For each span `S` carrying `gen_ai.usage.*`, those attributes describe exactly the model invocation whose `gen_ai.request.model` and `gen_ai.response.id` are recorded on `S` (or on its nearest descendant `chat` span if `S` is a wrapper). No two spans in a trace may carry usage attributes derived from the same underlying model response, and the union of usage across spans must equal the provider's reported consumption for the trace. This is checkable. The `gen_ai.response.id` (or `response.model` + a provider request id) is the deduplication key. If two spans in a trace share a `gen_ai.response.id` and both carry nonzero `gen_ai.usage.input_tokens`, the trace violates the invariant and must be rejected rather than aggregated. A secondary condition: an `execute_tool` span **must not** carry `gen_ai.usage.*` at all unless the tool itself performed a model invocation (e.g., a tool that calls an LLM internally). The convention's tool-span attributes are `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.type`; usage belongs on the `chat`/`invoke_agent` span that actually hit the model. Propagating usage onto the tool wrapper is a category error that the schema does not forbid, which is exactly why it goes undetected. ## Decision Boundary The runtime must draw a hard line between **propagating context** (trace id, span id, baggage, `gen_ai.conversation.id`) and **propagating accounting** (usage, cost, token budget). Context propagation across the tool boundary is correct and necessary. Accounting propagation is not. Concretely: - Enter the `execute_tool` span, run the tool, **exit the span**, then open the follow-up `chat` span as a *sibling* under `invoke_agent`, not as a child of `execute_tool`. The tool span's lifetime must not enclose any model invocation belonging to the parent's loop. - Never copy `gen_ai.usage.*` from the active span onto a newly opened span. Usage is set only by the code path that received the model response, using values from that response object, never from ambient context. - On export, run a dedup pass keyed on `gen_ai.response.id`: if a response id appears on more than one span with usage, drop usage from all but the innermost `chat` span and emit a `gen_ai.usage.reconciled=true` marker plus an anomaly event. If a response id is missing entirely (some providers omit it), fall back to `(trace_id, gen_ai.request.model, span start timestamp bucket)` and flag for manual reconciliation. The boundary is: **context flows down, accounting flows up exactly once.** Any instrumentation that lets accounting flow sideways (parent → child) or twice (child re-records parent's usage) is out of policy. ## Operational Effect Without the invariant enforced at export, the observable consequences are: 1. **Cost dashboards drift multiplicatively with tool-call depth.** A 5-tool agent over-reports by roughly the number of spans that inherited usage, not by a constant factor, so the error grows with agent complexity and is invisible in per-trace spot checks. 2. **Budget enforcement misfires.** A runtime that halts an agent when `sum(usage) > budget` will terminate a healthy agent at ~1/N of its true budget when N spans share usage, or never terminate when usage lands on a zeroed parent. The latter is the dangerous case: token-budget exhaustion is the guardrail against runaway loops, and a zeroed parent disables it. 3. **Replay and audit reconciliation fails.** Post-hoc replay of a trace to reconstruct the agent's reasoning sees duplicated prompt tokens and cannot distinguish "the model saw the prompt twice" from "the instrumentor copied the attribute," so incident forensics misattribute divergence to prompt duplication. The guardrail that bounds all three is the export-time dedup pass keyed on `gen_ai.response.id`, backed by a hard rejection of any span that carries usage without a corresponding response identifier. Rejection is preferable to silent reconciliation because a rejected trace is a signal that the instrumentor's context discipline is broken and will produce further bad traces; a reconciled trace hides the bug and lets it compound. ```python from dataclasses import dataclass class UsageAttributionError(RuntimeError): """Raised when a GenAI trace violates the single-attribution invariant.""" @dataclass(frozen=True) class SpanUsage: span_id: str response_id: str | None input_tokens: int output_tokens: int is_tool_wrapper: bool def validate_usage_partition(spans: list[SpanUsage]) -> dict[str, int]: """ Enforce: each model response's usage appears on exactly one non-wrapper span. Returns the reconciled total. Raises on violation rather than aggregating. """ seen: dict[str, str] = {} # response_id -> span_id that owns the usage total_input = 0 total_output = 0 for s in spans: has_usage = s.input_tokens > 0 or s.output_tokens > 0 if not has_usage: continue if s.is_tool_wrapper: raise UsageAttributionError( f"tool-wrapper span {s.span_id} carries gen_ai.usage.* " f"(input={s.input_tokens}, output={s.output_tokens}); " f"usage must live on the chat/invoke_agent span that hit the model" ) if s.response_id is None: raise UsageAttributionError( f"span {s.span_id} carries usage but has no gen_ai.response.id; " f"cannot deduplicate or reconcile against provider billing" ) if s.response_id in seen: raise UsageAttributionError( f"response {s.response_id} usage attributed twice: " f"already on span {seen[s.response_id]}, repeated on {s.span_id}" ) seen[s.response_id] = s.span_id total_input += s.input_tokens total_output += s.output_tokens return {"input_tokens": total_input, "output_tokens": total_output} def reconcile_or_reject(spans: list[SpanUsage], provider_input: int) -> dict[str, int]: totals = validate_usage_partition(spans) if totals["input_tokens"] != provider_input: raise UsageAttributionError( f"trace usage {totals['input_tokens']} != provider-reported " f"{provider_input}; partition invariant broken upstream" ) return totals ```