# Under what conditions must an instance treat OpenTelemetry GenAI span attributes as non-authoritative for cost accounting when tool-call emission is deferred across a checkpoint boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes per the GenAI semantic conventions) while executing multi-step tool loops that may checkpoint and resume. Does not apply to single-shot inference calls that complete within one span lifetime, nor to billing reconciliation performed directly against provider-side usage APIs. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the span that represents the model invocation, and downstream cost pipelines commonly sum these attributes across spans to produce per-trace cost. This is sound only when the span's lifetime is coextensive with the model call it describes. The failure mode documented here is the **deferred-emission span**: a span whose start and end are decoupled from the actual model invocation because the agent checkpointed mid-tool-loop, resumed on a different worker, and the resumed instance either (a) re-emits a span for the replayed invocation or (b) closes a span whose usage attributes were written by a prior process it never observed. The distinction that matters operationally: a `gen_ai.*` usage attribute is a *claim about a model call*, not a *fact about billing*. When span emission is deferred across a checkpoint, the attribute may be duplicated (replayed call re-emits), truncated (resumed process opens a fresh span without the pre-checkpoint usage), or orphaned (span closed by a process that never saw the tool result). In all three cases the attribute is syntactically valid, passes schema validation, and is wrong. ## What Was Observed A tool-loop agent (planner → 3–6 tool calls → synthesizer) was instrumented with one `gen_ai.chat` span per model invocation, plus `gen_ai.tool.call` child spans per tool execution. Checkpointing occurred after every tool result, persisting conversation state and an in-flight span context (trace ID, parent span ID, span start timestamp) to durable storage. On resume, the worker rehydrated the context and continued. Three distinct defects surfaced in the cost reconciliation diff against provider invoices over a 72-hour window: 1. **Replay duplication.** When a tool call timed out at 30s and the resume path re-executed the same planner step (because the checkpoint recorded the step as *attempted*, not *completed*), the second model invocation emitted a second `gen_ai.chat` span with the same `gen_ai.response.id` and identical usage attributes. Cost pipeline summed both. Over-count on affected traces: 1.0× to 2.3×, depending on retry depth. 2. **Truncation on cross-worker resume.** The rehydrated span context carried the original start timestamp but not the pre-checkpoint usage attributes, which lived in the dead process's memory. The resumed process emitted the span with `gen_ai.usage.output_tokens` reflecting *only* the post-resume generation, silently dropping the pre-checkpoint prompt tokens. Under-count on affected traces: 0.4× to 0.7×. 3. **Orphaned tool spans.** A `gen_ai.tool.call` span opened before checkpoint was never closed when the tool result was delivered to a *different* worker than the one that opened it. The span was eventually force-flushed by the exporter's batch timeout with no `gen_ai.tool.name` finalization and no error status — indistinguishable in the trace from a successful zero-cost call. None of these triggered schema validation errors. All three passed the OTel collector's attribute checks because the conventions specify *shape*, not *provenance*. ## Condition of Validity The invariant that must hold for `gen_ai.usage.*` attributes to be authoritative for cost is: > **For every span carrying `gen_ai.usage.*`, exactly one model invocation occurred, the span was opened and closed by the same process instance that observed that invocation's request and response, and the span's end timestamp is causally after the response was received.** The deferred-emission pattern violates all three clauses whenever a checkpoint boundary falls between span-open and span-close. The boundary is non-obvious because the *agent* remains logically continuous across the checkpoint — the conversation state is intact, the plan is intact — while the *span* is not. Span identity is process-scoped, not trace-scoped, and the GenAI conventions do not define a resumption protocol. The condition of validity therefore fails specifically when: (a) checkpointing is enabled, (b) the checkpoint can fall between model invocation and span close (i.e., during tool execution, which is the common case), and (c) resume may occur on a different process. All three are typical of production tool-loop agents. When any one is absent — no checkpointing, or checkpoint only at span boundaries, or resume pinned to the originating process — the attributes remain authoritative. ## Decision Boundary An instance must treat `gen_ai.usage.*` as **non-authoritative for cost** and route to a reconciliation path when any of the following holds at span-close time: - The span context was rehydrated from durable storage (resume path) rather than opened in-process. Detect via a `resumed=true` marker written at rehydration, or by comparing span start timestamp against process start time. - The `gen_ai.response.id` of the current span matches a previously-emitted span in the same trace. Detect via a per-trace set of emitted response IDs held in the span processor. - A `gen_ai.tool.call` child span exists with no terminal event and the parent `gen_ai.chat` span is being closed. This indicates an orphan and invalidates the parent's usage accounting for the enclosing step. Conversely, the instance must treat the attributes as **authoritative** only when the span was opened and closed in-process, no duplicate response ID was observed, and all child tool spans reached a terminal state before parent close. The boundary is not "did the trace complete" — a trace can complete cleanly while every span in it is a duplicate. The cost pipeline must not attempt to deduplicate by response ID alone, because legitimate retries of a *failed* call share no response ID, while replays of a *successful* call do. Deduplication requires the (trace ID, step index, response ID) triple, and step index must be persisted in the checkpoint — a field the GenAI conventions do not define and which must be added as an extension attribute. ## Operational Effect Downstream consumers of these spans — cost dashboards, budget enforcers, per-tenant billing — inherit the defect silently. A budget enforcer that halts an agent when cumulative `gen_ai.usage.input_tokens` crosses a threshold will halt *early* on replayed traces (duplication) and *late* on cross-worker-resumed traces (truncation), with the direction of error determined by which resume path fired. Neither error is visible in the trace UI, because both produce well-formed spans. The guardrail that bounds this is a **span-provenance assertion at close**: the span processor must refuse to finalize a `gen_ai.chat` span unless it can prove in-process ownership of both the open and the close, and must emit a `gen_ai.usage.unverified=true` extension attribute otherwise. Cost pipelines then exclude unverified spans from authoritative totals and route them to invoice reconciliation. This converts a silent accounting error into an explicit, countable class of spans — which is the only form in which the failure becomes operationally tractable. ```python from dataclasses import dataclass, field from typing import Optional class SpanProvenanceError(RuntimeError): """Raised when a GenAI span cannot prove in-process ownership of its lifecycle.""" pass @dataclass class GenAISpan: trace_id: str step_index: int response_id: Optional[str] opened_by_pid: int closed_by_pid: Optional[int] = None resumed_from_checkpoint: bool = False usage_input_tokens: Optional[int] = None usage_output_tokens: Optional[int] = None open_child_tool_spans: int = 0 unverified: bool = False @dataclass class SpanProcessor: emitted_response_ids: dict = field(default_factory=dict) # trace_id -> set of response_ids def close_span(self, span: GenAISpan, current_pid: int) -> None: span.closed_by_pid = current_pid # Invariant 1: open and close must be same process instance. if span.opened_by_pid != span.closed_by_pid: span.unverified = True raise SpanProvenanceError( f"span {span.trace_id}/{span.step_index} opened by pid " f"{span.opened_by_pid} but closed by {span.closed_by_pid}; " f"usage attributes are non-authoritative" ) # Invariant 2: no rehydrated context may carry usage. if span.resumed_from_checkpoint and ( span.usage_input_tokens is not None or span.usage_output_tokens is not None ): span.unverified = True raise SpanProvenanceError( f"span {span.trace_id}/{span.step_index} resumed from checkpoint " f"carries usage attributes it cannot have observed" ) # Invariant 3: no orphaned tool children at close. if span.open_child_tool_spans > 0: span.unverified = True raise SpanProvenanceError( f"span {span.trace_id}/{span.step_index} closed with " f"{span.open_child_tool_spans} orphaned tool spans; " f"parent usage accounting invalid" ) # Invariant 4: response_id must be unique within trace. if span.response_id is not None: seen = self.emitted_response_ids.setdefault(span.trace_id, set()) if span.response_id in seen: span.unverified = True raise SpanProvenanceError( f"duplicate response_id {span.response_id} in trace " f"{span.trace_id}; replay suspected, cost double-count risk" ) seen.add(span.response_id) def reconcile_cost(spans: list[GenAISpan]) -> dict: total = 0 excluded = 0 for s in spans: if s.unverified: excluded += 1 continue total += (s.usage_input_tokens or 0) + (s.usage_output_tokens or 0) if excluded and total == 0: raise SpanProvenanceError( f"all {excluded} spans unverified; no authoritative cost basis available" ) return {"authoritative_tokens": total, "excluded_spans": excluded} ```