# In what scenarios must an instance reject a GenAI span whose token usage counters have already been emitted before the tool-call result is known **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) where a single logical agent turn spans an LLM inference and one or more tool calls, and where token/cost metrics are exported as cumulative counters or histograms. Does not apply to pure stateless inference logging with no tool-call fan-out, nor to batch offline scoring pipelines. ## Core Distinction The GenAI semantic conventions treat an LLM inference span and a tool-execution span as sibling spans under an agent invoke span, with `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attached to the inference span and `gen_ai.tool.name` / `gen_ai.tool.call.id` attached to the tool span. The non-obvious boundary is this: **token usage is finalized at inference completion, but the agent turn is not finalized until tool results feed back into a subsequent inference.** A turn that does N inferences interleaved with tool calls produces N usage records, and the *cost attributable to the turn* is only correct if each usage record is bound to the inference span that produced it—not to the turn, not to the tool call, and not emitted twice when the runtime re-enters the inference span after a tool round-trip. The failure mode is what I will call **premature usage finalization with span re-entry**: the exporter flushes `gen_ai.usage.*` for an inference span, the agent then executes a tool call, the tool result triggers a *re-emission* of the same inference span (or a re-export of its attributes after mutation), and the cost counter double-counts the first inference while the second inference's usage is attributed to the wrong span ID. The invariant that bounds this is: *usage attributes on a GenAI span are immutable once the span's end timestamp is set, and a span ID must never be re-opened after end.* ## What Was Observed A tool-using agent (single model, three-round loop: inference → tool → inference → tool → inference) emitted the following trace under load. The runtime used an async span processor with a 500ms batch timeout, and the agent loop reused a cached `Span` handle across tool round-trips to "avoid re-creating spans." Trace excerpt as exported to the collector: ``` span_id=A1 kind=INTERNAL name=invoke_agent span_id=B1 kind=CLIENT name=chat gen_ai.usage.input_tokens=1840 output_tokens=210 end_ts=T0 span_id=C1 kind=CLIENT name=execute_tool gen_ai.tool.name=search start_ts=T0+5ms end_ts=T0+1800ms span_id=B1 kind=CLIENT name=chat gen_ai.usage.input_tokens=1840 output_tokens=210 end_ts=T0+1810ms <-- re-exported span_id=C2 kind=CLIENT name=execute_tool gen_ai.tool.name=fetch start_ts=T0+1815ms end_ts=T0+3000ms span_id=B2 kind=CLIENT name=chat gen_ai.usage.input_tokens=2210 output_tokens=140 end_ts=T0+3010ms ``` Two distinct defects are visible: 1. **B1 is exported twice** with identical usage attributes but different `end_ts`. The downstream metric processor, which converts `gen_ai.usage.input_tokens` into a counter increment keyed on `(span_id, model)`, counted 1840 twice. Total input tokens reported: 5890. Ground truth: 4050. A 45% overcount on this turn. 2. **The second inference (B2) carries only its own usage**, which is correct—but because the runtime re-entered B1's span context to issue the second inference's *request*, the `gen_ai.request.model` attribute on B2 was inherited from B1's cached handle and reflected a fallback model name, not the model actually invoked. Cost-per-model dashboards attributed 2210 input tokens to the wrong SKU. The trigger condition was precise: the runtime's span cache was keyed on `(turn_id, role)` rather than `(turn_id, inference_ordinal)`. When the tool call returned within the batch window (1800ms < 500ms is false, so the batch had *already flushed* B1 before the re-entry), the re-entered span had no live state to mutate—the SDK's `Span` object was a no-op wrapper after `end()`, so the runtime's `set_attribute` calls silently dropped, and the *exported* B1 retained its original usage while a *new* export fired on the second `end()` call. The double count came from the metric processor, not the span processor: the span processor deduplicated by span ID, but the metric processor keyed on `(span_id, end_ts)` and saw two distinct series. ## Condition of Validity The invariant holds—and the guardrail is mandatory—only when all three of the following are true: - **Usage is emitted as a counter or histogram delta, not as a gauge snapshot.** A gauge (`gen_ai.usage.input_tokens` read as last-value) is idempotent under re-export; a counter increment is not. The GenAI conventions permit both; the double-count only bites the counter form. - **The tool round-trip latency can exceed the span processor's batch export timeout.** If every tool call returns in <50ms and the batch window is 500ms, the span is never flushed mid-turn and re-entry mutates live state harmlessly. The boundary is crossed exactly when `tool_latency_p99 > batch_timeout`. - **The runtime reuses span handles across inferences.** A runtime that creates a fresh span per inference (keyed on inference ordinal) cannot re-enter an ended span. The defect requires handle reuse. When any of these is false, the failure does not manifest, and the guardrail described below is unnecessary overhead. ## Decision Boundary An instance must **reject and re-emit** rather than mutate when it detects that a `gen_ai.usage.*` attribute is being set on a span whose end timestamp is already populated, or when a span ID appears in more than one metric export within a single agent turn. The decision rule: - If `span.end_time is not None` and the runtime attempts `set_attribute("gen_ai.usage.*", ...)` → the span is ended; the write would be a silent no-op. **Do not proceed.** Allocate a new span with a fresh ID, carrying `gen_ai.operation.name=chat` and an explicit `gen_ai.agent.inference_ordinal` attribute so the metric processor can reconstruct turn-level cost without relying on span nesting. - If the metric exporter observes the same `(span_id, gen_ai.usage.input_tokens)` pair twice with different `end_ts` → the second is a re-export artifact. **Drop it and emit a `gen_ai.span.reentry_detected` event** on the parent agent span, because the drop hides a real defect that must be visible to the operator. - If the tool call is still in flight when the batch flush fires (the common case at p99), the correct behavior is to **end the inference span before the tool span starts** and never re-open it. The tool result feeds a *new* inference span. The agent turn span aggregates by summing child inference spans at turn end—not by mutating any inference span. The boundary is not "flush less often" or "increase the batch timeout." Those push the failure to a rarer latency regime without removing it. The boundary is the immutability of ended spans, enforced at the write site. ## Operational Effect With the guardrail in place, the observed trace becomes: ``` span_id=A1 name=invoke_agent span_id=B1 name=chat ordinal=0 usage.in=1840 usage.out=210 end_ts=T0 span_id=C1 name=execute_tool tool=search end_ts=T0+1800ms span_id=B2 name=chat ordinal=1 usage.in=2210 usage.out=140 end_ts=T0+1810ms span_id=C2 name=execute_tool tool=fetch end_ts=T0+3000ms span_id=B3 name=chat ordinal=2 usage.in=905 usage.out=88 end_ts=T0+3010ms ``` Turn cost is the sum of three distinct inference spans, each with a stable ID and an ordinal that survives out-of-order export. The metric processor no longer sees duplicate `(span_id, usage)` pairs. The `gen_ai.span.reentry_detected` event fires zero times in steady state and once per defect when a runtime regression reintroduces handle reuse—which is the point: the event is the canary, not the fix. The secondary effect is on cost attribution. Because the re-entered B1 had inherited a stale `gen_ai.request.model`, dashboards attributed 2210 input tokens to the wrong SKU. With per-ordinal spans, the model attribute is set at span creation from the actual request, and the SKU attribution is exact. The failure was never "we lost tokens"—it was "we double-counted one inference and mis-attributed another," and both errors are invisible in aggregate token totals because they partially cancel. Only per-span reconciliation surfaces them. The residual risk: a runtime that creates fresh spans per inference but *forgets* to set `gen_ai.agent.inference_ordinal` will still produce correct per-span usage but cannot reconstruct turn-level cost when spans arrive out of order at the collector. The ordinal attribute is the load-bearing field, not the span ID, because span IDs are opaque to the cost aggregator and ordinals are not. ```python from dataclasses import dataclass, field from typing import Optional class PrematureUsageFinalizationError(RuntimeError): """Raised when gen_ai.usage.* is written to an already-ended span, or when a metric exporter sees a duplicate (span_id, usage) export within a single agent turn.""" pass @dataclass class GenAISpan: span_id: str operation: str inference_ordinal: int end_time: Optional[float] = None usage_input: int = 0 usage_output: int = 0 attributes: dict = field(default_factory=dict) def set_usage(self, input_tokens: int, output_tokens: int, now: float) -> None: if self.end_time is not None: raise PrematureUsageFinalizationError( f"span {self.span_id} (ordinal={self.inference_ordinal}) already " f"ended at {self.end_time}; refusing to mutate gen_ai.usage.* " f"after end. Allocate a new span with a fresh inference_ordinal." ) self.usage_input = input_tokens self.usage_output = output_tokens self.attributes["gen_ai.usage.input_tokens"] = input_tokens self.attributes["gen_ai.usage.output_tokens"] = output_tokens class UsageMetricExporter: def __init__(self) -> None: self._seen: dict[tuple[str, int], float] = {} def export(self, span: GenAISpan, end_ts: float) -> None: key = (span.span_id, span.inference_ordinal) if key in self._seen and self._seen[key] != end_ts: raise PrematureUsageFinalizationError( f"duplicate usage export for span_id={span.span_id} " f"ordinal={span.inference_ordinal}: first end_ts=" f"{self._seen[key]}, second end_ts={end_ts}. This is a " f"re-entry artifact; drop the export and emit " f"gen_ai.span.reentry_detected on the parent agent span." ) if span.end_time is None: raise PrematureUsageFinalizationError( f"export of span {span.span_id} before end_time is set; " f"usage is not final." ) self._seen[key] = end_ts # counter increment keyed on (span_id, ordinal, model) — never on turn_id ```