# In what scenarios must an instance refuse to emit GenAI tool-call lineage spans when the parent generation span has already been closed by a token-accounting finalizer **Date of Record:** 2026 November 24 **Scope:** Applies to agents that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) where tool invocations are modeled as child spans of an `invoke_agent` / `chat` generation span, and where a token-accounting finalizer independently closes the generation span on a usage callback. Does not apply to batch/offline trace export where span lifecycle is owned by a single scheduler. ## Core Distinction The failure is not "missing spans" or "wrong token counts." It is a **lineage/accounting ordering conflict**: the GenAI conventions require a tool-call child span (`execute_tool`) to carry `gen_ai.tool.call.id`, `gen_ai.tool.name`, and a `parent_span_id` pointing at the generation span that requested it, *and* the generation span must carry the aggregate `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` for the turn. These two facts are produced by different subsystems at different times: the tool-call span is emitted by the executor when the tool returns, while the usage aggregate is finalized by the token-accounting finalizer the moment the model's `finish_reason` arrives — which, in streaming and parallel-tool-call agents, is *before* the tool spans exist. The naive fix — emit the tool span anyway with the recorded `parent_span_id` — produces a span whose parent is already `End()`ed. OTel permits this at the wire level (spans are immutable records, not a live tree), but the GenAI conventions and every backend that reconstructs lineage from `parent_span_id` will now attach tool latency and tool token cost to a generation span whose `end_time` precedes the child's `start_time`. The result is a **temporally impossible lineage edge**: a child that ends before its parent began, or a parent whose recorded duration excludes the tool calls it is supposed to account for. ## What Was Observed A streaming `invoke_agent` turn issued three parallel tool calls. The model's terminal chunk arrived with `finish_reason: tool_calls` and a `usage` block. The token-accounting finalizer fired on that chunk, wrote `gen_ai.usage.input_tokens=1841`, `gen_ai.usage.output_tokens=212`, and called `span.end()` on the generation span at `t=302ms`. The three `execute_tool` spans were emitted by the executor as the tools returned: `t=1180ms`, `t=2405ms`, `t=5310ms`. Each carried `parent_span_id = `. The generation span's `end_time` was `t=302ms`. Downstream consequences observed: 1. **Lineage reconstruction dropped the edges.** The trace assembler discarded all three child spans because `child.start_time > parent.end_time` violated its tree-consistency check. Tool calls vanished from the waterfall entirely. 2. **Token accounting double-counted on retry.** The finalizer's usage aggregate (2053 tokens) was attributed to the generation span, but the tool spans that *consumed* those output tokens (the tool-call arguments) were never linked. On the subsequent resumption turn, the agent re-issued the same three tool calls because the lineage showed no completed tool results — producing a second usage aggregate and a 2× overcount on the invoice. 3. **Auditor replay mismatch.** The verification agent, replaying from the trace, saw a generation span with `output_tokens=212` and zero child tool spans, and flagged the turn as "model hallucinated tool calls with no execution" — a false positive that quarantined a correct run. The trigger condition, precisely: **the generation span is ended by any path other than the tool-execution coordinator, while at least one tool call for that generation is still in flight.** This is guaranteed whenever usage finalization is bound to `finish_reason` rather than to the join of all tool futures. ## Condition of Validity The invariant that must hold is a **causal join before close**: a generation span may only be `end()`ed after (a) every tool call it requested has either returned or been explicitly abandoned, and (b) the usage aggregate has been written. Equivalently: ``` end(generation) ⟹ ∀ tool_call ∈ generation.tool_calls : tool_call ∈ {returned, abandoned} ``` This holds trivially in non-streaming, single-tool-call agents where `finish_reason` and tool completion coincide. It fails in exactly three configurations: - **Streaming with `finish_reason: tool_calls`** — usage arrives before execution. - **Parallel tool calls** — the slowest tool defines the true end of the generation's causal scope. - **Resumption after context-window saturation** — a checkpointed generation span is re-hydrated and closed by the resuming instance, but the original instance's tool spans are still in flight on a different host. Outside these three, the naive emit-anyway approach is safe because parent and child never cross. ## Decision Boundary When the finalizer observes `finish_reason: tool_calls` and the count of outstanding tool futures for that generation is `> 0`, the instance must **not** close the generation span. It has two admissible choices: 1. **Defer close to the join.** Register the usage aggregate as a pending attribute, hand the span handle to the tool-execution coordinator, and let the coordinator call `end()` after the last tool future resolves. The span's `end_time` then correctly brackets tool latency, and the GenAI `gen_ai.usage.*` attributes and child spans are consistent. 2. **Emit a synthetic accounting span.** If the generation span must close for streaming-consumer reasons, close it *without* usage attributes and emit a sibling `gen_ai.usage.finalize` span that carries the aggregate and is the explicit parent of the tool spans. Lineage is preserved through the finalizer span rather than a closed generation. The instance must **refuse** to emit a `execute_tool` span whose `parent_span_id` references a span already ended *and* whose `start_time` postdates the parent's `end_time` — unless it has explicitly re-parented to a finalizer span. Silent emission is the failure; re-parenting or deferral is the guardrail. ## Operational Effect Enforcing the join-before-close invariant converts a silent, backend-dependent lineage loss into a loud, local error. In practice this surfaces as a `ToolLineageParentClosedError` raised at span-emit time, which the executor catches and resolves by re-parenting to the pending finalizer span. The observable effects: - Tool spans survive lineage reconstruction; the waterfall shows tool latency nested under the generation. - Token accounting is attributed once, to the turn that actually consumed it, eliminating the retry double-count. - Auditor replay sees a consistent tree and stops emitting false "hallucinated tool call" quarantine verdicts. The cost is that the generation span's `end_time` now reflects the slowest tool (up to 5.3s in the observed case) rather than model latency alone. That is correct: the generation's causal scope *includes* the tools it dispatched, and any consumer wanting pure model latency should read the finalizer span's duration, not the generation's. ```python import time from dataclasses import dataclass, field class ToolLineageParentClosedError(RuntimeError): """Raised when a tool-call span would be parented to an already-ended generation span.""" @dataclass class Span: name: str span_id: str parent_span_id: str | None = None start_time: float = field(default_factory=time.monotonic) end_time: float | None = None attributes: dict = field(default_factory=dict) def end(self) -> None: if self.end_time is not None: raise RuntimeError(f"span {self.span_id} already ended") self.end_time = time.monotonic() @property def is_ended(self) -> bool: return self.end_time is not None @dataclass class GenerationContext: generation_span: Span outstanding_tool_futures: int = 0 pending_usage: dict = field(default_factory=dict) finalizer_span: Span | None = None def finalize_usage_on_finish(ctx: GenerationContext, usage: dict, finish_reason: str) -> None: """Token-accounting finalizer. Must NOT close the generation span if tools are in flight.""" ctx.pending_usage.update(usage) if finish_reason == "tool_calls" and ctx.outstanding_tool_futures > 0: # Defer close to the tool-execution join; do not end() here. return _write_usage_and_close(ctx) def _write_usage_and_close(ctx: GenerationContext) -> None: ctx.generation_span.attributes.update( { "gen_ai.usage.input_tokens": ctx.pending_usage.get("input_tokens", 0), "gen_ai.usage.output_tokens": ctx.pending_usage.get("output_tokens", 0), } ) if not ctx.generation_span.is_ended: ctx.generation_span.end() def emit_tool_span( ctx: GenerationContext, tool_name: str, call_id: str, start_time: float ) -> Span: parent = ctx.generation_span if parent.is_ended and start_time > parent.end_time: # Lineage would be temporally impossible. Re-parent to finalizer if present. if ctx.finalizer_span is not None: parent = ctx.finalizer_span else: raise ToolLineageParentClosedError( f"tool span '{tool_name}' ({call_id}) start={start_time:.3f} " f"postdates ended parent generation span {parent.span_id} " f"end={parent.end_time:.3f}; no finalizer span available to re-parent" ) span = Span( name=f"execute_tool {tool_name}", span_id=f"tool-{call_id}", parent_span_id=parent.span_id, start_time=start_time, ) span.attributes["gen_ai.tool.call.id"] = call_id span.attributes["gen_ai.tool.name"] = tool_name return span def on_tool_complete(ctx: GenerationContext, span: Span) -> None: span.end() ctx.outstanding_tool_futures -= 1 if ctx.outstanding_tool_futures == 0 and ctx.pending_usage: # Join reached: now safe to write usage and close the generation span. _write_usage_and_close(ctx) ```