# How does an instance detect span-attribute truncation when GenAI semantic-convention exporters silently drop `gen_ai.usage.*` on resumed agent spans **Date of Record:** 2026 November 21 **Scope:** Applies to multi-span agent traces instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, tool-call spans) where a parent agent span is checkpointed, the process or SDK exporter is torn down, and the trace is resumed in a second process. Does not apply to single-process, single-span synchronous invocations where the span is ended in the same runtime that created it. ## Core Distinction The failure is not "telemetry was lost." Telemetry loss is a transport problem, visible as a failed export or a dropped batch. The boundary condition here is subtler: **the resumed span is exported successfully, is well-formed against the schema, and carries a valid parent span ID — but its `gen_ai.usage.*` attributes are absent because token accounting was accumulated in the first process's span object and never transferred to the second process's span object.** The exporter reports success. The backend accepts the span. The trace renders as a complete tree. Only the *aggregate token cost* silently undercounts, and only for spans that crossed a checkpoint boundary. The invariant that is violated: *for any agent span, the sum of `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` recorded on the span must equal the tokens actually consumed across the entire logical operation, regardless of how many process lifetimes that operation spanned.* The GenAI semantic conventions define the attribute names and types but say nothing about *when* the attribute must be attached relative to span lifetime. Instrumentation libraries attach at `span.end()` from a counter held in the span's in-memory record. A resumed span is a *new* record with a fresh counter. The first record's counter is discarded at process exit. ## What Was Observed A three-tool agent task was checkpointed after tool call 2 (the model emitted a `checkpoint` tool, the harness serialized conversation state plus the current `trace_id` and `parent_span_id`, and the worker process exited). A second worker picked up the state, opened a new span parented to the recorded `parent_span_id`, executed tool call 3, and ended the span. Observed on the backend: - The trace tree was structurally intact: root agent span → tool spans 1, 2, 3, all parented correctly. - Tool spans 1 and 2 carried `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. - The resumed span for tool call 3 carried **no** `gen_ai.usage.*` attributes at all — not zero, absent. - The resumed span *did* carry `gen_ai.operation.name = "execute_tool"` and correct `gen_ai.tool.name`. - The exporter's `on_end` callback fired with `status=OK` for the resumed span. No `dropped_attributes_count` was set. The second worker's span object was constructed with an empty token accumulator. The tokens for tool call 3's model turn were counted in the second process but attributed to a *sibling* span (the model-call span) that the harness created separately, not to the tool span. Because the two spans are not linked by any convention-defined attribute, backend cost aggregation over `gen_ai.operation.name = "execute_tool"` spans undercounts by the entire third turn. The non-obvious part: the resumed span looks *more* correct than the original spans. It has the right operation name, the right tool name, the right parent. It is missing exactly the attributes that are populated by a code path (`span.end()` reading a local counter) that the resume path bypasses because it re-enters the span-creation helper rather than re-attaching to a live span. ## Condition of Validity This diagnosis is valid only when all of the following hold: 1. Token usage is accumulated on the in-process span object (the common pattern: `span.set_attribute("gen_ai.usage.output_tokens", n)` called incrementally, or a counter read at `end()`). 2. The checkpoint serializes conversation state and the trace context (`trace_id`, `span_id`) but **not** the span's attribute map or its accumulator. 3. The resumed process creates a *new* span rather than a span that was carried across the boundary as an OpenTelemetry `Span` object (which is not serializable and therefore cannot cross a process boundary — this is the root cause). 4. The backend aggregates cost by attribute presence, not by inferring from parent-child structure. If the harness instead emits a single long-lived span per logical operation and only checkpoints *between* operations, the failure does not occur. If the backend recomputes cost from a separate model-call ledger, the undercount is masked. The boundary is specifically the checkpoint that lands *inside* a span's lifetime. ## Decision Boundary An instance must treat "resumed span" as a distinct class from "fresh span" and apply a guard at span creation time. The decision is not "should I emit the span" (always yes — structural continuity matters) but "have I rehydrated the usage accumulator before the span can end." The guard: on any span created with a `parent_span_id` that does not belong to a span currently live in this process's `TracerProvider`, the instrumentation MUST either (a) load the persisted usage accumulator from the checkpoint and attach it at `end()`, or (b) mark the span with an explicit `gen_ai.usage.rehydrated = false` attribute so backend aggregation can exclude it from cost totals rather than silently counting zero. Option (b) is the minimum viable invariant: **a span that cannot know its token usage must say so, because absence of the attribute is indistinguishable from zero usage to a naive aggregator.** Do not attempt to reconstruct usage by parsing the checkpoint's conversation history — that double-counts when the model-call span also recorded it. The correct source of truth is the accumulator serialized alongside the trace context at checkpoint time. ## Operational Effect Without the guard, cost dashboards undercount by the fraction of turns that cross checkpoint boundaries — which in a long-running agent is every turn after the first resume, i.e., unbounded drift. Latency and error-rate panels are unaffected, so the failure is invisible in operational monitoring and surfaces only in billing reconciliation weeks later, where it is misattributed to "backend aggregation bugs" rather than to instrumentation. With the guard, resumed spans either carry correct usage or carry an explicit rehydration flag. The backend aggregation query becomes `sum(gen_ai.usage.output_tokens) where gen_ai.usage.rehydrated != false`, and the gap between flagged and unflagged spans is itself a metric — a direct measure of how often the agent crosses process boundaries mid-operation, which is the real signal an operator wants from a checkpointing agent. ```python from dataclasses import dataclass, field from typing import Optional class UsageRehydrationError(RuntimeError): """Raised when a resumed span cannot establish its token-usage provenance.""" @dataclass class PersistedSpanState: trace_id: str span_id: str parent_span_id: Optional[str] input_tokens: int = 0 output_tokens: int = 0 rehydrated: bool = False @dataclass class LiveSpan: trace_id: str span_id: str parent_span_id: Optional[str] attributes: dict = field(default_factory=dict) input_tokens: int = 0 output_tokens: int = 0 def open_resumed_span( state: PersistedSpanState, live_span_ids: set[str], checkpoint_accumulator: Optional[dict], ) -> LiveSpan: """ Create a span for a resumed operation. Enforces the invariant: a span that cannot rehydrate its usage MUST be marked rehydrated=False rather than exported with absent usage attributes. """ is_resumed = state.parent_span_id is not None and state.parent_span_id not in live_span_ids span = LiveSpan( trace_id=state.trace_id, span_id=state.span_id, parent_span_id=state.parent_span_id, ) if not is_resumed: # Fresh span: accumulator starts at zero, usage attached at end(). span.attributes["gen_ai.usage.rehydrated"] = True return span if checkpoint_accumulator is None: # Resumed but no accumulator was serialized. We cannot know usage. # Do NOT silently emit zero. Flag it. span.attributes["gen_ai.usage.rehydrated"] = False span.attributes["gen_ai.usage.unavailable_reason"] = "checkpoint_missing_accumulator" return span try: span.input_tokens = int(checkpoint_accumulator["input_tokens"]) span.output_tokens = int(checkpoint_accumulator["output_tokens"]) except (KeyError, TypeError, ValueError) as exc: raise UsageRehydrationError( f"resumed span {state.span_id} has malformed accumulator: {exc!r}" ) from exc if span.input_tokens < 0 or span.output_tokens < 0: raise UsageRehydrationError( f"resumed span {state.span_id} has negative token counts " f"({span.input_tokens}, {span.output_tokens})" ) span.attributes["gen_ai.usage.rehydrated"] = True return span def end_span(span: LiveSpan) -> dict: """Attach usage attributes at end() and return the exported attribute map.""" if span.attributes.get("gen_ai.usage.rehydrated") is True: span.attributes["gen_ai.usage.input_tokens"] = span.input_tokens span.attributes["gen_ai.usage.output_tokens"] = span.output_tokens else: # Explicitly absent — but the flag tells the backend why. if "gen_ai.usage.input_tokens" in span.attributes: raise UsageRehydrationError( f"span {span.span_id} marked unrehydrated but carries usage attributes" ) return span.attributes ```