# When must an instance refuse to emit a GenAI agent span because the token-count attribute and the child tool-call spans disagree at export time **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) that emits a parent agent span alongside child tool-call spans and per-call token accounting. Does not apply to single-shot LLM calls with no tool orchestration or to runtimes that export token counts only as unstructured logs. ## Core Distinction The GenAI semantic conventions treat token accounting as *span-local attributes*: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are declared on the span that represents the model invocation. When an agent orchestrates N model invocations and M tool calls, the natural instrumentation emits one parent `invoke_agent` span and N+M children. The convention does **not** mandate that the parent's aggregate token attributes equal the sum of its children's token attributes — and this is precisely where a silent invariant break occurs. The distinction that matters operationally: a *token-accounting mismatch* is not a telemetry bug to be smoothed over at the collector. It is a signal that the agent's own internal accounting diverged from what the model provider actually billed — usually because a retry, a streaming truncation, or a context-compaction step consumed tokens that no child span recorded. An instance that reconciles the mismatch by rewriting the parent attribute (or by dropping the offending child) destroys the only forensic evidence that a retry loop or a compaction event occurred. The invariant is therefore: **the parent span's token attributes must be treated as a lower bound, and any export where the child sum exceeds the parent value must be flagged, not normalized.** ## What Was Observed A multi-step research agent was instrumented with a parent `invoke_agent` span carrying `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` set from the orchestrator's own running counter. Each of its 7 model invocations emitted a child `chat` span with provider-reported usage; each of its 4 tool calls emitted a `execute_tool` child with no token attributes (correct per convention). During a run that hit a provider 429 on step 4, the orchestrator's retry logic re-issued the request with the same message history but a *fresh* streaming connection. The retry consumed 1,180 input tokens and 340 output tokens before succeeding. The orchestrator's running counter — incremented only on the success path — never saw those tokens. The parent span reported 14,220 input tokens. The sum of the 7 child `chat` spans reported 15,400 input tokens: a 1,180-token gap exactly equal to the failed retry. The exporter, configured with a common "reconcile parent from children" processor, overwrote the parent attribute to 15,400 and emitted a clean trace. The retry event — the only evidence that the provider had throttled the agent mid-run, forcing a full re-prefill of 1,180 tokens — was erased. Downstream cost attribution undercounted the run by 8.3%, and a subsequent capacity-planning query concluded the agent's p99 input-token footprint was stable when it was in fact retry-sensitive. A second, subtler case: a context-compaction step fired at 92% window utilization, summarizing 40K tokens of history into 6K. The compaction call itself was a model invocation but was instrumented as an *internal* function, not a child span. The parent reported the post-compaction 6K as its input figure; the child sum reflected the pre-compaction invocations. Here the parent *under*-reported by design, and the mismatch was structural, not anomalous. ## Condition of Validity The invariant "parent token attributes are a lower bound, mismatch is a signal" holds only under these conditions: 1. **Child spans carry provider-reported usage, not orchestrator estimates.** If children are instrumented with the same running counter as the parent, the two are not independent measurements and the comparison is vacuous. The check requires at least one independent source. 2. **Every model invocation that consumes billable tokens emits a child span, including retries and compaction calls.** This is the hard requirement. An agent that instruments only the "logical" model call — folding retries into the parent — cannot satisfy the invariant and must instead emit an explicit `gen_ai.retry` event or a `retry_count` attribute so the gap is attributable. 3. **The comparison is done at span close, before any collector-side mutation.** Reconciliation processors must run *after* the mismatch has been recorded as an attribute or event, never instead of it. 4. **Token counts are compared in the same unit and tokenizer.** Cross-provider or cross-tokenizer aggregation invalidates the equality check; the invariant is per-provider, per-model. When condition 2 cannot be met (e.g., the provider SDK hides retries below the instrumentation layer), the correct posture is to *stop asserting* the parent aggregate is complete and instead mark the span `gen_ai.usage.partial=true`. ## Decision Boundary The boundary is the sign and magnitude of `child_sum − parent_value` at span close: - **`child_sum == parent_value`** (within tokenizer noise, typically 0): emit normally, no flag. - **`child_sum > parent_value`**: an unrecorded consumption event occurred — retry, shadow call, or double-instrumented child. Do **not** overwrite the parent. Emit the parent with its original value plus an event `gen_ai.accounting.mismatch` carrying `delta_tokens` and the child span IDs. This is a *recoverable* anomaly; the trace remains valid and the gap is attributable. - **`parent_value > child_sum` by more than a compaction threshold**: a structural under-report, typically context compaction or a provider that reports usage only on the final stream chunk. Mark `gen_ai.usage.partial=true`; do not attempt to backfill. - **`child_sum` exceeds parent by more than 2× the parent value**: instrumentation defect (likely child spans emitted twice under at-least-once export). Refuse to emit the parent; raise to the agent's error channel rather than exporting a trace that will poison cost dashboards. The decisive rule: **an instance must refuse to emit a reconciled parent span when reconciliation would erase a positive child-sum excess.** The trace is more valuable with a recorded gap than with a clean lie. ## Operational Effect Agents that adopt the lower-bound posture gain three operational properties. First, retry storms become visible in trace data as repeated `accounting.mismatch` events with `delta_tokens` clustered at the retry payload size — a directly actionable signal for provider throttling. Second, cost attribution stops silently absorbing unrecorded consumption; the 8.3% undercount in the observed case would have surfaced as a flagged delta rather than vanishing. Third, compaction events become distinguishable from anomalies: under-reports flagged `partial=true` are expected, over-reports are not. The cost is that downstream consumers must tolerate `partial=true` spans and mismatch events — dashboards that assume `sum(children) == parent` will need to branch. The alternative, reconciliation-by-overwrite, produces traces that are internally consistent and externally wrong, which is the worse failure for any agent whose cost and latency behavior is the thing being measured. ```python from dataclasses import dataclass class TokenAccountingMismatchError(RuntimeError): """Raised when a parent agent span's token attributes cannot be safely reconciled with the sum of its child span usage without erasing evidence of unrecorded consumption (retries, shadow calls, compaction).""" @dataclass class SpanUsage: span_id: str input_tokens: int output_tokens: int is_child: bool def reconcile_agent_span( parent: SpanUsage, children: list[SpanUsage], compaction_threshold_tokens: int = 4000, double_emit_factor: float = 2.0, ) -> dict: """Decide whether a parent agent span may be exported as-is, flagged, or refused. Returns a dict describing the export decision. Raises TokenAccountingMismatchError when the mismatch indicates a defect that must not be exported as a clean trace. """ if not children: # No independent measurement: the invariant is undefined, export as partial. return {"action": "export_partial", "reason": "no_child_usage", "delta": None} child_in = sum(c.input_tokens for c in children) child_out = sum(c.output_tokens for c in children) delta_in = child_in - parent.input_tokens delta_out = child_out - parent.output_tokens # Instrumentation defect: children likely emitted twice under at-least-once export. if child_in > parent.input_tokens * double_emit_factor and parent.input_tokens > 0: raise TokenAccountingMismatchError( f"parent span {parent.span_id} reports {parent.input_tokens} input tokens " f"but children sum to {child_in} ({child_in / parent.input_tokens:.1f}x). " f"Likely duplicate child emission; refusing to export a poisoned trace." ) if delta_in > 0 or delta_out > 0: # Unrecorded consumption: retry, shadow call, or missed child. Preserve the gap. return { "action": "export_with_mismatch_event", "event": "gen_ai.accounting.mismatch", "delta_input": delta_in, "delta_output": delta_out, "child_span_ids": [c.span_id for c in children], } if -delta_in > compaction_threshold_tokens: # Structural under-report, typically context compaction or final-chunk-only usage. return { "action": "export_partial", "reason": "compaction_or_streaming_underreport", "delta_input": delta_in, } return {"action": "export_clean", "delta_input": delta_in, "delta_output": delta_out} ```