What structural signals indicate span-attribute loss during OpenTelemetry GenAI semantic-convention export from mid-flight agent turns

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*` attributes) for LLM inference, tool-call, and agent-turn spans, where spans are finalized and exported asynchronously by a batch processor. Does not apply to synchronous in-process exporters that block the agent loop, nor to purely metric-based token accounting.

Core Distinction

The failure is not "telemetry is missing." The failure is **attribute divergence between the span as it was opened and the span as it is exported**, caused by mutating `gen_ai.*` attributes *after* the span has been ended but *before* the BatchSpanProcessor flushes it — or, more commonly, by the agent loop writing token-usage and finish-reason attributes in a `finally` block that races the span's own `end()` call. The GenAI conventions assume usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), the response model (`gen_ai.response.model`), and the finish reason (`gen_ai.response.finish_reasons`) are known at `end()` time. Streaming agents frequently are not: the stream terminates, the span ends, and *then* the usage object resolves from the final chunk. The result is a span that is structurally valid, passes schema validation, and silently reports `0` tokens or a missing finish reason — corrupting every cost and budget invariant downstream.

This is distinct from a dropped span. A dropped span is visible as a count mismatch. A diverged span is counted, exported, and wrong.

What Was Observed

A multi-turn agent executing a streaming chat completion with tool calls produced spans with the following signature when inspected at the collector:

The correlation was exact: every affected span corresponded to a turn where the streaming response included a tool call, and the agent's `finally` block awaited the tool dispatch *before* assigning usage. The span had already been ended by the `with tracer.start_as_current_span(...)` context manager exit, which fires before the `finally` assignments execute in the common `try/except/finally` ordering. Attributes set on an ended span are silently discarded by the SDK — no exception, no warning. The span was exported with whatever attributes existed at `end()`.

A second, subtler signal: `gen_ai.response.finish_reasons` was present but wrong (`["stop"]`) on spans where the actual finish reason was `tool_calls`. This occurred because the agent set a default `"stop"` at span start and the real value was written post-`end()`. The default masked the absence.

Condition of Validity

The invariant that must hold for GenAI span telemetry to be trustworthy:

> For every span where `gen_ai.operation.name` is set, all `gen_ai.usage.*` and `gen_ai.response.*` attributes MUST be assigned before `span.end()` is called, and the span MUST NOT be ended by a context manager whose exit ordering precedes attribute resolution.

This is violated whenever any of the following hold:

  1. The span lifetime is tied to a `with` block that exits before the streaming iterator is fully drained.
  2. Usage/finish-reason resolution depends on an `await` that occurs after the `with` block.
  3. A default value for `gen_ai.response.finish_reasons` is set at span start (masks the failure as a wrong value rather than an absent one).
  4. The agent's tool-dispatch path returns control to the span scope before the model's terminal chunk is parsed.

The condition is *valid* (telemetry trustworthy) only when span termination is explicitly sequenced after terminal-chunk parsing and usage extraction, and when no `gen_ai.*` attribute has a start-time default that is semantically meaningful.

Decision Boundary

The boundary is between **attribute-at-end semantics** and **attribute-at-open semantics**. The GenAI conventions are attribute-at-end: they describe the *completed* inference. The SDK's span object is attribute-at-open with a hard cutoff at `end()`. Any agent architecture that resolves GenAI attributes lazily crosses this boundary and loses them.

Operationally, the decision is:

The guardrail is a **pre-end assertion**: before calling `span.end()`, assert that every attribute required by `gen_ai.operation.name` is present and non-defaulted. If not, either delay the end or mark the span with an explicit `gen_ai.telemetry.incomplete = true` attribute so downstream cost aggregation can exclude it rather than trusting a zero.

Operational Effect

Without the guardrail, the downstream effects compound:

The recovery is not retroactive: exported spans are immutable at the collector. The only remediation is structural — detach span termination from context-manager exit, route late usage to a companion span, and add the pre-end completeness assertion so that incomplete telemetry is *labeled* incomplete rather than silently zeroed.

from dataclasses import dataclass, field
from typing import Optional


class GenAISpanAttributeLoss(RuntimeError):
    """Raised when a GenAI span is ended before its terminal attributes resolve."""
    pass


@dataclass
class GenAISpan:
    operation_name: str
    attributes: dict = field(default_factory=dict)
    ended: bool = False

    def set_attribute(self, key: str, value) -> None:
        if self.ended:
            # SDK silently discards; we surface it instead.
            raise GenAISpanAttributeLoss(
                f"attempted to set {key!r} after span.end(); value would be lost"
            )
        self.attributes[key] = value

    def end(self) -> None:
        self.ended = True


REQUIRED_BY_OPERATION = {
    "chat": {
        "gen_ai.usage.input_tokens",
        "gen_ai.usage.output_tokens",
        "gen_ai.response.finish_reasons",
    },
}


def finalize_chat_span(
    span: GenAISpan,
    usage: Optional[dict],
    finish_reasons: Optional[list],
) -> None:
    """Assign terminal attributes, then end. Refuses to end incomplete spans."""
    if span.ended:
        raise GenAISpanAttributeLoss("span already ended before finalize")

    if usage is None or finish_reasons is None:
        # Do not default. Mark incomplete so downstream cost aggregation excludes it.
        span.set_attribute("gen_ai.telemetry.incomplete", True)
        span.end()
        return

    span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
    span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    span.set_attribute("gen_ai.response.finish_reasons", finish_reasons)

    required = REQUIRED_BY_OPERATION.get(span.operation_name, set())
    missing = required - set(span.attributes)
    if missing:
        raise GenAISpanAttributeLoss(
            f"ending {span.operation_name!r} span with missing attributes: {sorted(missing)}"
        )
    span.end()