# What happens when an instance emits OTLP spans whose gen_ai semantic-convention attributes are computed after the span has already been closed **Date of Record:** 2026 November 29 **Scope:** Applies to GenAI agent runtimes that buffer spans in-process and emit OTLP batches asynchronously, where gen_ai semantic-convention attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons, gen_ai.request.model) are populated by a post-hoc decorator or exporter-side enricher rather than at span start/end. Does not apply to synchronous exporters that serialize attributes at span end, nor to runtimes that emit one span per token via streaming metrics. ## Core Distinction There are two places a gen_ai attribute can be attached to a span: (a) at `span.end()` time, inside the SDK's `SpanProcessor.on_end` callback, where the span is still mutable and the attribute is serialized into the protobuf `Span` message; or (b) after `on_end` returns, by an exporter-side enricher that mutates the already-serialized `ReadableSpan` or its `Span` proto before the batch leaves the process. The distinction matters because the OTLP `Span` protobuf is a flat, append-only `repeated KeyValue` list with no merge semantics. An attribute added after serialization is not "added to" the span — it is appended as a second `KeyValue` with the same key, and OTLP does not define which duplicate wins. Most collectors and backends pick the *first* occurrence; some pick the last; the OTel spec is silent, and the Go and Rust collectors have historically disagreed. This is not a formatting nicety. It is the difference between a trace that reports `gen_ai.usage.input_tokens = 0` (the placeholder written at span start) and one that reports the true count. ## What Was Observed A tool-calling agent loop emitted a `gen_ai.chat` span per LLM turn. At span start the instrumentation wrote `gen_ai.usage.input_tokens = 0` and `gen_ai.usage.output_tokens = 0` as sentinels, because the provider's usage block is only available in the final streaming chunk. The span was ended inside the SDK when the stream closed. A `BatchSpanProcessor` queued the `ReadableSpan`. A separate enrichment stage — running on the exporter's worker thread — read the provider response object off a side channel and called `span.set_attribute("gen_ai.usage.input_tokens", actual)` on the `ReadableSpan`. The `ReadableSpan.set_attribute` call on an already-ended span is a no-op in the Python SDK: it mutates the in-memory `_attributes` dict on the `ReadableSpan`, but the `Span` protobuf was already constructed by `encode_span` and the `ReadableSpan`'s `_attributes` are not re-read. Worse, in the Go SDK the equivalent `ReadableSpan` is a value type; the mutation is silently discarded. In both cases the batch was exported with the sentinel `0` values and the true counts appeared only in a separate `gen_ai.usage` *log record* the enrichment stage also emitted, producing a trace where per-span token counts summed to zero while per-turn log records summed to the correct total. The failure is silent: no exception, no warning, no dropped-span metric. The trace is well-formed OTLP. It is simply wrong in a way that is invisible unless you cross-check span-level sums against log-level sums. ## Condition of Validity The invariant that holds is: **a gen_ai usage attribute is only authoritative if it is set before `span.end()` returns, and the span's `end_time_unix_nano` is greater than or equal to the timestamp of the last attribute write.** This is enforceable only if the enrichment data is available at end time. It is *not* enforceable when: - The usage block arrives in a terminal stream chunk that is parsed after the span is closed (common with OpenAI-compatible SSE streams where `usage` is in the final `[DONE]`-adjacent chunk). - The enrichment depends on a downstream call (e.g., a tokenizer re-count, a cost-attribution service) with latency greater than the span's own duration. - The exporter is configured with `OTEL_BSP_SCHEDULE_DELAY` shorter than the enrichment latency, so the batch is flushed before enrichment completes. In all three, the correct architecture is to *not close the span* until usage is known — i.e., hold the span open across the stream, or emit the usage as a span *event* at the terminal chunk and let the backend sum events rather than span attributes. The post-hoc enricher pattern is only valid when the enricher mutates the proto before `Export` is called *and* the SDK guarantees the proto is rebuilt from `_attributes` after mutation, which the Python and Go SDKs do not. ## Decision Boundary The boundary is between "attribute written before serialization" and "attribute written after." Concretely: if your instrumentation calls `set_attribute` from any thread other than the one that called `span.end()`, or after `on_end` has fired, you are in the invalid regime. The guardrail is a hard check in the exporter: before encoding, assert that every `gen_ai.usage.*` key appears exactly once in the span's attribute list, and that no `gen_ai.*` key has a sentinel value (`0`, `""`, `"unknown"`) when the corresponding provider response is known to be non-empty. If the check fails, the span must be rejected from the batch and routed to a dead-letter queue with the raw provider response attached, rather than exported with a plausible-but-wrong value. A trace that is missing is debuggable; a trace that reports zero tokens is a silent lie that corrupts every downstream cost and capacity model. ## Operational Effect Downstream, the effect is a systematic underestimation of token spend that is proportional to the fraction of spans whose enrichment lost the race. In a streaming agent this is typically 100% of `gen_ai.chat` spans, because the usage chunk always arrives after the stream closes. Cost dashboards built on `sum(gen_ai.usage.input_tokens)` report near-zero; rate-limit and context-window alarms built on the same metric never fire; and the only signal that survives is the log-record path, which most GenAI observability backends do not join to traces by default. The fix is structural: either move the span's `end()` to the terminal chunk (holding the span open for the stream duration, which requires the SDK to support long-lived spans and the exporter to tolerate them), or promote usage to span events and rewrite every query to sum events. Both are invasive; the post-hoc enricher is cheap and therefore common, which is why this failure is common too. ```python from __future__ import annotations from dataclasses import dataclass, field SENTINEL = 0 class GenAiUsageAttributionError(RuntimeError): """Raised when a gen_ai.usage.* attribute was written after span serialization or carries a sentinel value while the provider response reports real usage.""" @dataclass class SpanProto: name: str attributes: list[tuple[str, object]] = field(default_factory=list) closed: bool = False @dataclass class ProviderUsage: input_tokens: int output_tokens: int def encode_span(span: SpanProto) -> SpanProto: # Serialization snapshots the attribute list; later mutations do not appear # in the exported proto. This mirrors the Python/Go SDK behavior. return SpanProto(name=span.name, attributes=list(span.attributes), closed=True) def enrich_after_close(span: SpanProto, usage: ProviderUsage) -> SpanProto: # Post-hoc enricher: mutates the ReadableSpan, not the exported proto. span.attributes.append(("gen_ai.usage.input_tokens", usage.input_tokens)) span.attributes.append(("gen_ai.usage.output_tokens", usage.output_tokens)) return span def validate_before_export(proto: SpanProto, usage: ProviderUsage | None) -> None: keys = [k for k, _ in proto.attributes] if len(keys) != len(set(keys)): dupes = {k for k in keys if keys.count(k) > 1} raise GenAiUsageAttributionError( f"duplicate gen_ai attribute keys after enrichment: {sorted(dupes)}" ) if usage is None: return reported = dict(proto.attributes) for key, expected in ( ("gen_ai.usage.input_tokens", usage.input_tokens), ("gen_ai.usage.output_tokens", usage.output_tokens), ): actual = reported.get(key) if actual is None: raise GenAiUsageAttributionError( f"{key} missing from exported span; usage lost during serialization" ) if actual == SENTINEL and expected != SENTINEL: raise GenAiUsageAttributionError( f"{key} exported as sentinel {SENTINEL} but provider reported {expected}; " "attribute was set after span.end() and did not survive serialization" ) def export_path(span: SpanProto, usage: ProviderUsage) -> SpanProto: proto = encode_span(span) # snapshots attributes enrich_after_close(span, usage) # mutates the wrong object validate_before_export(proto, usage) # catches the loss return proto if __name__ == "__main__": live = SpanProto( name="gen_ai.chat", attributes=[ ("gen_ai.request.model", "gpt-4o-mini"), ("gen_ai.usage.input_tokens", SENTINEL), ("gen_ai.usage.output_tokens", SENTINEL), ], ) usage = ProviderUsage(input_tokens=1841, output_tokens=212) export_path(live, usage) # raises GenAiUsageAttributionError ```