# Under what conditions must an instance attribute span latency to the wrong agent step when async tool callbacks outlive their parent span **Date of Record:** 2026 November 30 **Scope:** Applies to single- or multi-agent runtimes that emit per-step and per-tool-call spans to a tracing backend and compute cost/latency attribution by span parentage. Does not apply to synchronous, single-threaded invocations where every tool callback completes before the enclosing step span closes. ## Core Distinction Observability attribution is not logging. Logging tolerates misordered, orphaned, or duplicated records because a human reads them and reconstructs intent. Attribution *is* the accounting: a span's `parent_span_id` is the sole claim of which agent step owns a unit of latency and cost. When an async tool callback returns after its parent step span has already been closed and flushed, the runtime has two mutually exclusive options and no default that is correct for both: (a) attach the late span to the parent that no longer exists, producing an orphan whose duration is silently dropped from the step's total, or (b) attach it to whatever span happens to be "current" on the context at callback time, which is a *different* step — possibly a different agent — that inherited the context variable. Option (a) under-counts the step; option (b) over-counts a sibling. Both corrupt the per-step cost ledger, and the corruption is invisible because the trace still renders as a well-formed tree. ## What Was Observed A two-agent pipeline (planner → executor) ran a step that dispatched an asynchronous retrieval tool with a 4.2 s server-side tail latency. The executor step span closed at 900 ms — the model had already consumed the tool's *acknowledgement* token and moved on — and was flushed to the collector. The tool's completion span returned at 4.2 s. Because the runtime used `contextvars` for span propagation and the callback was scheduled on a worker that had been re-pooled, the completion span's inherited context pointed at the *planner's next step*, which had begun at 1.1 s. The completion span therefore recorded `parent_span_id = planner_step_7` with a `duration_ms` of 4200. Downstream attribution computed planner step 7 as 5.4 s wall-clock (1.2 s of real reasoning plus the 4.2 s retrieval it never invoked) and the executor step as 0.9 s with a tool call whose cost was attributed to the wrong owner. The executor's true 4.2 s tool latency vanished from its ledger entirely. Two invariants broke at once: the sum of child span durations no longer reconciled with any parent's wall-clock, and the cost-per-agent report charged the planner for retrieval tokens the executor consumed. The trace was structurally valid — every span had a resolvable parent — so no schema validator, no "orphan span" alert, and no tree-depth check fired. The distinguishing signal was a reconciliation mismatch, not a broken trace: `sum(child.duration) > parent.wall_clock` for the planner, and `sum(child.duration) < parent.wall_clock - parent.self_time` for the executor. Neither is checked by default because both are normal under concurrency. ## Condition of Validity The misattribution is *bounded and predictable* only when all four of the following hold; if any fails, the failure mode changes shape and the guardrail below is insufficient: 1. **Span context is propagated by ambient context variable, not by explicit handle passing.** If the tool callback receives its parent span as an argument, late completion attaches to the correct (closed) parent and becomes a recoverable orphan rather than a silent re-parent. 2. **Parent spans are closed and flushed on step boundary, independent of outstanding child work.** This is the trigger. If the runtime holds the step span open until all dispatched tools report, there is no window for re-parenting — but then step latency is inflated by tool tail, which is its own attribution lie. 3. **The worker pool reuses execution contexts across steps.** Context reuse is what lets a stale `current_span` leak into the callback. A fresh context per callback would orphan instead of misattribute. 4. **Attribution is computed post-hoc from the span tree, not from a synchronous counter incremented at dispatch.** A dispatch-time reservation (reserve expected cost, reconcile on completion) is immune because ownership is fixed before the async boundary. When condition 2 fails (span held open), you get *latency inflation* not misattribution. When condition 3 fails (fresh context), you get *orphaning* not misattribution. Only the conjunction produces a wrong-but-valid tree. ## Decision Boundary The runtime must decide, at the moment a step span closes with outstanding dispatched children, whether to (i) keep the step logically open for attribution while marking it "emitted," (ii) transfer ownership of late children to a synthetic `detached_tool` span parented to the trace root, or (iii) reject the close and block until children settle. The boundary is the *settle deadline*: a step may close early only if every dispatched tool has either completed or exceeded a declared `tool_deadline_ms`. Past the deadline, ownership must be reassigned to the trace root with an explicit `detached_reason` attribute — never to the ambient current span. The invariant to enforce: **a span's parent must have been open at the moment the span was *dispatched*, and that parentage is immutable across the async boundary.** Re-parenting on completion is the bug; freezing parentage at dispatch is the fix. ## Operational Effect Without the freeze, per-agent cost reports drift in the direction of whichever agent runs *after* the slow tool — systematically, not randomly, because the re-parenting target is always the next step to acquire the reused context. In a planner/executor split this means the planner is consistently overcharged for executor I/O, and the error grows with tool tail latency. Budget alarms keyed on per-agent spend fire on the wrong agent; autoscalers that scale the over-charged agent add capacity to the wrong tier. The reconciliation check — `sum(children.duration) ≤ parent.wall_clock` per step, and equality of `sum(tool.cost)` across agents to the trace-level total — is the only detector that catches it, and it must be run as a hard assertion at trace finalization, not sampled. ```python from dataclasses import dataclass, field from typing import Optional class AttributionInvariantError(RuntimeError): """Raised when span parentage or cost reconciliation is violated.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] agent_id: str dispatched_at_ms: int closed_at_ms: Optional[int] = None frozen_parent_id: Optional[str] = None detached_reason: Optional[str] = None children: list = field(default_factory=list) def close_step_span( step: Span, outstanding: list[Span], now_ms: int, tool_deadline_ms: int, trace_root_id: str, ) -> None: # Freeze parentage at dispatch: any child dispatched while this step was # open is irrevocably owned by this step, regardless of completion time. for child in outstanding: if child.frozen_parent_id is None: child.frozen_parent_id = step.span_id # If a child was already re-parented by ambient context, that is the bug. if child.parent_id is not None and child.parent_id != step.span_id: raise AttributionInvariantError( f"child {child.span_id} parented to {child.parent_id} " f"but dispatched under {step.span_id} (agent {child.agent_id})" ) overdue = (now_ms - child.dispatched_at_ms) > tool_deadline_ms if overdue and child.closed_at_ms is None: # Past deadline: detach to trace root, never to ambient current span. child.frozen_parent_id = trace_root_id child.detached_reason = "tool_deadline_exceeded" step.closed_at_ms = now_ms def reconcile_trace(spans: list[Span], trace_total_cost: float) -> None: by_parent: dict[str, float] = {} for s in spans: if s.closed_at_ms is not None and s.frozen_parent_id is not None: dur = s.closed_at_ms - s.dispatched_at_ms by_parent[s.frozen_parent_id] = by_parent.get(s.frozen_parent_id, 0.0) + dur for parent in spans: if parent.closed_at_ms is None: continue wall = parent.closed_at_ms - parent.dispatched_at_ms child_sum = by_parent.get(parent.span_id, 0.0) if child_sum > wall + 1: # 1ms tolerance for clock granularity raise AttributionInvariantError( f"span {parent.span_id} (agent {parent.agent_id}): " f"children sum {child_sum}ms exceeds wall {wall}ms — " f"late callback re-parented onto wrong step" ) ```