# Which invariants prevent GenAI Agent Span Misattribution When Parallel Tool-Call Fan-Out Exceeds the Parent Span's Emit Window **Date of Record:** 2026 November 21 **Scope:** Applies to agents emitting OpenTelemetry spans under the `gen_ai.*` semantic conventions (GenAI semconv ≥ v1.29) where a single agent turn fans out to concurrent tool calls whose completions may be reordered, dropped, or emitted after the parent agent span has ended. Does not cover single-threaded linear tool-call chains, or spans emitted by a gateway/proxy that owns its own trace lifecycle. ## Core Distinction The `gen_ai.agent.*` span hierarchy assumes a **parent-child causal ordering**: the agent span (carrying `gen_ai.agent.name`, `gen_ai.agent.id`, `gen_ai.operation.name=invoke_agent`) opens, emits child `gen_ai.tool.call` spans, and closes only after all children have been emitted with matching `parent_span_id`. The GenAI conventions treat the agent span's `end_time` as the boundary of its accounting window: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes of that span, and downstream aggregation (cost dashboards, token-budget auditors, replay verifiers) sums those attributes over spans whose `end_time` falls in a reporting interval. The non-obvious failure is that **tool-call span linkage and token accounting are decoupled by the emit window**. A tool span can be a *legitimate child* of the agent span (correct `trace_id`, correct `parent_span_id`) yet be emitted to the collector *after* the parent span has been closed and exported. Most exporters (OTLP batching, `BatchSpanProcessor`) do not enforce parent-before-child ordering on the wire, and the collector's span processor does not retroactively re-open a closed parent. The result: tool spans arrive orphaned by arrival order, their `gen_ai.tool.call.id` linkage resolves against a parent whose token attributes were already finalized, and any per-turn token reconciliation that joins tool spans to the parent's usage counters silently drops the late children. The invariant that prevents this is **monotonic span-closure with deferred usage finalization**: the agent span must not finalize `gen_ai.usage.*` or set `end_time` until every child tool span it spawned has been *acknowledged as exported*, not merely *created*. Creation-order parent-child links are insufficient; export-order acknowledgment is the binding condition. ## What Was Observed An agent executing a single `invoke_agent` turn dispatched four parallel tool calls (`search`, `fetch`, `summarize`, `write`). The agent span opened at `t0`, spawned all four children, and the orchestrator awaited the fastest three. The fourth (`write`, a slow filesystem tool) exceeded the orchestrator's internal 800ms soft deadline; the orchestrator treated it as backgrounded, closed the agent span at `t0+812ms`, and exported it with `gen_ai.usage.output_tokens=4187`. The `write` tool span completed at `t0+1904ms` and was emitted through the same `BatchSpanProcessor` on its next flush. It carried the correct `trace_id` and the correct `parent_span_id` (the closed agent span's `span_id`), plus `gen_ai.tool.call.id` matching the `tool_call_id` the model emitted. On the wire it was a well-formed child span. Downstream, the token auditor joined `gen_ai.tool.call` spans to their parent `invoke_agent` span by `parent_span_id` and summed `gen_ai.usage.*` per turn. Because the parent had already been exported and its usage attributes frozen, the auditor's join produced a turn record with **three tool spans and 4187 output tokens**—the `write` span's own `gen_ai.usage` (the tool's internal model call, 2900 tokens) was attributed to a *different* turn window (the next flush interval), inflating the next turn's cost by ~69% and undercounting the current turn. A replay verifier that re-executed the turn and compared tool-call sets flagged a `tool_call_set_mismatch` on 1 of 4 calls, then deadlocked because its reconciliation loop waited for a fourth child that the parent's `end_time` had already excluded from the window. The failure was invisible in trace UIs that render by span tree (the child appears correctly nested) and only surfaced in any consumer that aggregates **by parent span end_time**. This is the trap: tree rendering and windowed aggregation disagree about the same trace. ## Condition of Validity The deferred-finalization invariant is *required* (not merely recommended) whenever all of the following hold: 1. The agent span is the accounting owner of `gen_ai.usage.*` and tool spans carry their own `gen_ai.usage.*` that must roll up to the same turn. 2. Tool calls execute concurrently or asynchronously, so completion order ≠ emission order. 3. Any consumer aggregates by `parent_span_id` joined to parent `end_time` (i.e., windowed rollup), rather than by pure tree traversal. It is *not* required when tool spans are emitted synchronously before the parent closes (strict sequential chain), or when the collector is configured with a parent-close barrier that blocks parent export until all known children are acked. In those cases the invariant is trivially satisfied and adding deferred finalization only adds latency. The boundary condition is precisely: **`child.emit_time > parent.end_time` while `child.parent_span_id == parent.span_id`**. This is a legal OTLP state; nothing in the spec forbids it. The invariant exists to make that state unreachable for usage-bearing children. ## Decision Boundary The decision is whether to (a) block parent closure on child export acknowledgment, or (b) accept orphan-by-arrival children and make consumers join by `trace_id` + `gen_ai.tool.call.id` rather than by parent `end_time`. Choose (a) **deferred finalization** when the agent span is the sole accounting owner and turn-level token reconciliation must be exact—i.e., when a token-budget auditor or cost ledger reads `gen_ai.usage.*` per `invoke_agent` span. The cost is bounded added latency (the parent's `end_time` is the max child ack time, not the orchestrator's soft deadline); the orchestrator's soft deadline must be demoted from "close parent" to "mark child as backgrounded but keep parent open." Choose (b) **call-id join** when the agent span cannot be kept open (e.g., it is emitted by a stateless edge worker that must return within a hard SLA) and consumers can be rewritten to join on `gen_ai.tool.call.id`. This requires the tool span to carry a stable `gen_ai.tool.call.id` that is *globally unique within the trace* and that the parent records in a `gen_ai.tool.call.ids` array attribute at close time, so a late child can be reconciled to the correct turn by id even after the window closed. The anti-pattern to avoid is the hybrid: closing the parent on the soft deadline (so `end_time` excludes the slow child) **and** relying on `parent_span_id` for the join. That combination produces the exact misattribution observed—the child is structurally a child but temporally an orphan, and the two views disagree. ## Operational Effect With deferred finalization enforced, the agent span's `end_time` becomes `max(child.ack_time)` rather than the orchestrator's soft deadline, and `gen_ai.usage.*` is written only after the last child ack. A slow `write` tool extends the turn's accounting window by ~1.1s but keeps the turn record atomic: four tool spans, one usage total, no cross-window bleed. The replay verifier's tool-call-set comparison passes because the parent's window now contains all four `gen_ai.tool.call.id` values it spawned. The secondary effect is on the auditor's deadlock: reconciliation loops that iterate `expected_tool_calls - seen_tool_calls` must terminate when the parent span is *closed and final*, not when a timer expires. Deferred finalization makes "parent closed" a reliable terminal signal—there is no fourth child arriving later, because the parent could not have closed without acking it. Without the invariant, the auditor's loop has no sound termination condition and must fall back to a timeout heuristic, which is exactly the deadlock path observed. The guardrail is therefore twofold: (1) the agent runtime must not set `end_time` or write `gen_ai.usage.*` until every spawned `gen_ai.tool.call.id` has an export acknowledgment; (2) if a hard SLA forces early close, the parent must record the full `gen_ai.tool.call.ids` set as an attribute so late children remain reconcilable by id, and consumers must be configured to join on that set rather than on `end_time`. Emitting a parent span whose `end_time` precedes a known child's emission, while also omitting the call-id set, is the unrecoverable state. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Set class SpanEmitWindowViolation(RuntimeError): """Raised when an agent span finalizes usage/end_time before all spawned tool-call children have been acknowledged as exported.""" @dataclass class AgentSpan: span_id: str trace_id: str spawned_tool_call_ids: Set[str] = field(default_factory=set) acked_tool_call_ids: Set[str] = field(default_factory=set) usage_finalized: bool = False end_time: float | None = None def spawn_tool_call(self, tool_call_id: str) -> None: if self.usage_finalized or self.end_time is not None: raise SpanEmitWindowViolation( f"cannot spawn tool call {tool_call_id!r} on already-closed " f"agent span {self.span_id!r}" ) self.spawned_tool_call_ids.add(tool_call_id) def ack_tool_call_export(self, tool_call_id: str) -> None: if tool_call_id not in self.spawned_tool_call_ids: raise SpanEmitWindowViolation( f"ack for unspawned tool call {tool_call_id!r} on span " f"{self.span_id!r}" ) self.acked_tool_call_ids.add(tool_call_id) def finalize(self, end_time: float, output_tokens: int) -> None: pending = self.spawned_tool_call_ids - self.acked_tool_call_ids if pending: # The invariant: no usage finalization while any child is unacked. raise SpanEmitWindowViolation( f"agent span {self.span_id!r} cannot finalize usage " f"({output_tokens} tokens) at t={end_time}: " f"{len(pending)} tool-call child(ren) unacked: {sorted(pending)}" ) self.usage_finalized = True self.end_time = end_time def close_agent_turn( span: AgentSpan, soft_deadline: float, actual_export_times: Dict[str, float], output_tokens: int, ) -> float: """Close the agent turn honoring deferred finalization. The orchestrator's soft deadline is demoted to a *backgrounding* signal: it may stop awaiting, but it may not close the span. The span closes at max(child ack time), never earlier than the last spawned child's export. """ for tool_call_id, export_time in actual_export_times.items(): span.ack_tool_call_export(tool_call_id) if soft_deadline < max(actual_export_times.values(), default=soft_deadline): # Soft deadline was exceeded; we do NOT close early. We only record # that the deadline was breached and let finalization use the true # max-child ack time. pass true_end = max(actual_export_times.values(), default=soft_deadline) span.finalize(end_time=true_end, output_tokens=output_tokens) return true_end ```