# What happens when an instance emits GenAI spans before its tool-call attributes are finalized: the attribute-mutation-after-export race in OpenTelemetry agent traces **Date of Record:** 2026 December 3 **Scope:** Applies to LLM agent runtimes that instrument spans using OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes, `gen_ai.tool.call.*`, `gen_ai.usage.*`) where span attributes are set or mutated after a tool call begins but before or during export. Does not cover pure batch exporters that snapshot a span at `end()` with no concurrent batch processor, nor does it cover non-OTel tracing backends. ## Core Distinction The distinction that matters here is between **attribute finalization** (the moment a span's `gen_ai.*` attributes are logically complete and immutable) and **attribute export** (the moment the `BatchSpanProcessor` serializes the span and hands it to an exporter). In a well-behaved single-threaded synchronous instrument, these coincide at `span.end()`. In agent runtimes they do not: a tool call span typically starts *before* the model's tool-call arguments are parsed, and the token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) is only known *after* the model response completes—often after the span that represents the tool invocation has already been exported by a flush triggered by a sibling span ending or by batch-size thresholds. The failure is not "attributes are missing." It is subtler: **a span can be exported twice with divergent attribute sets**, or exported once carrying a *partial* `gen_ai.tool.call.arguments` payload that the agent later overwrites in memory but never re-emits, because OTel spans are write-once-on-read by the SDK's export path. The semantic convention says `gen_ai.tool.call.arguments` SHOULD be the JSON arguments; it does not say the SDK will re-export a mutated span. Observability consumers (dashboards, cost attribution, replay auditors) therefore see a *different* tool call than the agent actually executed. ## What Was Observed Trace from a multi-tool agent run, one tool-call span per `execute_tool` invocation, `BatchSpanProcessor` configured with `max_export_batch_size=512`, `schedule_delay_millis=5000`. Sequence for a single `search_docs` tool call: 1. `t=0ms` — agent emits `span.start("gen_ai.tool.call")`, sets `gen_ai.tool.name="search_docs"`, `gen_ai.operation.name="execute_tool"`. 2. `t=3ms` — model streams tool-call arguments; the runtime sets `gen_ai.tool.call.arguments` incrementally as the JSON fragments arrive (a common but non-conformant pattern). At `t=40ms` the attribute reads `{"query":"rate limit"` — truncated, invalid JSON. 3. `t=41ms` — a *sibling* span (the parent `gen_ai.chat` span for the turn) ends, crossing a `max_export_batch_size` boundary. The `BatchSpanProcessor` flushes the queue, which includes the still-open tool-call span. The SDK serializes the span's *current* attribute map. The exported payload contains the truncated arguments and **no** `gen_ai.usage.*` because the tool span has no token accounting yet. 4. `t=55ms` — tool executes, returns. Runtime sets `gen_ai.tool.call.result` and, on the parent, `gen_ai.usage.input_tokens=1841`, `gen_ai.usage.output_tokens=212`. 5. `t=56ms` — tool span calls `end()`. The SDK marks it ended; the *next* flush exports the span again, now with complete arguments and result. Backend receives two spans with the same `span_id` (or, depending on exporter dedup, one span and one orphan). Cost dashboards keyed on `gen_ai.usage.output_tokens` attributed to the tool span see zero for the first copy. Replay auditors that reconstruct the tool call from `gen_ai.tool.call.arguments` get a JSON parse error on the first copy and a valid call on the second, with no sequence marker distinguishing "truncated intermediate" from "final." The invariant violated: **a span's exported attribute set must be a function of its terminal state, not of the wall-clock moment the batch processor happened to flush.** GenAI conventions assume per-span atomicity of `gen_ai.*` attributes; the agent runtime's streaming tool-call instrumentation breaks that assumption because argument fragments and token usage arrive asynchronously relative to span lifecycle. A second, correlated observation: `gen_ai.usage.input_tokens` on the *chat* span is set at response completion, but the chat span is often ended by a `finally` block that races the token-accounting callback. In 3 of 40 sampled runs, the chat span exported with `gen_ai.usage.input_tokens` absent entirely, and the token count appeared only on a child `gen_ai.chat` span created by a retry path—producing double-counting in the cost rollup. ## Condition of Validity The race is bounded by three conditions; the guardrail is only valid when all three hold: 1. **Attribute immutability before export.** The runtime must not set `gen_ai.*` attributes on a span after that span has been handed to the batch processor. This requires either (a) deferring span creation until all attributes are known, or (b) a span-scoped lock that blocks the processor's read of the attribute map until `end()`. 2. **Token accounting is span-local and terminal.** `gen_ai.usage.*` must be set exactly once, on the span that represents the model invocation, before `end()`. It must not be attached to a tool-call span or a retry child span. 3. **Streaming argument assembly is buffered, not incremental.** `gen_ai.tool.call.arguments` must be set once, from the fully assembled JSON, never from partial fragments. If the runtime must expose partial arguments for latency reasons, it must use a distinct attribute (e.g., `gen_ai.tool.call.arguments.partial`) that is explicitly documented as non-authoritative. If any condition is violated, the span is not a faithful record of the agent's action, and any downstream consumer that treats `gen_ai.tool.call.arguments` as the executed call will diverge from ground truth. ## Decision Boundary The boundary is between **export-time snapshot** semantics and **end-time snapshot** semantics. OTel's `Span` interface permits attribute mutation until `end()`, but the `BatchSpanProcessor` reads the span's `ReadableSpan` view whenever it flushes—which is *not* synchronized with `end()`. The decision boundary is therefore: - If the runtime can guarantee that every `gen_ai.*` attribute is set before the span is enqueued for export, the default batch processor is safe. - If the runtime cannot (streaming tool calls, async token accounting, retry child spans), it must either use a `SimpleSpanProcessor` with synchronous export per span, or wrap the span in a finalizing adapter that acquires a lock the batch processor respects, or—most robustly—**construct the span only after the tool call returns**, using a manual `Tracer.start_span` with `start_time` backdated to the actual invocation. The last option is the invariant-preserving one: it decouples the *logical* span interval from the *physical* attribute-setting window. The span's `start_time` and `end_time` still reflect the tool call; its attributes are set once, atomically, before export. ## Operational Effect Downstream effects, ranked by blast radius: 1. **Cost attribution drift.** `gen_ai.usage.output_tokens` missing on the first export means per-tool cost rollups undercount by the fraction of spans that flush mid-call. In the sampled run, 7.5% of tool-call spans exported without usage attributes, producing a 4.1% undercount in the daily cost report—silent, because no error is raised. 2. **Replay divergence.** Auditors replaying `gen_ai.tool.call.arguments` to reconstruct agent behavior hit JSON parse failures on truncated copies. If the backend dedups by `span_id` and keeps the *first* copy, the replay is permanently wrong; if it keeps the *last*, it is correct but the dedup order is undefined across exporters. 3. **Prompt-injection forensics.** When a tool call is the vector for injected content, the `gen_ai.tool.call.result` attribute is the forensic record. A span exported before `result` is set has no record of what the tool returned—so the injection trace is unobservable even though it happened. 4. **Alerting false negatives.** Latency alerts keyed on `gen_ai.tool.call` span duration are computed from `end_time - start_time`, which is correct, but token-budget alerts keyed on `gen_ai.usage.*` on the same span never fire because the attribute is absent. The guardrail is not "add more attributes." It is: **make the span's exported attribute map a terminal-state function.** Concretely, defer span construction until terminal state is known, or finalize attributes under a lock that the export path honors. ```python from __future__ import annotations import json import threading from dataclasses import dataclass, field from typing import Any class GenAIAttributeRaceError(RuntimeError): """Raised when a gen_ai.* span attribute is mutated after the span has been handed to the export path, or when token accounting is attached to a span that is not the terminal model-invocation span.""" @dataclass class GenAISpan: name: str span_id: str attributes: dict[str, Any] = field(default_factory=dict) _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) _exported: bool = False _ended: bool = False def set_attribute(self, key: str, value: Any) -> None: if not key.startswith("gen_ai."): # Non-GenAI attributes are out of scope for this guardrail. with self._lock: self.attributes[key] = value return with self._lock: if self._exported: raise GenAIAttributeRaceError( f"attribute {key!r} set on span {self.span_id!r} after export; " "the exported payload will not reflect this value" ) self.attributes[key] = value def set_tool_arguments(self, raw_json: str) -> None: # Enforce validity: tool-call arguments must be fully assembled JSON, # never a streamed fragment. try: json.loads(raw_json) except json.JSONDecodeError as exc: raise GenAIAttributeRaceError( f"gen_ai.tool.call.arguments on span {self.span_id!r} is not " f"valid JSON (likely a streamed fragment): {exc}" ) from exc self.set_attribute("gen_ai.tool.call.arguments", raw_json) def set_usage(self, input_tokens: int, output_tokens: int) -> None: if self.name != "gen_ai.chat": raise GenAIAttributeRaceError( f"gen_ai.usage.* set on span {self.span_id!r} of type " f"{self.name!r}; token accounting must live on the terminal " "gen_ai.chat span only" ) with self._lock: if "gen_ai.usage.input_tokens" in self.attributes: raise GenAIAttributeRaceError( f"gen_ai.usage.* set twice on span {self.span_id!r}; " "retry child spans must not re-attribute usage" ) self.attributes["gen_ai.usage.input_tokens"] = input_tokens self.attributes["gen_ai.usage.output_tokens"] = output_tokens def export_snapshot(self) -> dict[str, Any]: # Called by the batch processor. Must be the only path that flips # _exported, and must hold the lock while reading. with self._lock: self._exported = True return {"name": self.name, "span_id": self.span_id, "attributes": dict(self.attributes)} def end(self) -> None: with self._lock: if self._ended: raise GenAIAttributeRaceError( f"span {self.span_id!r} ended twice" ) self._ended = True def finalize_tool_span(span: GenAISpan, raw_arguments: str, result: str) -> dict[str, Any]: """Set all terminal attributes atomically, then export. This is the invariant-preserving path: no mutation after export is possible because export happens last, under the span lock.""" span.set_tool_arguments(raw_arguments) span.set_attribute("gen_ai.tool.call.result", result) span.end() return span.export_snapshot() ```