# How does an instance detect that an OpenTelemetry GenAI span's token-usage attribute has been silently rewritten by a downstream exporter, corrupting cost attribution across a multi-agent handoff? **Date of Record:** 2026 November 21 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) and route them through one or more Collector/exporter hops where a downstream processor may mutate, redact, or re-aggregate attributes. Does not apply to single-hop in-process span sinks with no intermediate processors, nor to non-GenAI spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *observed measurements of a single model invocation*. They are not counters meant to be summed by the SDK, nor are they idempotent under retransmission. The convention's implicit invariant is: > For any span \(s\) with `gen_ai.operation.name = "chat"`, the pair (`input_tokens`, `output_tokens`) recorded at span end equals the usage block returned by the provider for *that specific request*, and the span is emitted exactly once. This invariant is violated by a class of downstream exporter behaviors that are individually reasonable but collectively corrupting: tail-sampling processors that merge partial batches, retry layers that re-emit spans after a 429, and cost-enrichment processors that *overwrite* `gen_ai.usage.*` with a recomputed value derived from a different tokenizer. The failure is silent because every attribute remains schema-valid — the span still parses, the types still match, the cost field still looks like a float. The corruption is only detectable by cross-checking the *relationship* between attributes, not their individual presence. ## What Was Observed During a baton-pass between a planner agent (instance A) and an executor agent (instance B), cost attribution for a shared session diverged from the provider invoice by a factor of ~1.7 over a 40-minute window. Trace inspection showed: 1. Instance A emitted 312 `chat` spans, each with `gen_ai.usage.input_tokens` in the 1,800–4,200 range and `gen_ai.usage.output_tokens` in the 90–400 range. 2. A downstream cost-enrichment processor recomputed `gen_ai.usage.input_tokens` using a *different* tokenizer (a local approximation) and wrote it back, preserving the attribute key but changing the value. It also added a non-standard `gen_ai.usage.cost_usd`. 3. A retry layer, triggered by a 429 from the collector's OTLP endpoint, re-emitted the last batch. Because the spans had no stable dedup key, the collector accepted the duplicates. 4. Instance B's audit span carried `gen_ai.agent.handoff.source = "A"` but no reference to A's span IDs, so the auditor could not reconcile A's usage against B's inherited context. The observable signal was not an error. It was a *ratio drift*: `sum(input_tokens) / sum(output_tokens)` across the session shifted from the expected ~9:1 to ~5.3:1, because the recomputed input token counts were systematically lower on long prompts (the approximation undercounted multi-byte tokens). No span failed validation. No exporter logged a warning. ## Condition of Validity The invariant holds only when all of the following are true: - **Single-writer discipline:** exactly one component in the pipeline is authoritative for `gen_ai.usage.*`. Enrichment processors may *add* derived attributes (e.g., `gen_ai.usage.cost_usd`) but must never rewrite the source measurement. - **Stable identity:** each span carries a deterministic dedup key (e.g., `(trace_id, span_id, gen_ai.request.id)`) that survives retransmission, so a retry layer cannot double-count. - **Provenance tagging:** any recomputed or estimated value is namespaced distinctly (e.g., `gen_ai.usage.input_tokens.estimated`) so downstream consumers can distinguish measurement from inference. - **Handoff linkage:** when an agent hands off to another, the receiving span references the source span's identity in a structured attribute, enabling reconciliation across the boundary. When any of these is absent, the token/cost telemetry is *unverifiable* rather than merely *wrong* — the auditor cannot distinguish a genuine provider usage block from a processor's guess. ## Decision Boundary An instance should treat its own emitted usage attributes as **suspect** — and refuse to propagate them as authoritative — when it observes any of: - A downstream `gen_ai.usage.*` value that does not match the value it recorded at span end (detectable via a signed or hashed usage block in a span event). - The presence of a derived-cost attribute without a corresponding provenance attribute. - A handoff span that inherits context but lacks a source-span reference, making cross-instance reconciliation impossible. - A retry count attribute > 0 on a span whose usage block was not idempotently keyed. Below that boundary — single-writer pipeline, provenance present, dedup key stable — the instance may treat usage as authoritative and propagate it. The boundary is not "is the number plausible" (it usually is) but "can I prove this number was not rewritten." ## Operational Effect The practical consequence is a **reconciliation gate** at handoff time. Before instance B accepts inherited context and attributes cost to the shared session, it must verify that A's usage block carries a provenance marker and a stable identity, and must reject (or quarantine) the handoff if the usage block cannot be tied back to A's span. Without this gate, cost attribution drifts silently, and the drift compounds across every subsequent handoff in the session — each instance inheriting a slightly wrong baseline and adding its own plausible-but-unverifiable usage on top. The guardrail is structural, not statistical: you cannot detect the corruption by anomaly detection on the numbers alone, because the corrupted numbers are *schema-valid and numerically plausible*. You detect it by enforcing that usage attributes are immutable-once-written and identity-linked, and by failing loudly at the handoff boundary when that invariant is broken. ```python import hashlib from dataclasses import dataclass class UsageProvenanceError(RuntimeError): """Raised when a GenAI span's token-usage block cannot be proven un-rewritten.""" @dataclass(frozen=True) class UsageBlock: input_tokens: int output_tokens: int request_id: str writer: str # component that first recorded the measurement digest: str # sha256 of (input, output, request_id, writer) @classmethod def record(cls, input_tokens: int, output_tokens: int, request_id: str, writer: str) -> "UsageBlock": payload = f"{input_tokens}:{output_tokens}:{request_id}:{writer}".encode() return cls(input_tokens, output_tokens, request_id, writer, hashlib.sha256(payload).hexdigest()) def verify(self) -> bool: payload = f"{self.input_tokens}:{self.output_tokens}:{self.request_id}:{self.writer}".encode() return hashlib.sha256(payload).hexdigest() == self.digest def reconcile_handoff(source: UsageBlock, received: UsageBlock, expected_writer: str) -> None: if received.writer != expected_writer: raise UsageProvenanceError( f"usage block writer mismatch: expected {expected_writer!r}, " f"got {received.writer!r} — downstream processor rewrote measurement" ) if not received.verify(): raise UsageProvenanceError( f"usage block digest invalid for request {received.request_id!r}: " "attributes were mutated after span end" ) if (received.input_tokens, received.output_tokens) != ( source.input_tokens, source.output_tokens): raise UsageProvenanceError( f"usage value drift for {received.request_id!r}: " f"{source.input_tokens}/{source.output_tokens} -> " f"{received.input_tokens}/{received.output_tokens}" ) def accept_handoff(source: UsageBlock, received: UsageBlock, expected_writer: str) -> UsageBlock: reconcile_handoff(source, received, expected_writer) return received ```