# Which invariants prevent span-level cost attribution from silently misattributing tokens when a tool call fans out into parallel sub-agent spans **Date of Record:** 2026 November 25 **Scope:** Applies to trace-based observability pipelines that attribute token cost and wall-clock latency to individual agent steps and tool calls, where a single tool invocation may dispatch concurrent child spans (sub-agents, retries, speculative branches). Does not apply to single-threaded, single-span-per-step tracing, nor to billing reconciliation against provider invoices (which is a separate, coarser invariant). ## Core Distinction The failure here is not "the trace is missing spans" or "the cost total is wrong." Those are visible. The non-obvious failure is **attribution drift under fan-out**: the aggregate cost of a parent step remains numerically correct while the per-child, per-tool-call attribution is silently redistributed. The trace looks internally consistent — parent cost equals sum of children — but individual tool calls carry costs they did not incur, because a child span's token usage was recorded against a shared parent context window, and the splitter assigned it by heuristic (equal division, or "last writer wins"). The distinction that matters: **accounting identity (parent = Σ children) is not the same as causal identity (child cost = tokens the child's own model call consumed).** Observability systems routinely enforce the first and assume it implies the second. It does not. Under fan-out, the two diverge, and the divergence is unobservable from the trace alone. ## What Was Observed A planner agent emits a single step `step_7` that invokes a tool `search_and_summarize`. That tool internally spawns three parallel sub-agent spans (`sub_A`, `sub_B`, `sub_C`) that each call the same model with different query fragments, then a reducer span `sub_R` merges their outputs into one completion attributed to `step_7`. The pipeline records token usage at the **parent completion** boundary: the provider returns one usage object for `step_7` (input tokens, output tokens) because the orchestration framework batched the three sub-calls into one completion request, or because the framework only instruments the outer call site. The three child spans exist as latency spans but carry **no independent usage object**. The attribution layer then applies a default policy: distribute parent usage across children by span duration weight. This is where drift enters. `sub_A` ran longest (it hit a retry after a malformed tool output), so it absorbs the largest share of tokens — but the retry's re-sent prompt was already counted in the parent's input tokens **once**, while the duration weight implies it was paid proportionally to time. The result: `sub_A` reports 61% of input tokens when it actually consumed ~33% plus one retry worth of duplication, `sub_C` reports 14% when it consumed a full third. The trace passes the accounting identity check (`61 + 25 + 14 = 100`). It fails causal identity. Downstream, a cost-regression detector flags `sub_A`'s tool as "expensive" and an engineer optimizes the wrong code path. The second observed mode is worse: when the reducer `sub_R` re-invokes the model to merge, its completion is recorded as a **new** top-level usage event but is nested under `step_7` in the span tree. The parent's usage object now double-counts — once as the batched sub-call, once as the reducer — and the accounting identity check fails loudly. Engineers "fix" it by dropping the reducer's usage from the parent, which now under-counts the true parent cost and re-introduces silent drift on every subsequent merge. ## Condition of Validity The invariant that prevents drift is: **every span that issues a model call MUST carry its own provider-returned usage object, and parent usage MUST be defined as the sum of child usage objects, never as an independently recorded quantity.** This holds only when three conditions are simultaneously true: 1. **Usage is captured at the call site, not the orchestration boundary.** The instrumentation wraps the actual model client invocation inside each sub-agent, so a retry produces a second usage object on the same span (accumulated, with a retry counter), not a modified parent total. 2. **Fan-out spans are causally ordered before attribution runs.** Attribution must not execute until all children of a parent have closed and reported. If the splitter runs on a partial child set (streaming traces, async exporters), it divides a parent total across a subset and the remaining children later appear with zero cost. 3. **The reducer/merge step is a distinct span with its own usage, and the parent's usage is explicitly the sum including the reducer.** No framework-level batching may collapse multiple model calls into one usage object without emitting synthetic child spans per call. When any condition fails, the accounting identity may still pass while causal identity is violated — and the violation is not detectable by comparing parent to children, because that comparison is exactly what was corrupted. ## Decision Boundary The boundary is whether the observability pipeline treats **usage as a property of a model call** or **as a property of a span**. These are the same thing only when spans and model calls are 1:1. Under fan-out, retries, speculative decoding branches, or framework batching, they are not. Operational rule: if a span can issue more than one model call (retry, fan-out, merge), it is not a valid attribution unit. Split it until every span maps to exactly one model call, or carry an explicit `call_index` and per-call usage array on the span. A span with `call_count > 1` and a single scalar `input_tokens` is a drift hazard and must be rejected at ingest, not reconciled later. The second boundary: **never allow the attribution layer to synthesize usage that the provider did not return.** Duration-weighted or equal splits are acceptable only as a labeled `estimated: true` field, never as the authoritative cost field. Any downstream consumer that sums authoritative cost must see only provider-returned values; estimates live in a separate namespace so a cost-regression detector cannot confuse the two. ## Operational Effect Enforcing call-site usage capture converts a silent, self-consistent misattribution into a loud ingest failure. The cost: orchestration frameworks that batch sub-calls must be instrumented at the client layer rather than the graph layer, which is more invasive and requires per-retry accumulation logic. The benefit: per-tool-call cost becomes causally meaningful, so optimization effort lands on the actual expensive call, and the trace's parent-equals-sum identity becomes a *consequence* of correct capture rather than a heuristic that masks errors. The residual risk after enforcement is fan-out spans that close out of order across async exporters — mitigated by holding attribution until a parent's child set is complete (tracked by an expected-child count on the parent span), and failing the attribution job rather than emitting a partial split. ```python from dataclasses import dataclass, field from typing import Optional class AttributionDriftError(RuntimeError): """Raised when a span's usage cannot be causally attributed to model calls.""" pass @dataclass class ModelCall: call_index: int input_tokens: int output_tokens: int is_retry: bool = False @dataclass class Span: span_id: str parent_id: Optional[str] calls: list[ModelCall] = field(default_factory=list) expected_children: int = 0 closed_children: int = 0 @property def call_count(self) -> int: return len(self.calls) @property def total_input(self) -> int: return sum(c.input_tokens for c in self.calls) @property def total_output(self) -> int: return sum(c.output_tokens for c in self.calls) def attribute_span(span: Span, children: list[Span]) -> dict: # Invariant 1: every span must map to >=1 explicit model call with provider usage. if span.call_count == 0 and not children: raise AttributionDriftError( f"span {span.span_id} has no model calls and no children; " f"usage would have to be synthesized (drift hazard)" ) # Invariant 2: no scalar parent usage independent of children. # If a span has both its own calls AND children, it is a merge/batch span # whose own usage must be an explicit, separate call — not a batched total. if span.call_count > 1 and children: raise AttributionDriftError( f"span {span.span_id} issued {span.call_count} calls and has " f"{len(children)} children; batched usage cannot be causally split. " f"Split into one span per model call." ) # Invariant 3: attribution only runs on a complete child set. if span.closed_children < span.expected_children: raise AttributionDriftError( f"span {span.span_id} has {span.closed_children}/" f"{span.expected_children} children closed; partial split would " f"silently zero out late children" ) # Invariant 4: parent total == sum of children + own calls (accounting identity), # and every child's usage is provider-returned (causal identity). own_in = span.total_input own_out = span.total_output child_in = sum(c.total_input for c in children) child_out = sum(c.total_output for c in children) for c in children: if c.call_count == 0: raise AttributionDriftError( f"child {c.span_id} of {span.span_id} closed with zero calls; " f"its cost cannot be attributed and must not be estimated silently" ) return { "span_id": span.span_id, "attributed_input": own_in + child_in, "attributed_output": own_out + child_out, "source": "provider_returned", "children": [c.span_id for c in children], } def ingest(trace: dict[str, Span]) -> None: by_parent: dict[str, list[Span]] = {} for s in trace.values(): if s.parent_id: by_parent.setdefault(s.parent_id, []).append(s) for s in trace.values(): if s.parent_id is None: attribute_span(s, by_parent.get(s.span_id, [])) ```