# Which invariants prevent token-accounting span collapse when GenAI agent traces cross a sampling or batching boundary **Date of Record:** 2026 November 29 **Scope:** Applies to OpenTelemetry-instrumented LLM agents that emit `gen_ai.*` spans (chat, execute_tool, invoke_agent) through a batching or tail-sampling collector pipeline. Does not apply to synchronous, single-process exporters that flush one span per request with no intermediate processor. ## Core Distinction The failure here is not "lost traces." It is a *partial* trace: an `invoke_agent` parent span survives with its `gen_ai.usage.input_tokens` / `output_tokens` attributes intact, but its child `gen_ai.chat` and `gen_ai.execute_tool` spans are dropped by a tail sampler or evicted from a full batch queue. The parent's token attributes are *aggregate projections* computed by the agent at span-close time, not derivable from children. So the surviving trace is internally consistent-looking — it has a token count, a model name, a status — but the accounting no longer reconciles with the observable child work. Downstream cost attribution, budget enforcement, and drift detection all read the parent and silently trust a number whose provenance has been severed. The distinction that matters: standard OTel treats dropped child spans as a *sampling* concern (statistical, tolerable). GenAI token accounting treats the same drop as a *conservation* violation, because the invariant `parent.usage == Σ child.usage + overhead` is what every consumer assumes and none of the collectors enforce. ## What Was Observed A multi-step agent (planner → 3 tool calls → summarizer) ran under an OTel SDK with `BatchSpanProcessor` (queue 2048, batch 512, 5s schedule) feeding a tail-sampling collector configured to keep traces with `gen_ai.usage.total_tokens > 10000` and drop the rest of the trace's spans below a 1% probabilistic floor. Trigger condition: the planner's `invoke_agent` span closed *last* (correct parent-close ordering), carrying a self-reported `gen_ai.usage.total_tokens = 14230` aggregated across all four model invocations. Each child `gen_ai.chat` span carried its own usage (e.g. 3100, 4200, 2900, 4030). The tail sampler evaluated the *root* span, saw 14230 > 10000, and kept it. But the sampler's decision was made against a trace *already partially evicted* from the batch queue: the first two child spans had been flushed in an earlier batch and, under the 1% floor, dropped before the root arrived. The collector never saw them. Result: a 2-span trace (root + one child at 4030 tokens) whose root claims 14230. Reconciliation delta = 10200 tokens with no span to attribute them to. Three independent consumers broke differently: 1. **Cost attribution** double-counted nothing but *under-attributed* 10200 tokens to the agent, over-attributing to "unattributed" — a silent 72% error on that trace. 2. **Budget enforcement** read the parent correctly (14230) and thus did not fail — this is the dangerous case, because the number was right while the trace was wrong, masking the pipeline defect. 3. **A replay/audit job** that reconstructs usage from children computed 4030 and flagged a 3.5× discrepancy, generating a false "agent over-reported" alert. The mechanism: token usage on the agent span is a *terminal aggregate* with no referential integrity to its inputs. OTel's semantic conventions specify the attribute names (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) but do not specify that a parent's usage must equal the sum of descendants', nor do they provide a `gen_ai.usage.child_span_count` or checksum to detect severed provenance. The batch processor and tail sampler are each individually correct; their composition violates conservation because sampling is applied per-span-batch while aggregation is applied per-trace-root, and the two boundaries do not align. ## Condition of Validity The conservation invariant `parent.total_tokens = Σ(descendant.total_tokens) + parent.own_overhead` holds **only** when all of the following are true simultaneously: - Every descendant span that contributed to the parent aggregate is emitted, and emitted *before* the parent closes (so the parent can be validated against children at export). - The sampling decision is made at trace granularity and applied uniformly to all spans of the trace — i.e., no span is dropped by a *different* rule (probabilistic floor, queue eviction, per-span rate limit) than its siblings. - The batch processor's queue capacity exceeds the maximum in-flight span count of any single trace, OR the agent emits a durable per-trace manifest that survives eviction. If any one fails, the parent aggregate becomes unverifiable and any consumer treating it as ground truth is operating outside the invariant's validity domain. The common mistake is assuming the first condition (it is the *emitter's* responsibility, often satisfied) implies the second (a *collector* responsibility, routinely violated by tail sampling + batching composition). ## Decision Boundary The architectural guardrail is a **provenance seal on aggregate attributes**, enforced at span close and verified at collector ingest: - On `invoke_agent` close, the agent writes `gen_ai.usage.total_tokens` *and* a companion attribute `gen_ai.usage.descendant_span_ids` (a set of child span IDs that contributed) plus `gen_ai.usage.descendant_count`. - The collector, before accepting a root span whose descendants are not all present, either (a) rejects the trace as `incomplete_aggregate` and routes it to a dead-letter topic rather than the cost pipeline, or (b) downgrades the aggregate to `gen_ai.usage.total_tokens_partial` with an explicit `unattributed_tokens` field. - The decision boundary is: **an aggregate token count may be consumed as authoritative only if `descendant_count` observed == `descendant_count` declared.** Equality is the gate; inequality is not a warning but a hard classification into "partial trace." Do not attempt to repair by summing observed children — that under-counts and reproduces the replay job's false discrepancy. The correct action on mismatch is to *quarantine the trace from cost/budget pipelines* and emit a pipeline-health metric (`genai.trace.aggregate_unreconciled`), because the defect is in the transport, not the agent. ## Operational Effect With the seal in place, the failure mode converts from silent under-attribution to an explicit, countable `aggregate_unreconciled` rate. In the observed pipeline this rate was 4.7% of traces at the 1% floor and dropped to 0.0% once the sampler was reconfigured to sample at trace granularity with a queue sized to 2× max trace span count. The trade-off is memory: trace-granularity tail sampling buffers entire traces, so queue sizing must be driven by `max_spans_per_trace × max_concurrent_traces`, not request rate. Budget enforcement now fails *closed* (quarantined traces do not count toward spend) rather than trusting a possibly-orphaned aggregate — a deliberate choice to over-report unattributed spend rather than under-report agent spend. The invariant to carry forward: **token aggregates are projections, not facts; they are only facts when their provenance set is closed at the collector.** ```python class AggregateProvenanceError(RuntimeError): """Raised when a GenAI agent span's token aggregate has no closed descendant set.""" pass def seal_agent_span(span_attrs: dict, child_span_ids: set[str]) -> dict: """Attach a provenance seal to a closing invoke_agent span.""" declared = span_attrs.get("gen_ai.usage.descendant_span_ids", set()) if declared != child_span_ids: raise AggregateProvenanceError( f"declared descendants {declared} != observed {child_span_ids}" ) span_attrs["gen_ai.usage.descendant_count"] = len(child_span_ids) return span_attrs def admit_root_span(root: dict, observed_child_ids: set[str]) -> dict: """Collector-side gate: only admit aggregate as authoritative if sealed set is closed.""" declared = root.get("gen_ai.usage.descendant_span_ids", set()) if declared != observed_child_ids: root["gen_ai.usage.classification"] = "partial_trace" root["gen_ai.usage.unattributed_tokens"] = root.get("gen_ai.usage.total_tokens", 0) # quarantine from cost/budget pipelines; do not raise here, classify instead return root root["gen_ai.usage.classification"] = "authoritative" return root def enforce_conservation(root: dict, child_usage: list[int]) -> None: """Hard check used by audit/replay; raises on unreconciled aggregate.""" if root.get("gen_ai.usage.classification") != "authoritative": raise AggregateProvenanceError( f"cannot reconcile non-authoritative aggregate: " f"{root.get('gen_ai.usage.unattributed_tokens')} unattributed tokens" ) total = root.get("gen_ai.usage.total_tokens", 0) if sum(child_usage) > total: raise AggregateProvenanceError( f"child usage {sum(child_usage)} exceeds parent aggregate {total}" ) ```