# Under what conditions must an instance reconcile GenAI semantic-convention token accounting with the actual tool-call span tree before emitting a parent span **Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*` attributes) where a single logical agent invocation fans out into nested tool-call spans and the parent span reports aggregate token usage. Does not apply to flat, single-span LLM proxies that never create child tool spans, nor to runtimes that delegate all accounting to a billing backend outside the trace pipeline. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-model-call* attributes, defined on the span that represents a single inference request. An agent parent span is not a model call. It is a scheduling and orchestration span that happens to contain many model calls as children. The convention does not define an aggregate token attribute for non-model spans, and it does not define how a parent's reported usage relates to the sum of its children. This creates a silent accounting boundary: the moment an agent runtime writes `gen_ai.usage.*` onto a parent orchestration span, it is asserting a number that has no defined reconciliation rule against the child spans it wraps. The invariant that must hold is *conservation*: for any parent span, `parent.usage == Σ(descendant model-call spans' usage)` **restricted to the model calls that actually belong to that invocation**, computed at span-close time, not at emission time. The non-obvious part is that tool-call spans are not model calls, but they *contain* or *trigger* model calls, and a single tool call can retry internally, fan out to sub-agents, or be served from a cache — each of which breaks naive summation. ## What Was Observed A planner-executor agent emitted the following tree for one user turn (attributes abbreviated): ``` agent.invoke (parent) gen_ai.usage.input_tokens=4820 output_tokens=612 ├── chat (planner) gen_ai.usage.input_tokens=1900 output_tokens=310 ├── execute_tool search (no usage — tool span) │ └── chat (sub-agent) gen_ai.usage.input_tokens=1450 output_tokens=140 │ └── chat (retry #2) gen_ai.usage.input_tokens=1450 output_tokens=140 └── chat (synthesizer) gen_ai.usage.input_tokens=1620 output_tokens=205 ``` Three distinct discrepancies appeared in the same tree: 1. **Retry double-count.** The `search` sub-agent's inner chat was retried once after a malformed tool result. Both the failed attempt and the retry emitted full `gen_ai.usage.*`. The parent summed both into its 4820, inflating input tokens by 1450 that were never billed as a successful call — but *were* billed by the provider, because the failed call still consumed prompt tokens. The parent's number was "correct" against billing and "wrong" against the semantic convention's per-call intent. 2. **Cache-served child.** The synthesizer chat's prompt was 1620 tokens but 1400 were a cache hit. The provider reported `gen_ai.usage.input_tokens=1620` with a separate cache attribute the runtime ignored. Summation over children matched the parent, but neither number matched the *cost* the operator expected, because cache reads are priced differently. 3. **Orphaned child.** A fourth chat span from a speculative "lookahead" model call was started, then cancelled when the planner chose a different branch. Its span was exported with `gen_ai.usage.input_tokens=880` but its parent context had already closed, so it was attached to the *next* invocation's traceparent. The original parent's 4820 did not include it; the next turn's parent did, producing a phantom 880-token jump that reconciliation could not explain from that turn's own tree. The invariant failure is uniform across all three: the parent's aggregate was computed **incrementally as children reported**, not **at parent close from the materialized child set**, and the child set was defined by export order rather than by span-parent linkage. ## Condition of Validity The conservation invariant `parent.usage == Σ(owned model-call children)` holds only when all of the following are true at parent-close time: - **Ownership is defined by `parent_span_id`, not by trace membership or wall-clock overlap.** A child that started under this parent but was reparented (orphaned speculative call) or a child that shares the trace but has a different parent (sibling invocation) must be excluded. Trace-level summation is the wrong aggregation key. - **Retries are collapsed to a single logical model call.** The convention has no retry attribute. A runtime must either emit only the final attempt's usage and record attempt count separately, or emit every attempt but mark the parent's aggregate as "billed" rather than "semantic" and never conflate the two. Mixing them makes the parent number unverifiable against either definition. - **Cache and reasoning tokens are tracked as disjoint components, never folded into `input_tokens`/`output_tokens`.** If a provider reports cache reads, they must land in a separate attribute; folding them in makes the sum non-comparable across providers and non-reconcilable against the child spans that *do* separate them. - **Cancelled and speculative spans are excluded from the parent aggregate and marked `gen_ai.usage.*` absent or zero.** A span that represents work the agent decided not to use is not part of the invocation's semantic cost. When any of these fails, the parent's `gen_ai.usage.*` is not a semantic-convention quantity; it is an ad-hoc billing estimate wearing the convention's attribute names, and any downstream consumer (cost dashboards, budget governors, trace-based evaluation) that trusts the convention will be wrong. ## Decision Boundary The runtime must decide, per parent span, between two mutually exclusive postures: - **Semantic posture:** the parent carries *no* `gen_ai.usage.*` attributes. Aggregate usage is derivable only by summing owned children at query time. This is convention-faithful and always reconcilable, at the cost of requiring the consumer to do tree aggregation. - **Billing posture:** the parent carries `gen_ai.usage.*` but also carries an explicit `gen_ai.usage.aggregation="billed"` marker and a `gen_ai.usage.attempt_count`, and the runtime guarantees it equals the sum of all attempted calls including retries and cancelled speculative calls, with cache components broken out. The boundary is crossed the instant a runtime emits `gen_ai.usage.*` on a parent *without* declaring which posture it is in. The failure is not the number being wrong in isolation; it is the number being *unlabeled* and therefore silently reinterpreted by every consumer according to its own assumption. A budget governor that assumes semantic posture will under-count retries; a cost dashboard that assumes billing posture will over-count cache hits. Both read the same attribute. The decision must be made at span construction, before any child reports, because the posture determines whether the parent accumulates incrementally (billing) or defers to close-time tree walk (semantic). Choosing after children have reported is the root cause of the orphan and retry discrepancies above. ## Operational Effect A runtime that enforces the invariant gains a checkable property: every parent span's usage is reproducible from its own subtree by a single deterministic fold, and any drift is a detectable bug rather than a silent cost leak. The enforcement point is parent-close: the runtime must materialize the owned-child set by `parent_span_id`, fold usage with retry-collapse and cache-separation rules, and compare against any incrementally accumulated figure, raising on mismatch. This converts the three observed failures into hard errors at emission time — the retry double-count fails the fold comparison, the cache fold fails the component-disjointness check, and the orphan is rejected because its `parent_span_id` refers to a closed span with a mismatched trace context. The cost is that speculative and cancelled calls must be explicitly tombstoned rather than dropped, so the fold has a complete owned set to reason over. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent agent span's aggregate usage cannot be reconciled against its owned model-call children under the declared GenAI semantic-convention posture.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] kind: str # "agent" | "chat" | "tool" status: str # "ok" | "cancelled" | "speculative" input_tokens: int = 0 output_tokens: int = 0 cache_read_tokens: int = 0 attempt: int = 1 logical_call_id: Optional[str] = None def fold_owned_usage(parent: Span, all_spans: list[Span], posture: str) -> tuple[int, int]: if posture not in ("semantic", "billing"): raise UsageReconciliationError(f"unknown posture {posture!r} on span {parent.span_id}") owned = [s for s in all_spans if s.parent_span_id == parent.span_id and s.kind == "chat"] if posture == "semantic": # Collapse retries to the final attempt of each logical call; drop # cancelled/speculative calls entirely. by_call: dict[str, Span] = {} for s in owned: if s.status != "ok": continue key = s.logical_call_id or s.span_id prev = by_call.get(key) if prev is None or s.attempt > prev.attempt: by_call[key] = s chosen = list(by_call.values()) else: # billing: include every attempt, including cancelled speculative chosen = owned # Cache reads must never be folded into input_tokens. for s in chosen: if s.cache_read_tokens and s.cache_read_tokens > s.input_tokens: raise UsageReconciliationError( f"span {s.span_id}: cache_read_tokens {s.cache_read_tokens} " f"exceeds input_tokens {s.input_tokens}" ) return ( sum(s.input_tokens for s in chosen), sum(s.output_tokens for s in chosen), ) def close_parent(parent: Span, all_spans: list[Span], posture: str, reported_input: int, reported_output: int) -> None: expected_in, expected_out = fold_owned_usage(parent, all_spans, posture) if (reported_input, reported_output) != (expected_in, expected_out): raise UsageReconciliationError( f"parent {parent.span_id} reported " f"({reported_input},{reported_output}) but owned fold under " f"posture={posture!r} yields ({expected_in},{expected_out})" ) ```