# Under what conditions must an instance reject a GenAI span whose token-accounting attributes were inherited across a tool-call boundary **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) and that wraps tool execution inside a parent LLM-invocation span. Does not cover pure tracing of non-LLM RPCs, nor span export/transport concerns (OTLP retry, batching) except where they interact with attribute inheritance. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.*` as attributes of a *model invocation* — the token cost of a single request/response pair against a specific model. They are **not** span-scoped cumulative counters, and they are **not** inheritable. The failure mode here is architectural: an agent runtime creates a child span for tool execution, and because the child is nested under the parent LLM span (or because a shared `Span`/`Context` object is reused across the tool-call boundary), the child inherits the parent's `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` through resource/attribute propagation or through a naive `set_attribute` merge. The resulting trace reports the tool call as having consumed tokens it never consumed, and — because the parent span's usage is now double-counted across N children — the aggregate `sum(gen_ai.usage.output_tokens)` across the trace is inflated by a factor of (1 + number of tool children). The distinction that matters operationally: **token accounting is a leaf property of the invocation that produced the tokens, not a property of the span tree.** Any runtime that treats it as inherited state will produce cost telemetry that is wrong by construction, and the error is *silent* — the trace is structurally valid, spans are well-formed, and no validator complains because every attribute is individually within schema. ## What Was Observed A multi-step agent executing a `search → read → summarize` chain emitted the following trace (abridged, one representative run): ``` span: chat gpt-4o (parent, gen_ai.operation.name=chat) gen_ai.usage.input_tokens = 1842 gen_ai.usage.output_tokens = 210 ├── span: execute_tool search (gen_ai.operation.name=execute_tool, gen_ai.tool.name=search) │ gen_ai.usage.input_tokens = 1842 <-- inherited │ gen_ai.usage.output_tokens = 210 <-- inherited ├── span: execute_tool read (gen_ai.operation.name=execute_tool, gen_ai.tool.name=read) │ gen_ai.usage.input_tokens = 1842 <-- inherited │ gen_ai.usage.output_tokens = 210 <-- inherited └── span: execute_tool summarize (...) gen_ai.usage.input_tokens = 1842 <-- inherited gen_ai.usage.output_tokens = 210 <-- inherited ``` Downstream cost aggregation summed `gen_ai.usage.output_tokens` across all spans in the trace and reported 210 × 4 = 840 output tokens for a single-turn interaction that actually consumed 210. The billing dashboard over-reported by 4× for this trace, and the ratio scaled with tool-call fan-out — a 12-tool agent run over-reported by 13×. The inheritance was traced to a `ContextVar`-held `Span` object whose `set_attribute` was called once at invocation start and then re-read by the tool-wrapper decorator, which copied *all* current span attributes onto the child before adding `gen_ai.tool.name`. Two secondary observations: 1. The over-reporting was **non-deterministic in magnitude** because tool-call fan-out is itself model-driven. The same prompt produced 3, 7, or 11 tool calls across runs, so the inflation factor varied run to run with no code change. 2. The inflated spans passed every schema-level check. `gen_ai.usage.input_tokens` is typed as an integer and was an integer; `gen_ai.operation.name` was a valid enum value. The only detector that caught it was a cross-span invariant: *a span with `gen_ai.operation.name=execute_tool` must not carry `gen_ai.usage.*` unless the tool itself invoked a model.* ## Condition of Validity The invariant is only well-defined — and the rejection is only correct — under the following conditions. If any fail, the span may legitimately carry usage attributes and must not be rejected: - **Condition A — Operation classification.** The span's `gen_ai.operation.name` is `execute_tool` (or equivalent tool-execution operation) *and* the tool implementation did not itself perform a model invocation. If the tool wraps an LLM call (e.g., a `summarize` tool that calls a model), the child span legitimately owns its own `gen_ai.usage.*` — but those must be the *tool's* usage, not the parent's. The discriminator is provenance, not presence. - **Condition B — Value identity with parent.** The suspect child's `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are *bit-identical* to the parent invocation span's values. Coincidental equality (a tool that happens to consume exactly 1842 tokens) is astronomically unlikely but must be excluded by requiring the parent to be the *nearest* `chat`/`text_completion` ancestor, not any ancestor. - **Condition C — No override marker.** The runtime did not explicitly set the child's usage attributes from a measured source. If the tool-wrapper sets usage from an actual measurement (even if the value equals the parent's), the span is valid; the failure is *inheritance*, not *equality*. This requires the emitter to tag measured usage distinctly (see Decision Boundary). - **Condition D — Parent is a model invocation.** The inheritance check only applies when the parent span carries `gen_ai.operation.name ∈ {chat, text_completion, generate_content}`. A tool span nested under another tool span is a different case (tool-chaining) and the parent has no usage to inherit. ## Decision Boundary The boundary is between **"usage attribute present"** and **"usage attribute inherited."** The GenAI conventions give no explicit marker for the latter, so the runtime must impose one. The decision procedure at span-close time: 1. If `gen_ai.operation.name != execute_tool` → do not apply this check; emit normally. 2. Walk to the nearest ancestor with `gen_ai.operation.name ∈ {chat, text_completion, generate_content}`. If none → no inheritance possible; emit normally. 3. If the child's `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are both present and both equal the ancestor's, **and** the child carries no `gen_ai.usage.source = "measured"` marker (or equivalent provenance attribute the runtime defines) → the span is an inheritance artifact. Reject: strip the usage attributes, emit the span, and record a `genai.usage.inherited_rejected` counter. 4. If the child carries the measured marker → emit with usage; the tool genuinely invoked a model. 5. If the child's usage differs from the ancestor's but the child is a non-model tool → this is a *different* violation (fabricated usage); reject and flag as `genai.usage.unattributed`, which is a harder error than inheritance because it implies the emitter invented numbers. The boundary is deliberately *not* "reject any tool span with usage attributes" — that would break legitimate model-invoking tools (Condition A) and would suppress real telemetry. The boundary is provenance: inherited vs. measured. ## Operational Effect Enforcing the boundary changes three things: - **Cost telemetry becomes additive-correct.** With inheritance rejected, `sum(gen_ai.usage.output_tokens)` over a trace equals the true model cost regardless of tool fan-out. Without it, the sum is a function of the model's own tool-call decisions — an unstable metric that cannot be alerted on. - **The rejection must be non-fatal to the trace.** Stripping attributes and emitting the span (rather than dropping it) preserves the causal structure that downstream latency and error analysis depend on. Dropping the span would create orphaned children and break parent-child integrity — a worse failure than the mis-accounting. - **The counter is the real signal.** `genai.usage.inherited_rejected` is the operational metric: a nonzero rate means the runtime's span-context propagation is leaking attributes across the tool boundary, which is a code defect in the wrapper, not a data problem. Alert on rate, not on individual rejections. The guardrail is therefore twofold: a **strip-and-emit** transform at the span processor, and a **provenance marker** (`gen_ai.usage.source`) that the tool wrapper must set explicitly when it measures usage. Without the marker, the processor cannot distinguish inheritance from a legitimate model-invoking tool, and the boundary collapses to a heuristic. ```python from __future__ import annotations from dataclasses import dataclass from typing import Optional MODEL_OPS = frozenset({"chat", "text_completion", "generate_content"}) TOOL_OP = "execute_tool" USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") SOURCE_KEY = "gen_ai.usage.source" MEASURED = "measured" class InheritedUsageError(RuntimeError): """Raised when a tool span's usage attributes were inherited from a model ancestor.""" class FabricatedUsageError(RuntimeError): """Raised when a non-model tool span carries usage it cannot attribute to a measurement.""" @dataclass class Span: name: str operation: str attributes: dict parent: Optional["Span"] = None def get(self, key: str): return self.attributes.get(key) def _nearest_model_ancestor(span: Span) -> Optional[Span]: node = span.parent while node is not None: if node.get("gen_ai.operation.name") in MODEL_OPS: return node node = node.parent return None def validate_usage_provenance(span: Span) -> Optional[str]: """ Returns None if the span's usage attributes are valid. Raises InheritedUsageError / FabricatedUsageError otherwise. Stripping is the caller's responsibility; this function only decides. """ if span.get("gen_ai.operation.name") != TOOL_OP: return None usage_present = [k for k in USAGE_KEYS if span.get(k) is not None] if not usage_present: return None ancestor = _nearest_model_ancestor(span) measured = span.get(SOURCE_KEY) == MEASURED if ancestor is None: if measured: return None raise FabricatedUsageError( f"tool span {span.name!r} carries {usage_present} with no model ancestor " f"and no {SOURCE_KEY}={MEASURED!r} marker" ) identical = all( span.get(k) is not None and span.get(k) == ancestor.get(k) for k in USAGE_KEYS ) if identical and not measured: raise InheritedUsageError( f"tool span {span.name!r} inherited {usage_present} from ancestor " f"{ancestor.name!r} (values {ancestor.get(USAGE_KEYS[0])}/" f"{ancestor.get(USAGE_KEYS[1])}); no measured marker present" ) if not identical and not measured: raise FabricatedUsageError( f"tool span {span.name!r} has usage {usage_present} that differs from " f"ancestor {ancestor.name!r} but is not marked measured" ) return None def process_span(span: Span) -> Span: """Strip inherited/fabricated usage, emit the (structurally intact) span.""" try: validate_usage_provenance(span) return span except (InheritedUsageError, FabricatedUsageError): for k in USAGE_KEYS: span.attributes.pop(k, None) span.attributes["genai.usage.rejected"] = "inherited_or_unattributed" return span # --- exercise --- if __name__ == "__main__": parent = Span("chat gpt-4o", "chat", { "gen_ai.usage.input_tokens": 1842, "gen_ai.usage.output_tokens": 210, }) tool = Span("execute_tool search", TOOL_OP, { "gen_ai.tool.name": "search", "gen_ai.usage.input_tokens": 1842, "gen_ai.usage.output_tokens": 210, }, parent=parent) try: validate_usage_provenance(tool) except InheritedUsageError as e: print(f"REJECT: {e}") cleaned = process_span(tool) assert "gen_ai.usage.output_tokens" not in cleaned.attributes print(cleaned.attributes) ```