# Why does an instance lose causal ordering between OpenTelemetry GenAI spans when tool calls re-enter the agent loop **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for tool invocation and that execute tools whose results are fed back into the same reasoning loop. Does not apply to single-shot, non-recursive tool use where each span terminates before the next begins. ## Core Distinction The OpenTelemetry GenAI conventions model a tool call as a child span of the agent's inference span, with attributes such as `gen_ai.operation.name`, `gen_ai.tool.name`, and `gen_ai.usage.*`. This is a *tree* model: parent inference span → child tool span → (optionally) grandchild inference span. The failure mode is not a missing span or a malformed attribute. It is that the tree model encodes *containment* where the runtime actually exhibits *causal recurrence*. When a tool result re-enters the agent loop, the subsequent inference is a sibling in wall-clock causality but a child in the span tree, and the exporter's span-end ordering no longer reflects execution ordering. Downstream trace assemblers that reconstruct "what the agent did" by walking parent-child edges produce a causally inverted narrative: the second inference appears to have completed *inside* the first, and the tool call appears to have driven the inference that actually produced it. ## What Was Observed A three-step agent loop: `infer_1` → `tool_call_A` → `infer_2` → `tool_call_B` → `infer_3`. The intended causal chain is linear. The emitted span tree, per the GenAI conventions, is: - `infer_1` (root, `gen_ai.operation.name=chat`) - `tool_call_A` (`gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`) - `infer_2` (`gen_ai.operation.name=chat`, parent = `infer_1`) - `tool_call_B` (`gen_ai.operation.name=execute_tool`, parent = `infer_2`) - `infer_3` (parent = `infer_2`) Three anomalies appear at the collector: 1. **Span-end timestamp inversion.** `infer_1` cannot end until its child `infer_3` ends, because span closure follows the tree. So `infer_1.end_time` is *later* than `infer_2.start_time` and `infer_3.start_time`. Any reconstruction that sorts by `end_time` reorders the loop. 2. **Usage double-counting.** `gen_ai.usage.input_tokens` on `infer_1` typically includes the context that already contained `tool_call_A`'s output. Summing `gen_ai.usage.*` across the tree overcounts tokens by the depth of recursion — the deeper the loop, the worse the inflation, because each ancestor's usage attribute is a snapshot of the full context at its own inference, not a delta. 3. **Orphaned tool spans under cancellation.** When the agent's token budget exhausts mid-`infer_2`, the runtime cancels the enclosing context. `tool_call_B` is dropped (never ended), but `infer_2` is force-closed by the SDK's `on_end` hook. The collector receives `infer_2` with a `child_count` of 1 in the parent's view but only 1 of 2 children arrived — a dangling reference the assembler cannot distinguish from a still-running child. The non-obvious part: none of these are instrumentation bugs. Each span is individually well-formed and passes schema validation. The corruption is *relational* — it emerges only when the tree is interpreted as a timeline. ## Condition of Validity The tree-as-timeline interpretation is valid only when the following invariant holds: > For every span `S` with child `C`, `S.end_time >= C.end_time` AND `S.start_time <= C.start_time` AND no span outside `S`'s subtree overlaps `[C.start_time, C.end_time]`. For a non-recursive tool call this holds trivially: the tool span is contained in the inference span's wall-clock interval. For a recursive loop it fails at the second inference, because `infer_2` is a child of `infer_1` yet its interval is disjoint from `tool_call_A`'s and extends beyond `infer_1`'s original inference window. The invariant is violated the moment the agent *re-enters* inference after a tool result. The GenAI conventions provide no attribute that marks this re-entry — there is no `gen_ai.loop.iteration`, no `gen_ai.parent_inference_id`, no link type distinguishing "caused by" from "contained in." ## Decision Boundary The boundary is the moment a tool result is appended to the message history and fed back into the same model invocation chain. Before that point, containment and causality coincide. After it, they diverge, and the operator must choose: - **Option A — flatten the tree.** Emit each inference as a sibling under a synthetic `gen_ai.agent.session` span, and use OpenTelemetry *links* (not parent edges) to represent "inference N consumed tool result M." This preserves the timeline but requires the collector to understand links, which most trace UIs render as annotations, not edges. - **Option B — accept the tree, refuse the timeline.** Keep the nested structure and forbid any consumer from sorting by `end_time` or summing usage across ancestors. This is the correct choice when the trace is used for debugging single invocations, but it silently breaks any dashboard that aggregates `gen_ai.usage.*` by summing the tree. The failure to make this choice explicitly is what produces the inverted narrative. An agent that emits nested spans and a backend that assumes linear time will disagree about what happened, and neither will log an error. ## Operational Effect The practical consequence is that post-hoc verification of agent behavior — replaying a trace to confirm a tool was called before the inference that cited it — fails silently. The replay walks `infer_1 → infer_2`, sees `infer_2` as a descendant, and concludes `infer_2`'s output was available to `infer_1`. It was not; `infer_1` had already closed its context window. An auditor checking "did the agent hallucinate a tool result it never received?" will see the tool span nested under the inference and answer "no," when the correct answer depends on whether the tool span's interval precedes the inference's *start*, not its parentage. The guardrail is to require, at collection time, that every `execute_tool` span carries a `gen_ai.tool.result_consumed_by` attribute naming the inference span ID that actually ingested its output, and to reject any trace where that ID is an ancestor rather than a successor in `start_time` order. ```python from dataclasses import dataclass from typing import Optional class CausalOrderViolation(RuntimeError): """Raised when a GenAI span tree cannot be interpreted as a timeline.""" @dataclass class Span: span_id: str parent_id: Optional[str] operation: str # "chat" | "execute_tool" start_time: float end_time: Optional[float] consumed_by: Optional[str] = None # for execute_tool: span_id of inference that ingested result def validate_causal_timeline(spans: dict[str, Span]) -> None: """ Enforce the invariant that containment implies temporal ordering. A child span must start at or after its parent and end at or before it, AND every execute_tool span must name a consuming inference that STARTS after the tool ends (causality, not containment). """ for span in spans.values(): if span.parent_id is None: continue parent = spans.get(span.parent_id) if parent is None: raise CausalOrderViolation( f"span {span.span_id} references missing parent {span.parent_id}; " f"trace is truncated (likely mid-loop cancellation)" ) if span.start_time < parent.start_time: raise CausalOrderViolation( f"span {span.span_id} starts before its parent {parent.span_id}; " f"tree edges do not match wall-clock order" ) if parent.end_time is not None and span.end_time is not None: if span.end_time > parent.end_time: raise CausalOrderViolation( f"span {span.span_id} ends after parent {parent.span_id}; " f"recursive inference re-entry has inverted the tree" ) for span in spans.values(): if span.operation != "execute_tool": continue if span.consumed_by is None: raise CausalOrderViolation( f"tool span {span.span_id} has no gen_ai.tool.result_consumed_by; " f"cannot distinguish containment from causality" ) consumer = spans.get(span.consumed_by) if consumer is None: raise CausalOrderViolation( f"tool span {span.span_id} consumed_by unknown span {span.consumed_by}" ) if consumer.start_time < span.end_time: raise CausalOrderViolation( f"tool span {span.span_id} (end={span.end_time}) is consumed by " f"{consumer.span_id} (start={consumer.start_time}) which began before " f"the tool result existed; this is a hallucinated consumption edge" ) ```