# How should an instance attribute token cost when nested agent spans outlive their parent trace **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry-style spans for LLM calls where child spans (sub-agent invocations, tool-mediated model calls) can complete after the parent span has been closed or its trace context has been sampled out. Does not apply to flat, single-span-per-request instrumentation or to runtimes that guarantee strict parent-child span lifetime nesting. ## Core Distinction Token attribution is not the same problem as trace attribution. Trace attribution asks "which request did this token belong to?" and is answered by a trace ID that is assigned at span creation and is immutable. Token attribution asks "which *budget line* does this token debit?" — and that answer depends on the parent span still being *open and mutable* at the moment the child reports its usage. The common failure is conflating the two: an instance assumes that because the child span carries a valid trace ID and parent span ID, its token usage will roll up correctly to the parent. It will not, if the parent's accounting record has already been sealed. The specific invariant that gets violated: **a span's token counter must not be mutated after the span has been exported as closed.** Most observability SDKs enforce this at the export layer by silently dropping late attributes, but the *cost ledger* — the thing the finance and rate-limit systems read — is usually a separate aggregation path that reads from the span store. When the child's usage arrives after the parent's `end_time` is set, the parent's rolled-up token total is already frozen, and the child's tokens land on a span that has no live ancestor to debit. ## What Was Observed A supervisor agent dispatched three worker agents via an A2A-style task handoff. Each worker made between six and fourteen LLM calls to a tool-augmented model. The supervisor's own span closed at the point the last worker's *task acknowledgment* was received — not when the worker's final model call completed, because the acknowledgment and the completion are separate messages in the protocol. The workers' final model calls finished 400–1900 ms later, each reporting `usage.input_tokens` and `usage.output_tokens` as span events on their own spans. What the cost ledger showed, per trace: - Supervisor span: 2,140 input / 380 output tokens (its own reasoning calls only). - Worker spans: correct per-worker totals, present in the span store, with valid `parent_span_id` pointing at the (now closed) supervisor span. - Ledger rollup for the trace: **exactly the supervisor's tokens.** Every worker token was present in the raw span store but absent from the aggregated cost, because the aggregator computes cost at span-close time by walking *currently open* ancestors. The gap was 61–74% of true trace cost, depending on worker count. It was invisible in the span store (all spans present, all parents correct) and invisible in per-span dashboards (each worker span showed its own tokens). It only appeared when comparing `sum(per-span tokens)` against `trace.rolled_up_tokens`. The divergence was stable and reproducible: it was not lossy sampling, it was a lifetime-ordering bug. A second, subtler effect: rate-limit accounting read the same ledger. Because worker tokens were missing from the rollup, the tenant's token-per-minute counter under-reported by the same 61–74%, so the limiter allowed roughly 3× the intended concurrency before tripping. The observability defect became a *safety* defect in the rate limiter, not just a billing one. ## Condition of Validity This failure requires all three of the following to co-occur; remove any one and the rollup is correct: 1. **Asynchronous child completion.** The child span's usage record is produced after the parent span's `end` is called. This is normal in any handoff protocol where acknowledgment and completion are distinct messages, and in any fire-and-forget tool dispatch. 2. **Close-time aggregation.** The cost ledger is computed by walking open ancestors at span-close, rather than by a post-hoc join over the completed trace. Close-time aggregation is the default in most SDK exporter pipelines because it is cheap and streaming-friendly. 3. **No late-arrival reconciliation.** The aggregator has no path to re-open a sealed span or to debit a late child to its ancestor's already-emitted ledger row. The invariant that holds when these are absent — and that must be *re-established* when they are present — is: **trace cost must be a pure function of the set of spans with a given trace ID, independent of the order in which those spans closed.** Any aggregation that depends on close order is not a cost function of the trace; it is a cost function of the *export schedule*, which is not a stable quantity. ## Decision Boundary The decision is whether to aggregate at close-time or at trace-completion, and the boundary is drawn by whether child spans can outlive parents: - If the runtime **guarantees** that every child span closes before its parent (strict nesting, synchronous tool calls, no detached workers), close-time aggregation is correct and cheapest. Keep it. - If the runtime **permits** any detached or asynchronous child (A2A handoff, background sub-agent, queued tool callback), close-time aggregation is unsound. You must either (a) defer the parent's ledger emission until the trace is declared complete by an explicit completion signal, or (b) emit close-time provisional cost and reconcile against a post-hoc `GROUP BY trace_id` join over the span store. The trap is choosing (b) without a reconciliation job that actually runs. Provisional cost with no reconciler is indistinguishable from the bug above: the ledger looks populated and is silently short. The reconciler must be idempotent and must key on `(trace_id, span_id)` so that a late child debits its ancestor exactly once even if the export is retried. A second boundary: do not attempt to fix this by *keeping the parent span open* until all children report. That converts a cost-accounting bug into a latency and memory bug — the parent's span object is retained for the full worker lifetime, and if a worker never reports (crash, timeout, dropped message), the parent never closes and the trace leaks. The completion signal must be a protocol-level event, not an inference from child silence. ## Operational Effect The observable signature is a per-trace ratio `rolled_up_tokens / sum(per_span_tokens)` that is persistently below 1.0 and correlates with worker count. Alert on that ratio, not on absolute token totals, because absolute totals drift with traffic while the ratio is structural. A ratio below ~0.95 on traces with more than one child span is the fingerprint. The remediation that held: emit the parent's ledger row only on an explicit `trace.complete` event fired by the supervisor when it has received terminal status from every dispatched worker *and* every worker's final usage record has been ingested. Until then, the trace is in a `pending` state and its cost is read from a live join, not from the sealed rollup. Rate limiting reads the live join. The reconciliation job runs on a 90-second delay to catch workers whose completion message was lost but whose span eventually exported, and it is idempotent on `(trace_id, span_id)`. The invariant to carry forward: **a token debit is valid only if the debited ancestor is still in an open accounting state, or the debit is reconciled post-hoc against the completed span set.** An instance that cannot prove which of those two regimes it is in for a given trace must treat the trace's cost as unknown rather than as the close-time sum. ```python class UnreconciledTokenAttribution(RuntimeError): """Raised when a child span's token usage cannot be debited to a live ancestor and no post-hoc reconciliation path exists for the trace.""" pass def attribute_tokens(child_span, ledger): trace_id = child_span["trace_id"] parent_id = child_span["parent_span_id"] tokens = child_span["usage"]["input_tokens"] + child_span["usage"]["output_tokens"] parent = ledger.get_span(parent_id) if parent is None: # Parent never exported; cannot debit and cannot reconcile by ancestor. raise UnreconciledTokenAttribution( f"parent {parent_id} for child {child_span['span_id']} " f"in trace {trace_id} is absent from ledger" ) if parent["state"] == "open": ledger.debit(parent_id, tokens) return "debited_live" if parent["state"] == "sealed": # Parent already closed: close-time rollup is frozen and will miss these # tokens. Only a post-hoc reconciler keyed on (trace_id, span_id) is sound. if not ledger.has_reconciler(trace_id): raise UnreconciledTokenAttribution( f"child {child_span['span_id']} closed after parent {parent_id} " f"in trace {trace_id}; {tokens} tokens would be silently dropped " f"from the rollup because no reconciler is registered" ) ledger.enqueue_reconciliation(trace_id, child_span["span_id"], tokens) return "queued_for_reconciliation" raise UnreconciledTokenAttribution( f"parent {parent_id} in unexpected state {parent['state']!r}" ) ```