# When must an instance abort a trace rather than close it: span-termination invariants for OpenTelemetry GenAI agent spans under tool-call attribute mutation **Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes, `execute_tool` child spans, `invoke_agent` parent spans) where tool-call attributes are written from non-deterministic tool outputs. Does not apply to stateless request/response inference spans with a single terminal status write, nor to traces exported via a sidecar that buffers and rewrites attributes post-hoc. ## Core Distinction The GenAI semantic conventions treat a span as a *record of a completed operation*: attributes such as `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.usage.input_tokens` are expected to be set before the span ends, and `span.set_status()` is expected to be called exactly once at termination. The failure mode examined here is not "attributes are wrong" — it is that an agent's tool-call lifecycle is *open-ended and revisable* in a way the span lifecycle is not. Concretely: an agent may emit an `execute_tool` span, write `gen_ai.tool.name = "search"`, then — because the model re-plans after a partial tool result — decide the call was actually a *retry* of an earlier call, or that the tool identity was misreported by the model's own function-call payload, or that the call must be replayed under a different `gen_ai.tool.call.id`. The span has already been started with the first attribute set. OpenTelemetry's `Span` API is write-once-per-key at the SDK layer for exported spans, and `set_status` after `end()` is a no-op that silently drops. The boundary condition is: **the agent's authoritative record of a tool call can change after the span that represents it has legally terminated, and there is no conformant way to express that revision inside a single span.** The invariant that resolves this is not "never revise." It is: *a span whose GenAI attributes were derived from a model output that the agent later invalidated must be terminated with `Status.ERROR` and a `gen_ai.tool.call.revision` linkage to the superseding span — it must not be closed `OK` and then left to stand as the record of record.* Closing it `OK` and emitting a corrective span produces two `OK` spans for one logical call, which is the trace-level equivalent of a double-spend. ## What Was Observed A tool-using agent (planner → `execute_tool` → observe → re-plan) was instrumented with the GenAI conventions. The planner occasionally emits a function-call payload whose `name` field is a near-miss of a registered tool (e.g. `web_search_v2` when only `web_search` is registered). The runtime's dispatch layer resolves the near-miss to the registered tool via fuzzy match, executes it, and writes the span attributes from the *resolved* tool, not the *requested* one. The model, on seeing the result, sometimes re-emits the call with the corrected name because its own scratchpad still contains the near-miss. Trace observed: 1. Span `execute_tool` #1 starts. `gen_ai.tool.name = "web_search"` (resolved). Executes. Result returned. Span ends `OK`. 2. Model re-plans, emits `web_search` again with the same arguments — it believes the first call failed because the result schema did not match its expected shape for `web_search_v2`. 3. Span `execute_tool` #2 starts. Same `gen_ai.tool.name`, same arguments, different `gen_ai.tool.call.id`. Ends `OK`. Downstream trace analysis sees two `OK` tool spans with identical name and arguments and concludes the agent is in a duplicate-call loop, and a cost-attribution job double-counts `gen_ai.usage.input_tokens`. Neither span is *wrong* in isolation. The trace is wrong as a whole because the first span's `OK` status asserts "this call completed and its result was accepted," which the agent's subsequent behavior contradicts. The second observed variant is worse: the agent, on realizing the near-miss, attempts to *correct* span #1 by calling `span.set_attribute("gen_ai.tool.name", "web_search_v2")` after `end()`. The SDK drops the write silently. The exported span retains the resolved name. The agent's internal log and the exported trace now disagree about what tool was called, and no error is raised at either layer. ## Condition of Validity The abort-rather-than-close rule is valid only when all of the following hold: - The tool-call span is a *child of an `invoke_agent` span that is still open*. If the parent has ended, the trace is already sealed and the corrective span must be emitted as a new root with an explicit `gen_ai.conversation.id` linkage, not as a sibling. - The revision is *caused by model output*, not by transport failure. A retried HTTP call to the same tool with the same `call.id` is a transport concern and belongs in span events (`exception`, retry count), not in a new span. - The agent retains the original `gen_ai.tool.call.id` and the superseding `call.id` in its own state. If the agent has already discarded the first `call.id` (common after context-window compaction), it cannot emit a valid linkage and must instead emit a `gen_ai.tool.call.orphaned` event on the parent — a weaker but honest record. It does **not** hold when the tool is genuinely idempotent and the duplicate is benign (e.g. a pure read). In that case the correct action is to close both `OK` and attach a `gen_ai.tool.call.duplicate_of` attribute to the second, because forcing `ERROR` on a benign duplicate poisons error-rate SLOs. ## Decision Boundary The decision is between three terminal actions for a tool-call span whose attributes were invalidated after execution: | Condition | Action | Status | Linkage | |---|---|---|---| | Result was consumed by the model and drove a re-plan that re-issues the call | Close `OK` with `gen_ai.tool.call.duplicate_of` on the *second* span | `OK` | forward pointer on successor | | Result was consumed but the model's *requested* tool identity differed from the executed identity | Abort first span `ERROR`; emit successor span with corrected `gen_ai.tool.name` | `ERROR` → `OK` | `gen_ai.tool.call.supersedes` on successor | | Result was never consumed (agent crashed, context saturated, budget exhausted mid-call) | Abort span `ERROR` with `gen_ai.tool.call.abandoned = true` | `ERROR` | none; parent event | The boundary is *consumption*, not *completion*. A tool call that completed at the transport layer but whose result never entered the model's context is not a completed operation from the agent's perspective, and marking it `OK` is the specific lie that produces phantom-success traces. This is the non-obvious part: OpenTelemetry's `OK` means "the operation the span represents did not fail," and for a GenAI tool span the operation is *call-and-incorporate*, not *call-and-return*. ## Operational Effect Enforcing the boundary changes three things: 1. **Cost attribution becomes single-counted.** The `gen_ai.usage.input_tokens` on the successor span is the only one counted; the aborted predecessor carries `gen_ai.usage.input_tokens = 0` and a `gen_ai.tool.call.supersedes` pointer. Downstream rollups that sum tokens no longer double-count re-planned calls. 2. **Error-rate SLOs must be scoped.** Aborted-but-superseded spans inflate raw error rates. The SLO query must filter `status = ERROR AND NOT exists(gen_ai.tool.call.supersedes)`, or the agent's self-correction looks like failure. 3. **The agent must checkpoint `call.id` before the span ends.** Because the successor's linkage depends on the predecessor's `call.id`, the agent's episodic memory must persist `call.id` at span-start, not at span-end. If it persists at end, a mid-call crash loses the id and the successor cannot be linked — which is exactly the orphaned-event fallback above. The guardrail is therefore not in the tracing layer at all. It is an agent-state invariant: *`gen_ai.tool.call.id` must be durably written before the tool executes, because it is the only key that can bind a future corrective span to a past one.* ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpanTerminationError(RuntimeError): """Raised when a GenAI tool-call span cannot be legally terminated.""" class ToolSpanStatus(Enum): OPEN = "open" OK = "ok" ERROR = "error" @dataclass class ToolCallSpan: call_id: str requested_tool: str executed_tool: str status: ToolSpanStatus = ToolSpanStatus.OPEN result_consumed: bool = False supersedes: Optional[str] = None duplicate_of: Optional[str] = None abandoned: bool = False _ended: bool = False _attrs: dict = field(default_factory=dict) def set_attribute(self, key: str, value) -> None: if self._ended: # SDK silently drops this; we surface it instead of lying. raise SpanTerminationError( f"attribute {key!r} written after span end on call {self.call_id!r}" ) self._attrs[key] = value def terminate(self, successor: Optional["ToolCallSpan"] = None) -> None: if self._ended: raise SpanTerminationError(f"span {self.call_id!r} already terminated") if not self.call_id: raise SpanTerminationError("call_id must be persisted before termination") # Boundary rule: consumption, not completion, decides OK vs ERROR. if not self.result_consumed and successor is None: self.abandoned = True self.status = ToolSpanStatus.ERROR self.set_attribute("gen_ai.tool.call.abandoned", True) elif self.requested_tool != self.executed_tool and successor is None: # Identity was invalidated by model output; must abort, not close OK. self.status = ToolSpanStatus.ERROR self.set_attribute("gen_ai.tool.call.identity_mismatch", True) elif successor is not None: self.status = ToolSpanStatus.ERROR successor.supersedes = self.call_id self.set_attribute("gen_ai.tool.call.superseded_by", successor.call_id) else: self.status = ToolSpanStatus.OK self._ended = True def finalize_tool_span( span: ToolCallSpan, successor: Optional[ToolCallSpan] = None, parent_open: bool = True, ) -> None: if not parent_open: raise SpanTerminationError( f"cannot terminate call {span.call_id!r}: parent invoke_agent span sealed; " "emit corrective span as new root with conversation linkage" ) if span._ended: raise SpanTerminationError(f"span {span.call_id!r} already ended") span.terminate(successor=successor) ```