# Which invariants prevent token-accounting drift from silently corrupting GenAI span trees under retry and streaming **Date of Record:** 2026 November 24 **Scope:** Applies to agents emitting OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*`) where a single logical tool call or model turn may be retried, streamed incrementally, or replayed across multiple span objects. Does not cover pure metrics pipelines or log-only instrumentation without span context. ## Core Distinction The GenAI semantic conventions describe *what attributes a span should carry* — `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.request.model`. They do **not** define an invariant on *how many spans may carry usage attributes for one logical operation*. This is the boundary. A single agent turn that is retried three times because of a 429, a tool-call schema mismatch, or a streaming connection reset can produce three sibling spans, each of which is individually convention-compliant because each genuinely consumed tokens. Downstream cost aggregation that sums `gen_ai.usage.*` across a trace then over-counts by the retry factor — and there is no attribute in the spec that distinguishes "authoritative final attempt" from "abandoned partial attempt." The invariant that must be enforced by the *emitter*, not the spec, is: **exactly one span per logical operation carries the authoritative usage attributes; every other attempt carries usage but is marked non-authoritative via a stable attribute key.** The spec gives you `gen_ai.usage.*`; it does not give you `gen_ai.usage.authoritative`. ## What Was Observed An agent runtime wrapping a provider SDK emitted one span per HTTP attempt under a parent `gen_ai.operation.name=chat` span. Under normal conditions the tree looked clean: one child span, usage on the child. Under a retry storm (provider returning 529s), the tree grew to N children, each with `gen_ai.usage.input_tokens` set to the *full prompt token count* because the SDK reports usage on the request object regardless of whether the response body was consumed. The parent span carried no usage. A cost dashboard summing leaf usage reported 4.1× actual spend for the incident window. A second, subtler failure appeared with streaming. When a stream was aborted mid-generation (`gen_ai.response.finish_reasons` absent, span status `ERROR`), the partial `output_tokens` were still recorded from the last delta. A subsequent successful retry recorded the *complete* output tokens. Both spans were valid; the sum double-counts the shared prefix of generated tokens. Because the spec does not require `gen_ai.response.id` on errored spans, the two attempts could not be deduplicated by response identity — only by `trace_id` + `gen_ai.operation.name` + timestamp ordering, which is heuristic. ## Condition of Validity The guardrail holds only under these conditions: 1. The emitter owns a *logical operation identifier* that is stable across retries — typically the parent span's `span_id`, or an explicit `gen_ai.operation.id` attribute if you introduce one. Retries must be children of, or siblings tagged with, that identifier. 2. Exactly one attempt is designated authoritative at the moment the logical operation completes — the attempt whose response the agent actually used. This must be decided by the caller, not the transport layer. 3. Streaming spans must record `gen_ai.response.finish_reasons` only when a terminal finish reason was received; a span without finish reasons is by definition non-authoritative for output-token accounting. 4. Aggregators must be written to sum only authoritative spans, and to treat non-authoritative spans as *diagnostic*, not *billable*. If any of these fails — most commonly (2), because retry logic is usually buried in a transport interceptor that has no notion of "which attempt won" — the invariant is unenforceable at aggregation time and the drift is unrecoverable from the trace alone. ## Decision Boundary The decision the emitter faces at span-close time is: *does this attempt's usage reflect tokens the agent will actually be billed for and whose output it consumed?* Three cases: - **Attempt succeeded and its response was parsed into agent state** → authoritative. Emit usage, emit finish reasons, set `gen_ai.usage.authoritative=true`. - **Attempt failed before response body** (connection reset, 5xx before first token) → non-authoritative for output, but input tokens *were* consumed by the provider and are typically billed. Emit `input_tokens` with `authoritative=false`; do not emit `output_tokens`. - **Attempt streamed partially then aborted** → the partial output tokens are real spend but not usable output. Emit both with `authoritative=false` and a `gen_ai.response.aborted=true` marker; the aggregator must count these as cost but not as generated content. The boundary that trips most implementations: they conflate "span succeeded" (status OK) with "authoritative." A span can be OK and non-authoritative (a successful attempt that was discarded because a parallel hedged request returned first), and a span can be ERROR and partially authoritative for input tokens. Status and authority are orthogonal axes. ## Operational Effect Enforcing the invariant changes three downstream behaviors. First, cost dashboards stop drifting during retry storms — the over-count factor collapses to 1.0 because non-authoritative spans are excluded by attribute, not by heuristic. Second, token-budget enforcement inside the agent loop becomes correct: a budget check that reads `gen_ai.usage.output_tokens` from the last span must read the last *authoritative* span, otherwise an aborted stream can push the agent into premature budget exhaustion. Third, trace replay for debugging becomes deterministic: given a logical operation id, the authoritative span is recoverable without timestamp heuristics, so an auditor replaying the trace reconstructs the same agent state the runtime saw. The failure mode when the invariant is absent is not a crash. It is a slow, silent skew between the trace and reality that only surfaces when someone reconciles the trace against the provider invoice — by which point the trace has been rotated out of retention. ```python from dataclasses import dataclass, field from typing import Optional class NonAuthoritativeUsageError(RuntimeError): """Raised when a span claims authoritative usage without satisfying the invariant.""" pass @dataclass class GenAISpan: span_id: str operation_id: str operation_name: str status: str # "OK" | "ERROR" input_tokens: Optional[int] = None output_tokens: Optional[int] = None finish_reasons: Optional[list] = None aborted: bool = False authoritative: bool = False def close_attempt_span( span: GenAISpan, *, response_consumed: bool, terminal_finish_reason: bool, ) -> GenAISpan: """Apply the authority invariant at span-close time. Authority requires: response was consumed by the agent AND a terminal finish reason was observed. Anything else is diagnostic-only. """ if response_consumed and terminal_finish_reason: span.authoritative = True return span # Non-authoritative path: input tokens are real spend, output tokens # are only real if the stream produced them before abort. if span.output_tokens is not None and not span.aborted: raise NonAuthoritativeUsageError( f"span {span.span_id} has output_tokens={span.output_tokens} " f"but was not consumed and not marked aborted; cannot classify" ) span.authoritative = False return span def aggregate_authoritative_usage(spans: list[GenAISpan]) -> dict: """Sum usage across a trace, counting only authoritative spans for output accounting, all spans for input accounting.""" by_op: dict[str, dict] = {} for s in spans: bucket = by_op.setdefault( s.operation_id, {"input": 0, "output": 0, "authoritative_found": False} ) if s.input_tokens: bucket["input"] += s.input_tokens if s.authoritative: if bucket["authoritative_found"]: raise NonAuthoritativeUsageError( f"operation {s.operation_id} has multiple authoritative spans" ) bucket["authoritative_found"] = True if s.output_tokens: bucket["output"] += s.output_tokens return by_op ```