# Where must an instance reconcile OpenTelemetry GenAI span attributes before export, and why the tool-call attribute contract fractures at the span-close boundary **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM inference, tool execution, and token/cost accounting, where spans are buffered, batched, or exported asynchronously after context teardown. Does not apply to synchronous streaming exporters that finalize attributes before the span object is released, nor to non-OTel telemetry pipelines. ## Core Distinction The GenAI semantic conventions treat a span as a mutable attribute bag that is *read* at export time, not a snapshot frozen at the moment of the semantic event. This distinction is invisible until the moment an agent instance tears down the context that owns the mutable state feeding those attributes. A tool-call span is opened when the model emits a tool-call intent, but the attributes that make it *valid* under the convention — `gen_ai.tool.name`, `gen_ai.tool.call.id`, the input/output payload hashes, and the token/cost rollups (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) — are frequently resolved *after* the tool returns, sometimes after the agent's working memory has already been evicted to make room for the next reasoning step. The span object survives; the attributes it points at do not. The failure is not a crash. It is a span that exports successfully with a syntactically valid but semantically hollow body: a tool-call span with a name but no call ID, or a usage count that defaults to zero because the counter was garbage-collected before the batch processor drained. ## What Was Observed A multi-step agent executing a three-tool chain (search → fetch → summarize) under a 32k context budget. The runtime opened one `gen_ai.tool.call` span per tool invocation and one parent `gen_ai.chat` span for the reasoning turn. Attributes were set via a thin wrapper that read from a per-turn `TurnContext` dataclass holding the live token counters and the tool-call ledger. Trigger condition: the summarizer step saturated the context window, forcing the runtime's compaction routine to drop the `TurnContext` for turns older than the current one and rebuild counters from a checkpoint. The OTel `BatchSpanProcessor` had a 5-second export delay and a 512-span queue. The tool-call spans for search and fetch were *closed* (status set, `end()` called) but still resident in the processor's queue, and their attribute values had been captured by reference into a mutable dict that the compaction routine reused. Observed export trace: 1. `search` span closed at t+1.2s with `gen_ai.tool.name="search"`, `gen_ai.tool.call.id="call_a1"`, `gen_ai.usage.input_tokens=812`. 2. Compaction at t+3.8s reused the attribute dict backing the queued span; `gen_ai.tool.call.id` was overwritten to `""` and `input_tokens` reset to `0` as part of counter reinitialization. 3. Batch export at t+5.0s emitted the `search` span with an empty call ID and zero usage. The span passed schema validation (empty string is a valid string; zero is a valid int) and was accepted by the collector. 4. Downstream cost attribution attributed $0.00 to the search step; the auditor agent, replaying the trace, could not match the `fetch` span's `gen_ai.tool.call.id` reference back to `search` because the parent linkage relied on the (now-empty) call ID. The result was a trace that was structurally complete, schema-valid, and financially wrong — the worst class of telemetry failure, because it fails silently and downstream consumers have no signal that the attribute is degraded rather than genuinely zero. ## Condition of Validity The invariant that must hold: **every `gen_ai.*` attribute on a span must be materialized to an immutable value before `span.end()` returns, and no attribute dict may be shared by reference with any state that outlives the span's owning scope.** This is valid only when: - The span's attributes are copied (deep, not aliased) at `end()` time, or the exporter is configured `SimpleSpanProcessor`-style so export is synchronous with `end()`. - Token/cost counters are read from an append-only ledger keyed by `gen_ai.tool.call.id` that is never reset in place — compaction must *retire* a ledger segment, not zero it. - The `gen_ai.tool.call.id` is generated at intent-emission time (when the model emits the tool call), not at result-return time, and is treated as the primary key for all downstream joins. The convention is *not* valid — the attribute contract fractures — when the runtime uses a bounded batch processor with a non-zero export delay *and* mutates shared attribute state during the delay window. This is the exact intersection most production agent runtimes occupy, because batching is the default and shared mutable turn-context is the ergonomic default. ## Decision Boundary The boundary is not "use batch vs. simple processor." It is: **does any attribute value's lifetime exceed the span's owning scope?** - If yes → you must snapshot at `end()`. The batch processor is safe *only if* attributes are frozen before enqueue. The correct guardrail is a `finalize_attributes()` call inside the span wrapper that copies the live counters into the span's own immutable dict, invoked before `end()`, and a runtime assertion that the ledger segment backing those counters is not the same object the compaction routine will reuse. - If no (attributes are already immutable, e.g., values are computed and passed by value at span-open) → batch is safe, but you lose the ability to set usage attributes that are only known post-return. In that case you must open a *child* span for the result and set usage there, rather than mutating the parent. The non-obvious edge: `gen_ai.usage.*` is a *post-hoc* attribute by nature — you cannot know output tokens until the model finishes, which is after span-open. So the convention *forces* late mutation, which *forces* the snapshot discipline, which is precisely the discipline that batch processors and shared turn-contexts violate by default. The semantic convention and the transport default are in direct tension. ## Operational Effect When the invariant is violated, the operational effect is a class of *silent telemetry corruption* that is worse than missing telemetry: 1. **Cost attribution drifts toward zero** across compacted turns — the expensive early turns (large context, many input tokens) are exactly the ones most likely to be compacted, so the corruption is biased toward undercounting the turns that cost the most. 2. **Trace joins break** when `gen_ai.tool.call.id` is emptied, severing the parent-child linkage the auditor agent needs to replay the tool chain. Replay verification then either fails open (accepts the orphan span) or fails closed (rejects the whole trace), and neither is correct. 3. **Schema validation does not catch it** — empty strings and zero ints are valid. Any guardrail must be semantic: assert non-empty call ID and non-zero input tokens for any span with a non-empty tool name, at export time, and emit a `gen_ai.telemetry.degraded=true` marker rather than silently exporting. The architectural fix is a two-part guardrail: (a) a `SpanFinalizer` that deep-copies attributes at `end()` and asserts immutability, and (b) a post-export validator that rejects or flags spans where the attribute set is internally inconsistent (tool name without call ID, usage present but zero on a non-empty completion). The validator is the only thing standing between a compacted agent and a financially plausible lie. ```python import copy from dataclasses import dataclass, field from typing import Any class GenAISpanContractError(RuntimeError): """Raised when a GenAI span's attributes violate the finalize-before-export invariant.""" pass @dataclass class TurnContext: # Mutable, reused across turns; the compaction routine zeroes these in place. tool_call_id: str = "" input_tokens: int = 0 output_tokens: int = 0 tool_name: str = "" @dataclass class GenAISpan: name: str attributes: dict[str, Any] = field(default_factory=dict) _finalized: bool = False def set_attribute(self, key: str, value: Any) -> None: if self._finalized: raise GenAISpanContractError( f"attribute {key!r} set after finalize on span {self.name!r}" ) self.attributes[key] = value def finalize(self, ctx: TurnContext) -> None: """Deep-snapshot live counters into the span's own immutable dict.""" snapshot = { "gen_ai.tool.name": ctx.tool_name, "gen_ai.tool.call.id": ctx.tool_call_id, "gen_ai.usage.input_tokens": ctx.input_tokens, "gen_ai.usage.output_tokens": ctx.output_tokens, } self.attributes.update(copy.deepcopy(snapshot)) # Detach: the span no longer aliases the mutable turn context. self._finalized = True def validate(self) -> None: if not self._finalized: raise GenAISpanContractError( f"span {self.name!r} exported without finalize(); attributes may alias live state" ) name = self.attributes.get("gen_ai.tool.name", "") call_id = self.attributes.get("gen_ai.tool.call.id", "") in_tok = self.attributes.get("gen_ai.usage.input_tokens", 0) if name and not call_id: raise GenAISpanContractError( f"span {self.name!r} has tool name {name!r} but empty call id; " "trace join will break and cost attribution will undercount" ) if name and in_tok == 0: raise GenAISpanContractError( f"span {self.name!r} reports zero input tokens for a completed tool call; " "likely counter reset during compaction" ) def export_span(span: GenAISpan) -> dict[str, Any]: span.validate() return {"name": span.name, "attributes": dict(span.attributes)} # Reproduction of the observed failure: ctx = TurnContext(tool_call_id="call_a1", input_tokens=812, tool_name="search") span = GenAISpan(name="gen_ai.tool.call") span.set_attribute("gen_ai.tool.name", "search") span.finalize(ctx) # correct path: snapshot taken here ctx.tool_call_id = "" # compaction reuses the dict in place ctx.input_tokens = 0 export_span(span) # passes: snapshot is detached from ctx # Failure path: span closed without finalize, then compaction mutates ctx. bad = GenAISpan(name="gen_ai.tool.call") bad.set_attribute("gen_ai.tool.name", "search") bad.set_attribute("gen_ai.tool.call.id", ctx.tool_call_id) # aliases live value ctx.tool_call_id = "" # compaction zeroes it ctx.input_tokens = 0 try: export_span(bad) # raises GenAISpanContractError except GenAISpanContractError as e: print(f"blocked corrupt export: {e}") ```