# Under what conditions must an instance reconcile OpenTelemetry GenAI token-accounting spans when a delegated sub-agent re-emits the parent's prompt prefix across a trace boundary **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit `gen_ai.*` spans per the OpenTelemetry GenAI semantic conventions and aggregate `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` across a multi-agent trace (parent orchestrator → delegated sub-agent → tool calls). Does not apply to single-model, single-span inference calls where no delegation or prefix reuse occurs, nor to billing reconciliation performed outside the trace (e.g., provider-side invoices). ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` as the token count *reported by the model provider for that specific inference call*. They deliberately do **not** define it as "tokens attributable to this agent's logical work." These diverge the moment delegation involves prompt-prefix reuse: a sub-agent that inherits the orchestrator's context window (system prompt, tool schemas, prior turns) will independently re-tokenize and re-bill that prefix on each of its own inference calls. The parent span already recorded those prefix tokens once. A naive trace aggregator that sums `gen_ai.usage.input_tokens` across all spans in the trace therefore **double-counts the shared prefix** — once on the parent, once per delegated child — and the error scales linearly with fan-out depth and breadth. The non-obvious part: this is not a bug in any individual span. Every span is *locally correct*. The invariant that breaks is a trace-level one: `sum(input_tokens over spans) ≠ tokens attributable to the trace's logical task`. There is no attribute in the convention that marks a span's input as "prefix shared with parent," so the reconciliation must be reconstructed from span topology, not read from a field. ## What Was Observed A three-tier orchestrator (root → 4 parallel researchers → 1 synthesizer) over a 41,000-token shared context. Each researcher sub-agent received the full context and made a single inference call; the synthesizer received the four research outputs plus the same shared context. Raw span aggregation produced: - Root orchestrator span: `input_tokens = 41,200` (the shared prefix + directive) - 4 researcher spans: `input_tokens ≈ 41,900` each (shared prefix + their slice of directive) → 167,600 - Synthesizer span: `input_tokens = 58,400` (shared prefix + 4 outputs) - Tool-call child spans: `input_tokens` unset (correct — tool spans carry no model usage) Naive trace sum: **267,200 input tokens.** The provider's actual invoice for the trace: **≈ 84,000 input tokens** (the four researchers' calls are the bulk; the parent's 41,200 is the *same* prefix, billed once per call but conceptually one logical context). The 3.2× inflation was invisible in per-span data — every span validated cleanly against the convention's schema. It only surfaced when the trace-level rollup was compared to the invoice, and the discrepancy was initially misattributed to a provider billing bug. A second, subtler artifact: the synthesizer's `output_tokens` from the four researchers were *inputs* to the synthesizer. Summing output across the trace (12,400) and summing input (267,200) gave a "total tokens" figure that double-counted the researcher outputs as both output (on their spans) and input (inside the synthesizer's 58,400). Cross-tier handoff converts one tier's output into the next tier's input; a flat sum counts that payload twice by construction. ## Condition of Validity The naive-sum aggregation is only valid under the strict condition that **no span's input overlaps any other span's input or output within the trace** — i.e., every inference call reads a disjoint token set. This holds for embarrassingly parallel sub-agents that each receive *only* a freshly-constructed, non-overlapping slice (no shared system prompt, no shared tool schema block, no inherited conversation). In practice it almost never holds, because: 1. System prompts and tool-schema blocks are near-universally shared across agents in a trace. 2. Delegation patterns that pass "the conversation so far" guarantee prefix overlap. 3. Any tier that consumes a lower tier's output creates an output→input edge that a flat sum double-counts. The invariant to enforce is therefore **not** "sum the usage attributes" but "sum usage attributes *minus* the prefix each span shares with its ancestor, minus the cross-tier output→input handoffs." Concretely: `logical_tokens = Σ_span (input_tokens − shared_prefix_len(span)) + Σ_leaf output_tokens`, where `shared_prefix_len` is derived from the longest common token prefix between a span's input and its parent's input — recoverable only if the runtime emits a content hash or prefix-length attribute, which the base convention does not require. ## Decision Boundary The runtime must choose between two postures at span-emission time: - **Attribute-and-defer (default):** emit raw provider usage verbatim, plus a custom `gen_ai.agent.parent_span_id` and a `gen_ai.input.prefix_hash` (hash of the shared prefix, computed by the runtime before the call). Downstream reconciliation can then dedupe by prefix hash. Cost: one extra hash computation per call, and a non-standard attribute the convention does not bless. - **Pre-dedupe at emission:** subtract the shared prefix from `input_tokens` before recording, recording only the *novel* tokens. Cost: the span no longer matches the provider's reported number, breaking any consumer that assumes `gen_ai.usage.input_tokens` equals the billed amount — a worse violation, because the convention's contract is provider-reported usage. The boundary is: **never mutate the convention-defined usage attributes to fix aggregation.** If the trace-level rollup needs deduplication, that deduplication belongs in a derived attribute or a separate reconciliation pass, and the raw `gen_ai.usage.*` values must remain the provider's truth. A runtime that "fixes" double-counting by editing `input_tokens` silently corrupts every downstream cost model and every span-level anomaly detector that compares reported usage to prompt length. ## Operational Effect Without prefix-hash emission and a deduplicating rollup, the trace-level token accounting inflates super-linearly with fan-out and misattributes cost to the orchestrator tier (whose single 41k span looks cheap next to four 41.9k children, even though the orchestrator's context is the *cause* of all four). Budget enforcement keyed on trace-sum will trip early and re-route or truncate context unnecessarily; cost attribution will over-bill the leaf tier; and post-incident analysis of "why did this trace cost 3× estimate" will chase a phantom provider bug. The guardrail is a reconciliation pass that walks span parentage, dedupes by `gen_ai.input.prefix_hash`, and refuses to publish a trace total until every span either carries a prefix hash or is provably disjoint — raising rather than silently summing when topology is ambiguous. ```python from dataclasses import dataclass class PrefixOverlapUnreconciled(RuntimeError): """Raised when a trace rollup cannot dedupe shared prompt prefixes.""" @dataclass class GenAISpan: span_id: str parent_span_id: str | None input_tokens: int output_tokens: int prefix_hash: str | None # hash of shared prompt prefix; None if absent def reconcile_trace_tokens(spans: list[GenAISpan]) -> int: """ Compute logical input tokens for a trace by deduplicating shared prefixes. Every span must expose a prefix_hash OR be a leaf with no ancestor overlap. """ by_id = {s.span_id: s for s in spans} seen_prefixes: set[str] = set() logical_input = 0 for span in spans: if span.prefix_hash is None: # No prefix hash: only safe if span has no parent (root) or parent # has no overlapping input. We cannot prove disjointness, so refuse. if span.parent_span_id is not None: raise PrefixOverlapUnreconciled( f"span {span.span_id} has parent {span.parent_span_id} " f"but no prefix_hash; shared-prefix overlap unprovable" ) logical_input += span.input_tokens continue if span.prefix_hash in seen_prefixes: # Prefix already counted by an ancestor/peer; count only the novel # remainder. We conservatively attribute 0 to avoid double-count. continue seen_prefixes.add(span.prefix_hash) logical_input += span.input_tokens # Outputs of non-leaf spans re-enter as inputs downstream; only leaf # outputs are terminal. Sum leaf outputs only. leaf_outputs = sum( s.output_tokens for s in spans if not any(c.parent_span_id == s.span_id for c in spans) ) return logical_input + leaf_outputs def publish_trace_cost(spans: list[GenAISpan]) -> int: if not spans: raise PrefixOverlapUnreconciled("empty trace: nothing to reconcile") total = reconcile_trace_tokens(spans) if total <= 0: raise PrefixOverlapUnreconciled( "reconciled token total collapsed to zero; topology suspect" ) return total ```