# Which invariants prevent GenAI semantic-convention span attributes from silently mis-accounting tokens and cost across agent tool-call boundaries **Date of Record:** 2026 November 23 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) and propagate token/usage accounting across nested tool-call and sub-agent spans. Does not cover provider-side billing reconciliation, non-OTel tracing backends, or transport-level retry semantics. ## Core Distinction The GenAI semantic conventions treat *usage* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.usage.total_tokens`) as a property of a single inference operation, and *cost* as a derived, out-of-band quantity. They do **not** define an aggregation contract across a span tree. This is the fault line: an agent that performs N tool calls inside a single operator turn will, if it naively sums leaf-span usage, either double-count the parent inference's own tokens or drop the tokens consumed by intermediate reasoning steps whose spans were sampled, retried, or re-emitted after a mid-turn model switch. The non-obvious boundary is this: **usage attributes are additive per inference op, but the parent agent span is not an inference op** — it is an orchestration span. Summing `gen_ai.usage.total_tokens` over *all* descendant spans that carry the attribute produces a total that is only correct when every inference op is represented exactly once and no orchestration span carries a usage value copied up from a child. In practice one of those two conditions fails on nearly every non-trivial agent. ## What Was Observed A research agent with a planner/executor split emitted spans as follows. The planner span (`gen_ai.operation.name=chat`, `gen_ai.system=openai`) carried `usage.total_tokens=1840`. The executor performed three tool calls, each wrapped in a `gen_ai.operation.name=execute_tool` span with no usage attributes (correct — tools don't consume model tokens). Between tool calls the executor re-invoked the model twice, emitting two more `chat` spans with `usage.total_tokens=610` and `usage.total_tokens=430`. The orchestrating agent span, emitted by the framework's auto-instrumentation, copied the *last* child's usage upward as `usage.total_tokens=430` — a convenience the instrumentation author added so dashboards "had something to show." The downstream cost pipeline summed `usage.total_tokens` across every span carrying the attribute. Result: 1840 + 610 + 430 + 430 = 3310, against a true 2880. The 430 overcount was the orchestrator's copied-up value. Worse, in a second trace the executor's first `chat` span was dropped by a tail-sampling policy (the trace was slow but not erroring), so the sum was 1840 + 430 + 430 = 2700 — an *undercount* of 610. The same pipeline produced both a +15% and a −21% error on structurally identical workloads, and neither error surfaced as an anomaly because the per-span values were individually plausible. The trigger condition is precise: **a span tree where (a) at least one orchestration span carries a `gen_ai.usage.*` attribute inherited from a descendant, and (b) at least one inference span is absent from the exported set (sampling, span-limit truncation, or a retry that reused the span ID and overwrote attributes).** Either alone is tolerable; together they make the aggregate unrepairable from the exported data. ## Condition of Validity The additive-sum invariant holds only under the conjunction: 1. **Uniqueness:** every `gen_ai.operation.name=chat` (or `embeddings`, `text_completion`) inference op is represented by exactly one exported span, keyed by a stable `gen_ai.response.id` where the provider supplies one. 2. **Non-propagation:** spans whose `gen_ai.operation.name` is `invoke_agent`, `create_agent`, or `execute_tool` MUST NOT carry `gen_ai.usage.*`. Usage belongs to the inference op, not the orchestration node. 3. **Completeness under sampling:** if the exporter samples, it must sample at the *trace* root, not per-span, or the aggregator must be given the sampling decision per span so it can reweight. 4. **Retry identity:** a retried inference op either reuses the same span with an incremented `gen_ai.request.retry_count` (and the aggregator takes the final usage, not the sum), or emits a new span with a distinct `gen_ai.response.id`. Mixing the two conventions across SDK versions produces silent double-counts. When any of these is violated, the summed total is not merely noisy — it is biased in a direction determined by which invariant broke, and the bias is stable across runs, so it evades anomaly detection. ## Decision Boundary The operational decision is where to enforce the invariant. Three viable placements: - **Emit-time enforcement (preferred):** the instrumentation layer rejects `gen_ai.usage.*` on non-inference spans. This is a hard guardrail and eliminates the copied-up overcount class entirely. It does not address sampling loss. - **Aggregation-time enforcement:** the cost pipeline walks the span tree, selects only `chat`/`embeddings` spans, deduplicates by `gen_ai.response.id`, and refuses to emit a total when the trace's span count is below the exporter's declared sampling threshold. This handles sampling loss but requires the pipeline to know the sampling policy — a coupling that breaks when the policy changes without a pipeline deploy. - **Hybrid (recommended):** emit-time rejection of usage on orchestration spans, plus aggregation-time dedup by response ID, plus a `gen_ai.usage.total_tokens` *reconciliation* check: if a parent agent span declares its own `usage.total_tokens` (some frameworks do), the aggregator must treat it as a *claim* to be verified against the sum of its `chat` descendants, and flag a mismatch rather than trusting either value. The boundary condition that forces the hybrid: neither placement alone is sufficient, because emit-time cannot see sampling loss and aggregation-time cannot see the copied-up value without knowing the instrumentation's intent. The reconciliation check is the only place both failure modes are simultaneously visible, because it compares the claim to the evidence within the same exported trace. ## Operational Effect With the invariant enforced, the observable failure changes character. Instead of a silently biased total, you get a *reconciliation exception* at the aggregation boundary — a span that claims a total its children cannot support, or a trace whose inference-span count is inconsistent with its declared sampling decision. This converts a cost-accounting error that surfaces weeks later as a finance discrepancy into an alert that fires on the trace that caused it, with the offending span ID attached. The cost of the guardrail is that some legitimate traces (those where an inference span was genuinely dropped by tail sampling) now raise instead of silently undercounting; the aggregator must therefore carry a sampling-aware fallback that reweights rather than aborts, and the exception is reserved for the case where the reweighted total still disagrees with the parent claim beyond a tolerance. The residual risk after enforcement is the retry-identity ambiguity: an SDK that reuses a span ID across retries and overwrites `usage.*` on each attempt will pass the reconciliation check (one span, one usage value) while undercounting the retried attempts' tokens. This is not detectable from the span tree alone and requires the provider's `gen_ai.response.id` to change per attempt, which is the invariant to negotiate with the SDK vendor before trusting any cost figure. ```python class UsageAccountingInvariantError(RuntimeError): """Raised when a GenAI span tree violates the additive-usage contract.""" pass INFERENCE_OPS = frozenset({"chat", "text_completion", "embeddings"}) ORCHESTRATION_OPS = frozenset({"invoke_agent", "create_agent", "execute_tool"}) def reconcile_usage(span_tree: list[dict], sampling_rate: float = 1.0) -> int: """Return the deduplicated token total for a trace, or raise. Enforces: usage only on inference ops, dedup by response id, and parent claims must match the sum of their inference descendants. """ if not 0.0 < sampling_rate <= 1.0: raise UsageAccountingInvariantError(f"invalid sampling_rate {sampling_rate}") seen_response_ids: set[str] = set() total = 0 claims: list[tuple[str, int]] = [] for span in span_tree: op = span.get("gen_ai.operation.name") usage = span.get("gen_ai.usage.total_tokens") if op in ORCHESTRATION_OPS and usage is not None: raise UsageAccountingInvariantError( f"orchestration span {span.get('span_id')} carries usage={usage}; " "usage must not propagate to non-inference spans" ) if op in INFERENCE_OPS and usage is not None: rid = span.get("gen_ai.response.id") if rid is None: raise UsageAccountingInvariantError( f"inference span {span.get('span_id')} missing gen_ai.response.id; " "cannot deduplicate retried attempts" ) if rid in seen_response_ids: continue seen_response_ids.add(rid) total += usage if op in ORCHESTRATION_OPS and span.get("usage_claim") is not None: claims.append((span.get("span_id"), span["usage_claim"])) if sampling_rate < 1.0: total = int(round(total / sampling_rate)) for span_id, claim in claims: if abs(claim - total) > max(1, int(0.02 * total)): raise UsageAccountingInvariantError( f"parent span {span_id} claims {claim} tokens but inference " f"descendants reconcile to {total} (sampling_rate={sampling_rate})" ) return total ```