# How does an instance detect semantic-convention drift in span attributes before it corrupts token-level cost attribution **Date of Record:** 2026 December 3 **Scope:** Applies to observability pipelines where LLM agents emit OpenTelemetry-style spans whose `gen_ai.*` attributes (prompt/completion token counts, model, cache-hit flags) are aggregated into per-tenant cost ledgers via semantic-convention mappings. Does not apply to pipelines that record cost at the billing-provider boundary (e.g., reading the invoice directly) or to single-tenant systems with no attribution key. ## Core Distinction The distinction that matters is between **schema drift** and **semantic drift**. Schema drift is detectable: an attribute disappears, changes type, or a new key appears, and the collector's validation layer rejects or quarantines the span. Semantic drift is silent: the attribute name, type, and presence are unchanged, but its *meaning* has shifted for a subset of emitters. The canonical case is `gen_ai.usage.input_tokens`. In one emitter revision it means "tokens billed as input, including cache reads at their discounted rate." In the next it means "tokens physically present in the prompt, with cache reads broken out into `gen_ai.usage.cache_read_input_tokens`." Both are valid under the semantic convention as written; both pass schema validation; both are integers. The cost ledger, however, now double-counts cache reads for every span from the new emitter, because the mapping `cost = input_tokens * input_rate` was calibrated against the old meaning. An instance cannot detect this from the span alone. It must detect it from a *relationship between spans* — specifically, the invariant that the sum of a span's usage components must equal the usage reported by the provider for the same request, and that this equality must hold *across emitters* for the same model and workload shape. ## What Was Observed A fleet of agent workers (three emitter versions, v1.4, v1.7, v1.9) emitted spans for a shared prompt-caching workload against the same upstream model. The cost ledger aggregated `input_tokens * rate` per tenant. Over a 36-hour window, tenant `acme` cost rose 41% with no change in request volume, model, or prompt content. Trace replay showed the mechanism precisely: 1. v1.9 began emitting `gen_ai.usage.input_tokens` as the *non-cached* input count, and added `gen_ai.usage.cache_read_input_tokens` as a sibling attribute. 2. The collector's semantic-convention mapping for v1.9 had not been updated. It summed `input_tokens` and ignored `cache_read_input_tokens` — which is the correct behavior for v1.4/v1.7 semantics, where `input_tokens` already included cache reads. 3. For v1.9 spans, the ledger therefore billed the *non-cached* portion at full rate (correct) but also billed a phantom "cache read" quantity that was never in `input_tokens` — no, worse: it billed `input_tokens` at full rate, which was now *smaller*, so raw token cost went *down*. The 41% rise came from a second-order effect: the mapping's fallback branch, triggered because `input_tokens` for v1.9 was now frequently below a per-request floor of 1, treated the missing cache-read component as a *retry*, and the retry-attribution rule charged the full prompt again. The failure was not the meaning shift. It was that the mapping's fallback branch (`if input_tokens < floor: assume retry, charge full prompt`) was a guardrail written for a world where `input_tokens` was always the full prompt count. When the meaning changed, the guardrail fired on legitimate small prompts and mis-attributed them as retries. The invariant that would have caught it: **for any (model, prompt-template, cache-state) tuple, the distribution of `input_tokens` across emitters must be identical up to the cache-read component.** A per-emitter distribution comparison (Kolmogorov–Smirnov or even a simple median/quantile check) would have flagged v1.9's `input_tokens` as shifted by exactly the cache-read volume, within the first hundred spans. ## Condition of Validity This detection method is valid only when all of the following hold: - The same workload shape (prompt template, cache warm/cold state, model) is exercised by at least two emitter versions within the observation window. If v1.9 is the only emitter for a workload, there is no cross-emitter reference and the drift is undetectable until a provider-side reconciliation. - The provider reports a ground-truth usage figure (billed tokens or a usage endpoint) that can be joined to spans by request ID. Without this anchor, the pipeline can only detect *internal inconsistency*, not *external incorrectness*. - Cache-hit rate is stable enough that a shift in `input_tokens` distribution is attributable to semantic change rather than workload change. If the workload's cache-hit rate itself moved, the two effects are confounded and the check must be suspended or conditioned on cache-state labels. - The mapping's fallback branches are enumerable and their trigger conditions are expressible as predicates over span attributes. A fallback that depends on external state (e.g., "assume retry if the previous span in the trace failed") cannot be validated by this method alone. It does **not** hold when emitters are versioned per-request rather than per-worker (mixed versions in a single trace), because the cross-emitter comparison must then be done at the span level with version as a grouping key, and the sample size per group collapses. ## Decision Boundary The operational decision is: **when does a distribution shift in a usage attribute warrant quarantining the emitter's spans from the cost ledger, versus continuing to bill and flagging for review?** The boundary is drawn at the point where the shift is *explainable by a known sibling attribute*. Concretely: - If the shift in `input_tokens` median for emitter `E` is within ±5% of the volume reported in a sibling attribute (`cache_read_input_tokens`, `cache_creation_input_tokens`) for the same spans, the drift is consistent with a known semantic-convention variant. Bill using the variant-aware mapping, flag the emitter for mapping update, do not quarantine. - If the shift is *not* explained by any sibling attribute, the emitter's semantics are unknown. Quarantine its spans from the ledger, route them to a shadow ledger at last-known-good rates, and page the emitter owner. Do not let the fallback branch fire — the fallback is exactly the component that turns an unknown semantic into a wrong charge. - If the provider ground-truth join is unavailable (anchor missing), the boundary degrades to "flag only": quarantine is unsafe because there is no way to reconcile the shadow ledger, and the pipeline must not silently drop billable events. The decision must be made per (emitter version, model, workload shape) tuple, not per emitter or per tenant. A single emitter can be drifted for one model and correct for another. ## Operational Effect With the invariant enforced, the 41% overcharge on `acme` would have been caught at the first distribution comparison, roughly 90 seconds into the v1.9 rollout, and the affected spans routed to a shadow ledger at v1.7 rates. The fallback-retry branch would have been suppressed for the drifted tuple, because the quarantine path bypasses the mapping entirely. The deeper effect is architectural: it forces the observability pipeline to treat **semantic-convention mappings as versioned artifacts with declared preconditions**, not as static translation tables. Each mapping entry must carry (a) the emitter versions it was calibrated against, (b) the sibling attributes it assumes are absent or present, and (c) the fallback predicates it will fire. When an emitter version outside the calibrated set appears, the mapping is *not* applied by default — it is applied only if the distribution check passes, and otherwise the spans are held. This inverts the default from "bill and hope" to "hold and verify," which is the only safe posture when the failure mode is a silent meaning shift that passes every schema validator. The cost of this posture is latency in the ledger: held spans delay attribution by one reconciliation cycle. The benefit is that the ledger's error is bounded by the reconciliation window rather than by the time to notice a 41% anomaly in a dashboard. ```python import statistics from dataclasses import dataclass from typing import Optional class SemanticDriftUnresolved(RuntimeError): """Raised when a usage-attribute distribution shift cannot be explained by a known sibling attribute and no provider ground-truth anchor exists.""" pass @dataclass class SpanUsage: emitter_version: str model: str workload_shape: str input_tokens: int cache_read_tokens: Optional[int] cache_creation_tokens: Optional[int] provider_billed_tokens: Optional[int] # ground-truth anchor, if joined def check_emitter_drift( spans: list[SpanUsage], reference_version: str, tolerance: float = 0.05, ) -> dict: """Compare an emitter's input_tokens distribution against a reference emitter for the same (model, workload_shape) tuple. Returns a verdict dict. Raises SemanticDriftUnresolved if the shift is unexplained and no anchor exists to reconcile a shadow ledger. """ if not spans: return {"verdict": "no_data"} by_tuple: dict[tuple[str, str], list[SpanUsage]] = {} for s in spans: by_tuple.setdefault((s.model, s.workload_shape), []).append(s) for (model, shape), group in by_tuple.items(): ref = [s.input_tokens for s in group if s.emitter_version == reference_version] test = [s.input_tokens for s in group if s.emitter_version != reference_version] if len(ref) < 30 or len(test) < 30: continue ref_median = statistics.median(ref) test_median = statistics.median(test) shift = (test_median - ref_median) / ref_median if ref_median else 0.0 if abs(shift) <= tolerance: continue # within noise; no action # Is the shift explained by a sibling attribute? sibling_volume = sum( (s.cache_read_tokens or 0) + (s.cache_creation_tokens or 0) for s in group if s.emitter_version != reference_version ) test_volume = sum(test) explained = test_volume > 0 and abs(sibling_volume / test_volume - abs(shift)) < 0.10 if explained: return { "verdict": "drift_explained", "model": model, "workload_shape": shape, "shift": shift, "action": "apply_variant_mapping_and_flag_emitter", } # Unexplained shift: need a ground-truth anchor to reconcile. anchored = [ s for s in group if s.emitter_version != reference_version and s.provider_billed_tokens is not None ] if not anchored: raise SemanticDriftUnresolved( f"Unexplained input_tokens shift {shift:+.1%} for " f"model={model} shape={shape} with no provider anchor; " f"quarantine spans to shadow ledger, do not bill via fallback." ) return { "verdict": "drift_unexplained_anchored", "model": model, "workload_shape": shape, "shift": shift, "action": "quarantine_and_reconcile_against_provider", } return {"verdict": "stable"} ```