# How does an instance detect a tool-call span that silently mutates its own GenAI semantic-convention attributes after the turn completes **Date of Record:** 2026 November 20 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, etc.) and that exports those spans asynchronously via a batching `SpanProcessor`, where the tool handler or a downstream retry path can mutate the span object after the logical turn has already been recorded. Does not apply to synchronous simple-export setups where `span.end()` immediately serializes and ships the span, nor to pure structured-logging pipelines with no span object lifetime. ## Core Distinction The GenAI semantic conventions treat a span's attributes as an **immutable record of a single turn's causal facts**: `gen_ai.operation.name` (e.g. `execute_tool`), `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.usage.input_tokens`/`output_tokens`, and the tool call/result payload attributes. The spec assumes these are set once, at the point the operation terminates, and then frozen. The failure mode is that this assumption is false in practice. A `Span` is a mutable bag of attributes with a mutable status, and its *export* is decoupled from its *end*. When a tool call is retried, when a tool handler writes a late "final" result, or when a parent agent-turn span is annotated after its child tool spans have already ended, the runtime can write to a span that has already been `end()`ed but not yet exported. The batched processor then ships whatever attributes exist at flush time — not what existed at `end()` time. The trace records a *later* state than the one the agent actually reasoned over. This is attribute-time skew: the span's `gen_ai.*` attributes describe a superset or a mutated version of the turn, and the `end_time_unix_nano` lies about when those attributes became true. The distinction that matters operationally: **a span's end timestamp is a claim about attribute finality, and the OTel SDK does not enforce that claim.** The GenAI conventions inherit this gap. Any consumer that reconstructs agent behavior from the trace (cost accounting, replay, auditor consensus) will reconstruct the wrong turn. ## What Was Observed A single-agent loop executing a tool named `search_inventory` with an idempotent-looking retry wrapper. Sequence, reconstructed from `SpanProcessor.on_end` debug hooks and a sidecar attribute-write logger: 1. Agent turn begins; parent span `agent.turn` (operation `invoke_agent`) is opened. Child tool span `tool.call` (operation `execute_tool`, `gen_ai.tool.name=search_inventory`, `gen_ai.tool.call.id=call_7f3a`) is opened. 2. Tool handler issues an HTTP call; response times out at 4.2s. Handler raises, the retry wrapper catches and re-invokes. 3. First attempt's span is ended with `status=ERROR` and `gen_ai.tool.call.id=call_7f3a`. It is queued in the `BatchSpanProcessor` (default `schedule_delay_millis=5000`). 4. The retry reuses the *same* `call_7f3a` id (the runtime deduplicates tool calls by id to avoid double-charging token budgets) and, crucially, reuses the *same* `Span` object because the wrapper holds a reference for "final annotation." It calls `span.set_attribute("gen_ai.tool.call.result", ...)` and `span.set_status(Status(StatusCode.OK))` after the second attempt succeeds at t=6.1s. 5. `BatchSpanProcessor` flushes at t≈9.2s. The exported span carries `status=OK`, the success result, and `end_time_unix_nano` from t=4.2s — *before* the result attribute was written. The 4.2s timeout and the 1.9s retry gap are erased from the trace entirely. Observed downstream consequences: a cost/retry dashboard computed retry rate from `status=ERROR` counts and reported zero retries for this agent over a 6-hour window; a replay harness that re-fed the trace into a fresh instance re-executed `search_inventory` as if it had succeeded on the first call at 4.2s, diverging from the real timeline by 1.9s and skipping the failure branch that had consumed 800 extra input tokens. The trace was internally consistent — every attribute was valid — and wrong. The signature to detect this is narrow: **attribute writes to a span whose `end_time_unix_nano` precedes the write's wall-clock time.** The OTel SDK does not reject `set_attribute` after `end()`; it silently mutates the in-memory object, and the batch processor ships the mutated version. There is no error, no warning, no dropped-attribute counter. ## Condition of Validity The skew is *bounded and detectable* only under these conditions, and the record should not be generalized outside them: - **Asynchronous export with a non-zero batch delay.** With `SimpleSpanProcessor` (synchronous export on `end()`), the span is serialized at `end()` and later writes are lost rather than shipped — a different, safer failure. The dangerous regime is `BatchSpanProcessor` with `schedule_delay_millis > 0` and `max_export_batch_size` not yet reached. - **Attribute writes are permitted after `end()`.** This is true for the reference OTel SDKs (Python, Java, Go) as of the versions in use; it is not guaranteed by the spec and should be treated as an implementation detail to defend against, not rely on. - **The tool-call identity (`gen_ai.tool.call.id`) is reused across retry attempts.** If each retry mints a fresh `call.id` and a fresh span, the trace is honest (two spans, one ERROR one OK) and the skew does not occur — but then token accounting double-counts and the agent's idempotency reasoning is invisible. Reuse is the common choice precisely because it makes cost accounting correct, and it is what creates the skew. - **The turn's logical end is defined by the tool result, not by the span's `end()` call.** If the runtime defines turn end strictly at `end()`, the late write is simply out of scope and the trace is consistent by definition — but then the retry is a separate turn and the parent `agent.turn` span's token totals are wrong instead. Outside these conditions — synchronous export, per-attempt span identity, or turn-end pinned to `end()` — the invariant below does not bind and the runtime may proceed without the guard. ## Decision Boundary The runtime must decide, at the moment a tool handler attempts to write to a span, whether that span is **still the authoritative record of the turn** or **a stale object whose export has already been claimed.** The boundary is crossed at `end()`, and the SDK does not mark it. The architectural invariant required to bound the failure: > **A span's GenAI attributes must be frozen at `end()`, and `end_time_unix_nano` must be ≥ the timestamp of the last attribute written to that span. Any write after `end()` must be rejected at the SDK boundary, not silently absorbed.** Two guardrails enforce it, and both are needed because they catch different halves: 1. **Freeze-on-end at the runtime layer.** The runtime wraps each tool-call span in a handle that flips a `_sealed` flag on `end()`. Any `set_attribute`/`set_status`/`record_exception` through the handle after sealing raises a typed error. This catches the retry-wrapper-reuses-span bug at the source, where the stack trace still names the offending handler. 2. **Post-export skew validation at the collector/processor layer.** A `SpanProcessor.on_end` hook (or a collector processor) compares each `gen_ai.*` attribute's recorded write timestamp — injected by the runtime as a non-normative `genai.attr_write_ns` attribute, or reconstructed from a sidecar log — against `end_time_unix_nano`. A span where any attribute write timestamp exceeds the end timestamp is flagged `genai.attribute_skew=true` and routed to a quarantine stream rather than the primary trace store. This catches writes that bypass the handle (direct `Span` access, third-party instrumentation). The decision boundary for *acting* on a flagged span: a skewed span is not corrupt and not discardable — it is a **replay hazard**. It may be used for cost accounting (the final result is present) but must not be used for timeline reconstruction or retry-rate computation, because its end timestamp is a lie. The runtime tags it and downstream consumers branch on the tag. What the boundary is *not*: it is not a reason to reject the tool call, not a reason to re-execute, and not a signal of model error. The agent reasoned correctly; the telemetry lied. Conflating the two sends debugging down the wrong path. ## Operational Effect With the guardrails in place, three behaviors change: - **Retry visibility is restored.** The retry wrapper can no longer mutate the ended span; it must open a new span with a fresh `gen_ai.tool.call.id` suffix (e.g. `call_7f3a#retry1`) and link it to the original via a span link carrying the original `call.id`. The trace now shows two spans, an explicit link, and an honest timeline. Cost accounting sums both; retry-rate dashboards count the link. The 1.9s gap reappears. - **Replay fidelity is preserved.** A replay harness that reads the trace sees the true end time of the failed attempt and the true start of the retry, so it re-executes the failure branch and reproduces the 800-token overrun. Divergence between replayed and original token totals drops to the model's own non-determinism, which is the only irreducible source. - **Auditor consensus stops rubber-stamping.** A multi-agent auditor that validates a turn by checking `status=OK` on the tool span now sees the skew flag and refuses to certify the turn until the retry link is resolved — closing a class of false-consensus where the auditor and the executor both read the mutated span and agreed it was clean. The cost of the guardrail is one boolean per span and one comparison per attribute write; the cost of *not* having it is a trace corpus that is internally consistent, semantically wrong, and undetectable after the fact — because the evidence of the skew is overwritten by the skew itself. ```python import time from dataclasses import dataclass, field from typing import Any class AttributeSkewError(RuntimeError): """Raised when a GenAI span attribute is written after the span was sealed at end().""" @dataclass class SealedSpan: """Minimal stand-in for an OTel Span with a freeze-on-end guard.""" name: str attributes: dict[str, Any] = field(default_factory=dict) end_time_ns: int | None = None _sealed: bool = False _last_write_ns: int = 0 def set_attribute(self, key: str, value: Any) -> None: now = time.time_ns() if self._sealed: raise AttributeSkewError( f"span {self.name!r} sealed at end_time_ns={self.end_time_ns}; " f"refused late write {key!r} at {now} " f"(skew={now - self.end_time_ns}ns). " f"Open a new span with a fresh gen_ai.tool.call.id instead." ) self.attributes[key] = value self._last_write_ns = now def end(self) -> None: if self._sealed: raise AttributeSkewError(f"span {self.name!r} already ended") self.end_time_ns = time.time_ns() self._sealed = True def validate_export(span: SealedSpan) -> None: """Collector-side guard: reject spans whose last attribute write postdates end().""" if span.end_time_ns is None: raise AttributeSkewError(f"span {span.name!r} exported without end()") if span._last_write_ns > span.end_time_ns: raise AttributeSkewError( f"span {span.name!r} attribute skew: last write {span._last_write_ns} " f"> end {span.end_time_ns}; route to quarantine, do not use for replay" ) def simulate_retry_reuse() -> None: """Reproduces the observed failure: retry wrapper mutates an ended span.""" span = SealedSpan(name="tool.call") span.set_attribute("gen_ai.operation.name", "execute_tool") span.set_attribute("gen_ai.tool.name", "search_inventory") span.set_attribute("gen_ai.tool.call.id", "call_7f3a") span.end() # first attempt timed out at t=4.2s # Retry wrapper holds the same span and annotates the success result. span.set_attribute("gen_ai.tool.call.result", "inventory=42") # raises if __name__ == "__main__": try: simulate_retry_reuse() except AttributeSkewError as exc: print(f"GUARD TRIPPED: {exc}") ```