# When must an instance refuse to close an OpenTelemetry GenAI agent span: the tool-call/token-accounting reconciliation invariant and its silent violation under streaming partial tool results **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.call.*`, `gen_ai.usage.input_tokens`/`output_tokens`) per the OTel GenAI semantic conventions and that streams tool-call arguments or results incrementally. Does not apply to non-instrumented agents, nor to batch runs that buffer the entire tool result before any span attribute is set. ## Core Distinction The distinction that matters is between *span closure* as a transport event (the runtime's `end()` call returns and the span is handed to the exporter) and *span closure* as an accounting event (the sum of the span's token attributes and tool-call attributes is internally consistent with the turn it describes). The GenAI conventions treat `gen_ai.usage.*` as monotonic counters and `gen_ai.tool.call.id` as a join key, but they say nothing about *when* those attributes become immutable. An agent that streams tool arguments will populate `gen_ai.tool.call.arguments` incrementally, and an agent that streams model output will populate `gen_ai.usage.output_tokens` from a provider-reported delta or a local tokenizer estimate. The failure mode is not a missing attribute — it is a span that closes *between* two consistent states, capturing a tool-call count and a token count that were each individually valid at different instants, and which together describe a turn that never existed. Downstream cost attribution, loop-detection heuristics, and replay-based verification all consume this composite and silently diverge. ## What Was Observed A planner agent issued a single turn containing two tool calls (`search_docs`, `fetch_url`). The provider streamed `tool_calls` deltas: the first call's arguments arrived complete in chunk 3, the second call's `id` arrived in chunk 4 but its `arguments` continued through chunk 9. The runtime's span lifecycle was tied to the *turn loop*, not the *tool-call loop*: it opened one `gen_ai.operation.name=chat` span, recorded `gen_ai.usage.output_tokens` from the final usage chunk (arriving at chunk 10), and called `span.end()` when the assistant message object was fully assembled — which the runtime considered complete at chunk 4, because `len(tool_calls) == expected_count` was satisfied by the second call's `id` alone. The remaining argument deltas were appended to the message object *after* `end()` had already snapshotted attributes. The exported span therefore carried: - `gen_ai.tool.call.count = 2` (correct), - `gen_ai.tool.call.arguments` for call 2 = `{"url": "https://` (truncated mid-string), - `gen_ai.usage.output_tokens = 412` (the full turn's output, including the ~180 tokens of argument text that arrived after `end()`). The inconsistency is subtle: neither number is wrong in isolation. The token count is the true turn cost. The tool-call count is the true turn cardinality. But the *arguments* attribute is a 90-byte prefix while the token count bills for the full 180-token argument payload. A downstream cost-attribution job that computes "tokens per tool call" now attributes the entire argument-streaming cost to a call whose recorded arguments are truncated, inflating the per-call cost by ~2.4x for that call and deflating the sibling. A replay harness that re-executes `fetch_url` from the recorded arguments fails on the malformed URL and records a spurious tool error, which a loop-detection heuristic then reads as a retry signal, which triggers a re-plan that was never warranted. The second, independent observation: under provider retry, the runtime emitted a *second* `chat` span for the same logical turn (the retry was at the HTTP layer, below the span boundary, but the runtime re-instrumented on resume). Both spans carried the full `gen_ai.usage.output_tokens`, because the provider's usage chunk is per-request and the retry re-sent the full completion. The aggregate cost for the turn was double-counted. The GenAI conventions define `gen_ai.usage.*` as per-span, not per-logical-turn, so this is *convention-compliant* and *operationally wrong*. ## Condition of Validity The reconciliation invariant holds only when three conditions are jointly true at the instant `end()` is called: 1. **Argument closure:** every `gen_ai.tool.call.arguments` value is a complete, parseable JSON object whose byte length is final — i.e., no further deltas for that `gen_ai.tool.call.id` are pending in the transport buffer. 2. **Usage closure:** `gen_ai.usage.output_tokens` reflects exactly the tokens emitted in the content that the span's other attributes describe — not the tokens emitted in the *request* if the request spans a retry or a speculative continuation. 3. **Identity closure:** each `gen_ai.tool.call.id` appears exactly once across the logical turn's spans, and no two spans in the same `trace_id` claim the same call id with different arguments. The invariant is violated whenever the span's `end()` is gated on a *cardinality* condition (`count == expected`) rather than a *termination* condition (the transport signalled end-of-stream for every open call id). Cardinality is satisfiable by a partial message; termination is not. The runtime conflated "I have seen N tool calls" with "I have finished receiving N tool calls," and the GenAI conventions provide no attribute to distinguish the two — there is no `gen_ai.tool.call.state` and no `gen_ai.usage.final` flag. The invariant must therefore be enforced by the runtime, not read from the span. ## Decision Boundary The boundary is drawn at the point where the runtime decides to snapshot attributes. Two policies are defensible; a third is not. - **Snapshot-on-end (current, unsafe):** attributes are read at `end()` from the live message object. Safe only if `end()` is gated on transport termination for every open call id and on the *final* usage chunk (not the first). Under streaming, this requires the runtime to hold the span open until the last delta of the last call, which may be arbitrarily later than the last content token. - **Snapshot-on-seal (safe):** the runtime maintains a per-call seal flag set when the transport emits a terminal delta for that `gen_ai.tool.call.id`, and a per-turn seal set when the provider emits its usage chunk. `end()` is deferred until all seals are set, or the span is closed with `gen_ai.tool.call.arguments` *omitted* and a `gen_ai.tool.call.arguments.truncated=true` (non-standard but honest) marker. Omission is strictly better than truncation: a missing attribute is detectable, a truncated JSON string is not. - **Snapshot-on-first-complete (unsafe):** close as soon as *any* consistent-looking state exists. This is the observed failure and must be rejected. For the retry double-count, the boundary is whether the retry is modeled as a child span (`gen_ai.operation.name=chat` with `retry.attempt` attribute) under a stable parent turn span, or as a sibling. Only the child-span model permits a parent span that carries the *deduplicated* turn cost while children carry per-attempt costs. The conventions do not mandate this; the operational invariant does. ## Operational Effect The consequence of violating the invariant is not a crash — it is a class of silent divergence that corrupts the three consumers of GenAI spans most likely to be automated: 1. **Cost attribution** drifts monotonically. Truncated arguments paired with full token counts bias per-call cost upward for streamed calls and downward for their siblings; over a long trace the bias does not average out because the truncation is correlated with argument length, which is correlated with call type. Budget alarms calibrated on the biased series fire late. 2. **Replay-based verification** produces false tool errors. A replay harness that reconstructs tool inputs from `gen_ai.tool.call.arguments` cannot parse truncated JSON; the resulting error is attributed to the tool, not the span, and poisons any verifier that treats tool errors as evidence of agent misbehavior. 3. **Loop detection** mis-fires. Duplicate `gen_ai.tool.call.id` across retry spans reads as a repeated call; a heuristic that flags "same tool, same args, within N spans" as a loop will flag every retried turn, suppressing legitimate retries or, worse, terminating agents that are recovering correctly. The guardrail is a single invariant enforced at the runtime layer: **a GenAI span may not close while any `gen_ai.tool.call.id` it references lacks a terminal-delta seal, and a turn's token attributes may not be summed across spans that share a retry lineage without deduplication at the parent.** The span is a *sealed* record or it is an *incomplete* record explicitly marked as such; it is never a composite of two consistent instants. ```python import json from dataclasses import dataclass, field class SpanSealViolation(RuntimeError): """Raised when a GenAI span is closed before its tool-call and usage attributes reach a jointly consistent state.""" pass @dataclass class ToolCallState: call_id: str arguments_buffer: str = "" sealed: bool = False def arguments(self) -> dict: if not self.sealed: raise SpanSealViolation( f"tool call {self.call_id!r} arguments read before terminal delta" ) try: return json.loads(self.arguments_buffer) except json.JSONDecodeError as exc: raise SpanSealViolation( f"tool call {self.call_id!r} arguments not valid JSON at seal: {exc}" ) from exc @dataclass class GenAISpanState: operation: str tool_calls: dict[str, ToolCallState] = field(default_factory=dict) usage_sealed: bool = False output_tokens: int = 0 retry_lineage: str | None = None def record_delta(self, call_id: str, delta: str, terminal: bool) -> None: state = self.tool_calls.setdefault(call_id, ToolCallState(call_id)) if state.sealed: raise SpanSealViolation( f"delta for already-sealed tool call {call_id!r}" ) state.arguments_buffer += delta if terminal: state.sealed = True def record_usage(self, output_tokens: int, final: bool) -> None: if self.usage_sealed: raise SpanSealViolation("usage recorded after seal") self.output_tokens = output_tokens if final: self.usage_sealed = True def close(self) -> dict: unsealed = [c for c in self.tool_calls.values() if not c.sealed] if unsealed: raise SpanSealViolation( f"refusing to close span: {len(unsealed)} tool call(s) " f"unsealed: {[c.call_id for c in unsealed]}" ) if not self.usage_sealed: raise SpanSealViolation( "refusing to close span: usage chunk not marked final" ) # Materialize arguments only now, when every call is sealed. return { "gen_ai.operation.name": self.operation, "gen_ai.usage.output_tokens": self.output_tokens, "gen_ai.tool.call.count": len(self.tool_calls), "gen_ai.tool.call.arguments": { cid: c.arguments() for cid, c in self.tool_calls.items() }, } def close_turn(spans: list[GenAISpanState]) -> dict: """Close a logical turn, deduplicating retry lineage at the parent.""" by_lineage: dict[str, int] = {} for span in spans: if span.retry_lineage is None: continue if span.retry_lineage in by_lineage: raise SpanSealViolation( f"duplicate retry lineage {span.retry_lineage!r} across spans; " "retry must be modeled as a child span, not a sibling" ) by_lineage[span.retry_lineage] = span.output_tokens return {"spans": [s.close() for s in spans]} ```