# How should an instance reconcile OpenTelemetry GenAI span attributes when a parent agent span closes before its delegated tool-call spans emit token usage **Date of Record:** 2026 December 3 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the `gen_ai.*` semantic conventions where a parent `invoke_agent` span is finalized (exported) before child `execute_tool` / `chat` spans report `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. Does not apply to runtimes that buffer the whole trace tree in a single batch exporter or that never aggregate usage at the parent level. ## Core Distinction There are two incompatible notions of "when a span's usage is known." The OpenTelemetry data model says a span's attributes are immutable once `End()` is called; the exporter forwards whatever was set at that instant. The GenAI semantic conventions, however, describe token accounting as an aggregate property of the agent invocation — `gen_ai.usage.*` on the parent is expected to reflect the sum of child model calls. These two facts collide when the parent agent span ends before the delegated tool-call and nested model spans have finished streaming their usage. The failure is not "missing telemetry." It is a *silent under-count*: the parent span exports with `gen_ai.usage.input_tokens` equal to only the tokens consumed before the first delegation, and the child spans — which do carry correct usage — are exported later as siblings-in-time but children-in-trace, with no mechanism to retroactively patch the parent. Downstream cost attribution, budget enforcement, and loop-detection heuristics that read the parent span see a number that is structurally too low and cannot be distinguished from a genuinely cheap invocation. ## What Was Observed A supervisor agent handling a research task emitted the following span sequence (timestamps in ms, single trace): - `t=0`: `invoke_agent` (parent) starts, `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name=supervisor`. - `t=0..180`: first model call completes, sets `gen_ai.usage.input_tokens=2100`, `output_tokens=180` on the parent via a shared attribute map. - `t=180`: parent delegates; runtime calls `parent.end()` to "release the span early" so the exporter queue drains, then spawns three `execute_tool` children and one nested `chat` span. - `t=180..4200`: children run. The nested `chat` span records `gen_ai.usage.input_tokens=9400`, `output_tokens=1100`. Tool spans record `gen_ai.tool.name` and durations. - `t=4200`: children end and export. The parent span exported at `t=180` with `input_tokens=2100`. The trace, when reconstructed, shows a parent whose usage is ~18% of the true model consumption (2100 of 11500 input tokens). The children's usage is present and correct, but the aggregation contract — "parent usage = sum of descendant model calls" — is violated. A cost dashboard summing parent spans under-bills by 82% on this trace. A budget guardrail keyed on the parent span never trips. A second, subtler observation: because `parent.end()` preceded child creation, the children were still correctly parented by trace/span ID (the runtime captured the parent `SpanContext` before ending), so the trace tree looked structurally valid. The corruption is purely in the attribute values, which is why it passed schema validation and trace-lint checks that only verify parent-child linkage. ## Condition of Validity The invariant that is being violated can be stated precisely: > For any `invoke_agent` span P, at the moment P is exported, `P.gen_ai.usage.input_tokens` must equal the sum of `gen_ai.usage.input_tokens` over all descendant `chat` spans plus P's own pre-delegation model calls, or the field must be absent and marked as deferred. This invariant only holds if the runtime either (a) keeps P open until all descendants end, or (b) treats parent usage as a *derived, post-hoc* quantity computed by a collector/processor rather than set inline. Runtimes that set usage inline on the parent and end it early cannot satisfy the invariant for any trace with post-delegation model calls. The failure is therefore deterministic given early parent termination and non-empty delegation — it is not a race, not a sampling artifact, and not dependent on exporter backpressure. It reproduces on every delegated trace. ## Decision Boundary The architect must choose one of three reconciliation strategies, and the choice is forced by whether the runtime can hold the parent span open: 1. **Hold-open (default-correct):** Parent `end()` is deferred until a reference-counted set of child spans completes. Requires the runtime to track outstanding children per parent. Cost: parent span stays in memory for the full delegation latency; a hung child leaks the parent. Bound with a max-hold timeout that, on expiry, ends the parent with usage marked incomplete. 2. **Deferred aggregation (collector-side):** Parent exports with usage omitted and an attribute `gen_ai.usage.aggregation=pending`; a collector processor sums descendant `chat` usage and emits a corrected span or metric. Requires the collector to see the full trace before the aggregation window closes — breaks under tail-based sampling drops or split-trace export. 3. **Explicit incompleteness (honest):** Parent exports with whatever usage it has plus `gen_ai.usage.incomplete=true`. Downstream consumers must treat the value as a lower bound. This is the only safe option when neither (1) nor (2) is available, and it converts a silent under-count into a detectable one. The boundary condition is: if any descendant `chat` span can end after the parent, option (1) is mandatory unless option (2)'s collector guarantee is verifiable. Option (3) is a fallback, never a fix. ## Operational Effect The immediate operational effect of getting this wrong is misattribution that compounds: budget alarms calibrated on parent-span usage never fire, so an agent loop that re-delegates hundreds of times appears cheap at the parent level while burning tokens in children that no guardrail reads. Loop-detection heuristics that watch parent `output_tokens` growth to spot runaway reasoning see a flat line because the growth is in descendants. Cost dashboards that group by `gen_ai.agent.name` on the parent span systematically under-report exactly the agents that delegate most — the expensive ones. The secondary effect is diagnostic confusion during incident review: the trace "looks fine," the child spans have correct numbers, and the discrepancy only surfaces when someone manually sums descendants and compares to the parent. Teams then add a post-hoc summation job, which duplicates the collector-side aggregation they should have adopted, and the two disagree whenever sampling drops a child. The guardrail is a runtime assertion at parent `end()`: if the parent has outstanding child spans that are `chat` operations, either block the end (hold-open) or set `gen_ai.usage.incomplete=true` and emit a counter metric `genai.span.usage_incomplete_total`. That counter is the early-warning signal; a nonzero rate means the runtime is exporting under-counted parent usage. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent agent span would export with usage that cannot equal the sum of its descendant model calls.""" @dataclass class SpanUsage: input_tokens: int = 0 output_tokens: int = 0 incomplete: bool = False @dataclass class AgentSpan: name: str usage: SpanUsage = field(default_factory=SpanUsage) outstanding_chat_children: int = 0 ended: bool = False def end_agent_span(span: AgentSpan, strategy: str = "hold_open") -> SpanUsage: """Finalize an invoke_agent span under one of the reconciliation strategies. strategy: - "hold_open": refuse to end while chat children are outstanding. - "honest": end now but mark usage incomplete. """ if span.ended: raise UsageReconciliationError(f"span {span.name!r} already ended") if span.outstanding_chat_children > 0: if strategy == "hold_open": # Do not end; caller must wait or hit a max-hold timeout. raise UsageReconciliationError( f"span {span.name!r} has {span.outstanding_chat_children} " "outstanding chat children; parent usage cannot equal " "descendant sum if ended now" ) elif strategy == "honest": span.usage.incomplete = True # emit counter: genai.span.usage_incomplete_total += 1 else: raise UsageReconciliationError(f"unknown strategy {strategy!r}") span.ended = True return span.usage def on_chat_child_end(parent: AgentSpan, child: SpanUsage) -> None: """Called when a descendant chat span reports usage. Must run before parent end() for hold_open to be satisfiable.""" if parent.ended: raise UsageReconciliationError( f"chat child ended after parent {parent.name!r} exported; " "parent usage is structurally under-counted" ) parent.usage.input_tokens += child.input_tokens parent.usage.output_tokens += child.output_tokens parent.outstanding_chat_children -= 1 ```