In what scenarios must an instance refuse to close a GenAI agent-turn span when tool-call child spans report `gen_ai.tool.call.id` values that do not reconcile with the parent's `gen_ai.agent.turn.tool_calls`
**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans for agent turns and their tool-call children, where the parent turn span is closed after the tool results are re-ingested into the model context. Does not apply to single-shot completion tracing with no tool loop, nor to runtimes that emit tool calls as span *events* rather than child spans.
Core Distinction
The failure is not "a tool call failed." A failed tool call is a normal, well-formed trace: the child span ends with `ERROR`, the parent turn records a `gen_ai.agent.turn.tool_calls` count that includes it, and the model sees a tool-result message describing the error. That is coherent telemetry.
The boundary case is subtler: **the set of tool-call identifiers the runtime *executed* diverges from the set the runtime *declares* on the parent agent-turn span, and the divergence is only detectable at span-close time.** OpenTelemetry's GenAI conventions treat `gen_ai.agent.turn.tool_calls` (a count/attribute on the parent) and `gen_ai.tool.call.id` (on each child) as *descriptive* — they carry no referential-integrity guarantee. Nothing in the SDK forces the parent's declared tool-call count to equal the number of distinct child spans that actually linked to it. When a model emits a parallel tool-call batch, the runtime fans out N children, but the parent's attribute is often written *before* the fan-out completes — from the model's raw response — while the children are created *after* deduplication, retry, or mid-batch cancellation. The two numbers are computed by different code paths at different times from different sources of truth.
The invariant that must hold: **for every agent-turn span, the multiset of `gen_ai.tool.call.id` values on linked child spans must be a subset of the tool-call identities declared on the parent, and any declared identity with no matching child must be explicitly annotated as `unexecuted` before the parent closes.** Closing the parent while this invariant is violated produces a trace that *looks* complete and is silently wrong — the worst class of telemetry defect, because downstream eval harnesses and cost attribution trust it.
What Was Observed
A planner agent emitted a single assistant message containing four parallel tool calls (`call_a`, `call_b`, `call_c`, `call_d`). The runtime wrote the parent turn span's `gen_ai.agent.turn.tool_calls = 4` synchronously from the parsed model response, then dispatched the four executions to an async executor. During dispatch:
- `call_b` was deduplicated against an identical call already in-flight from the prior turn (a cache-hit guard in the tool router), so **no child span was ever created** for it.
- `call_c` hit a per-turn token budget check and was cancelled before its span's `start` was recorded; the cancellation was logged to stderr but not to telemetry.
- `call_a` and `call_d` completed normally.
The parent turn span closed with `tool_calls = 4`, but only two child spans (`call_a`, `call_d`) ever linked to it. The trace backend rendered a turn with a declared count of four and an observable fan-out of two. No span carried `ERROR`. The parent's status was `OK`.
Downstream, an eval harness that computed "tool-call success rate" as `successful_children / parent.tool_calls` reported 2/4 = 50% for a turn that had in fact succeeded on every call it attempted. Worse, a cost-attribution job that summed child-span token usage and cross-checked against the parent's declared count flagged the turn as *truncated* and re-ran it — duplicating `call_a` and `call_d` side effects against a live payment API.
The root mechanic: **the parent's tool-call declaration is a *prediction* written from model output; the child spans are *observations* written from execution.** The two are reconciled by nothing. The GenAI conventions specify the attribute names and types but are deliberately silent on cross-span cardinality, so each runtime invents its own (non-)reconciliation.
Condition of Validity
The refusal-to-close rule is valid — and required — precisely under these conditions, all of which must hold:
- The parent agent-turn span declares a tool-call count or identity list (`gen_ai.agent.turn.tool_calls`, or a custom `tool_call_ids` array attribute) **at a time strictly before** all child tool spans have ended.
- Tool execution is fanned out concurrently or through a router that can deduplicate, cancel, or short-circuit calls without emitting a span.
- A consumer exists that treats the parent's declared count as ground truth for completeness, cost, or success-rate computation.
When any of these fails — e.g., the runtime writes the parent attribute only in the `on_end` hook after joining all children, with no dedup path — the divergence cannot occur and the invariant is trivially satisfied. The rule is *not* valid for runtimes that emit tool calls as span events on the parent (there, event count is atomic with the parent by construction).
Decision Boundary
At parent-span close, the runtime must compute:
- `declared = {id : id ∈ parent.gen_ai.agent.turn.tool_call_ids}` (or the count, if only a count is available)
- `observed = {child.gen_ai.tool.call.id : child linked to parent}`
and branch:
- `observed ⊆ declared` **and** `declared \ observed = ∅` → close normally, `status = OK`.
- `observed ⊆ declared` **and** `declared \ observed ≠ ∅` → every missing id must be annotated `gen_ai.tool.call.status = "unexecuted"` (with reason: `deduplicated` / `budget_cancelled` / `router_short_circuit`) as a span event on the parent, **then** close. This is the legitimate divergence path; it must be *recorded*, not silently dropped.
- `observed ⊄ declared` (a child exists whose id the parent never declared) → this is a **hard integrity violation**: a tool executed that the turn does not account for. This indicates either an id-collision bug (two turns reusing a `call.id` from a shared model response) or a child span mis-parented across a context boundary. The parent must **not** close with `OK`. It must close with `status = ERROR`, `error.type = "tool_call_reconciliation_failure"`, and the offending ids attached.
The non-obvious part of the boundary: the `declared \ observed ≠ ∅` case (missing children) is *recoverable and common* and must not be treated as an error; the `observed ⊄ declared` case (orphan children) is *rare and always a bug* and must never be treated as benign. Naive implementations invert these — they tolerate orphans (because "the child succeeded, who cares") and error on missing children (because "count mismatch!"). Both inversions corrupt the trace.
Operational Effect
Enforcing the boundary converts a silent telemetry defect into a loud, structured one at the exact span where the divergence originates, before it propagates to eval and cost pipelines. The concrete effects:
- **Cost attribution stops double-counting.** Deduplicated calls (`call_b`) are marked `unexecuted/deduplicated` rather than vanishing, so a cost job that sums child usage and reconciles against declared count sees an explicit explanation instead of a phantom shortfall — and does not re-run the turn.
- **Success-rate metrics become correct.** The denominator (declared) and numerator (successful observed) are reconciled with explicit `unexecuted` accounting, so a 4-declared / 2-executed turn reports 2/2 attempted, not 2/4.
- **Cross-turn id collisions surface.** The `observed ⊄ declared` branch catches the case where a retried turn reuses a `gen_ai.tool.call.id` from a cached model response, producing a child that links to the wrong parent — a bug that otherwise only manifests as duplicated side effects weeks later.
The guardrail is cheap: one set-difference at span close, two attribute writes. The cost of *not* having it is a trace corpus that is confidently, invisibly wrong — which is worse than no trace at all, because agents and humans both act on it.
from dataclasses import dataclass, field
class ToolCallReconciliationError(RuntimeError):
"""Raised when a GenAI agent-turn span cannot be closed coherently."""
pass
@dataclass
class TurnSpan:
turn_id: str
declared_tool_call_ids: set[str]
observed_tool_call_ids: set[str] = field(default_factory=set)
events: list[dict] = field(default_factory=list)
closed: bool = False
def close_agent_turn_span(
span: TurnSpan,
*,
strict: bool = True,
) -> None:
"""
Enforce the reconciliation invariant before closing a GenAI agent-turn span.
- observed subset of declared, no missing -> OK
- observed subset of declared, missing -> annotate 'unexecuted', OK
- observed NOT subset of declared -> hard error (orphan tool calls)
"""
if span.closed:
raise ToolCallReconciliationError(
f"turn {span.turn_id}: span already closed; double-close detected"
)
declared = set(span.declared_tool_call_ids)
observed = set(span.observed_tool_call_ids)
orphans = observed - declared
if orphans:
# A tool executed that the turn never declared: id collision or
# cross-context mis-parenting. Never close OK.
raise ToolCallReconciliationError(
f"turn {span.turn_id}: orphan tool-call ids not declared by parent: "
f"{sorted(orphans)}; declared={sorted(declared)} observed={sorted(observed)}"
)
missing = declared - observed
if missing:
# Legitimate divergence (dedup / budget cancel / router short-circuit).
# Must be recorded, not silently dropped.
for call_id in sorted(missing):
span.events.append(
{
"name": "gen_ai.tool.call.unexecuted",
"attributes": {
"gen_ai.tool.call.id": call_id,
"gen_ai.tool.call.status": "unexecuted",
"reason": "deduplicated|budget_cancelled|router_short_circuit",
},
}
)
if strict and not span.events:
raise ToolCallReconciliationError(
f"turn {span.turn_id}: missing children but no annotation emitted"
)
span.closed = True