# Where must an instance refuse to close a GenAI span when a tool-call child span is still open under OTel semantic conventions **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.agent.*`) and treat span close as the authoritative record of a completed tool call or agent handoff. Does not apply to runtimes that buffer telemetry offline and reconcile spans in a separate collector-side join. ## Core Distinction A GenAI span is not a log line. It is a **lifetime-bounded state record** whose end timestamp and `status.code` are the only signals a downstream verifier (auditor agent, replay harness, or cost governor) can use to decide whether a tool call actually terminated. The failure mode here is not "missing attributes." It is **premature span closure**: the parent `gen_ai.tool.call` or `gen_ai.agent.invoke` span is ended while a child span representing the actual side-effecting operation (an MCP `tools/call`, an A2A `tasks/send`, a nested model invocation) is still open. The parent closes with `status.code = OK` and a duration that reflects only the *dispatch* latency, not the *completion* latency. Every consumer of that span — cost accounting, retry logic, handoff warrant propagation — now operates on a lie that is structurally indistinguishable from truth. The distinction that matters: **an attribute is a claim; a span boundary is a proof.** OTel's semantic conventions give you `gen_ai.tool.name` and `gen_ai.tool.call.id` as attributes, but the *only* mechanism that proves the tool call finished is the parent span's end event occurring after all child end events. When an agent framework ends the parent inside a `finally:` block that runs before the child's async completion callback fires, the proof is forged. ## What Was Observed A multi-agent handoff runtime (planner → executor → auditor) instrumented per GenAI semconv v1.29 emitted a `gen_ai.agent.invoke` span for the executor with `gen_ai.operation.name = "invoke_agent"`, a child `gen_ai.tool.call` span for an MCP `tools/call` to a filesystem server, and a grandchild span for the model completion that decided to make the call. Under load, the following trace appeared repeatedly: ``` gen_ai.agent.invoke [executor] start=0.000 end=0.412 status=OK gen_ai.tool.call [fs.read_file] start=0.031 end=0.409 status=OK gen_ai.chat [claude] start=0.032 end=0.108 status=OK gen_ai.tool.call [fs.write_file] start=0.410 end=1.887 status=OK ← ends AFTER parent ``` The second tool call ends at t=1.887s but its parent `gen_ai.agent.invoke` closed at t=0.412s. The auditor agent, reading the trace to verify the executor's work, saw a parent span with `status.code=OK` and duration 412ms, concluded the write completed, and advanced the baton. The write actually completed 1.475s later — after the auditor had already read the file and found it stale, triggering a spurious re-plan. The re-plan then raced the original write, and a subsequent read observed a torn file. Root cause: the executor used `asyncio.gather(...)` to fire the two tool calls concurrently but wrapped the gather in a `try/finally` whose `finally` called `span.end()` on the agent span. When the *first* tool call resolved, an exception in the sibling's exception handler short-circuited the gather, the `finally` fired, and the agent span closed while the second child was still in flight. OTel's `Span.end()` is idempotent and does not block on open children — it simply records an end timestamp and freezes the span. There is no built-in invariant that a parent cannot end before its children. The auditor's verifier had no way to detect this from the span alone, because `gen_ai.tool.call.id` was present on both children and both had `status.code=OK`. The only signal was the temporal inversion — child end > parent end — which no standard OTel consumer checks for. ## Condition of Validity The invariant "a closed parent span implies all its children have closed" holds **only if** the span processor enforces it. The OTel SDK does not. Therefore any agent runtime that: 1. ends spans from `finally` blocks or async cleanup handlers that are not ordered after child completion, **and** 2. treats `status.code=OK` on a `gen_ai.agent.invoke` or `gen_ai.tool.call` span as a verifier-grade proof of completion, is operating outside the condition of validity. The span is still *valid telemetry* (it has the right attributes, the right names, a monotonic timestamp), but it is **not a valid completion proof**. Conversely, the invariant *does* hold when the runtime uses a structured `with tracer.start_as_current_span(...)` context manager that the async task owns for its full lifetime, or when a collector-side joiner reconciles parent/child end times and re-marks inverted parents as `status.code=ERROR` with `gen_ai.tool.call.incomplete=true` (a non-standard but necessary attribute). In those configurations, `status.code=OK` on a parent is a legitimate proof. ## Decision Boundary The boundary is **whether the span's end event is causally ordered after the side effect it claims to record.** Concretely: - If the tool call is synchronous and the span closes in the same call stack frame that returns the tool result → parent close is causally after completion. Safe. - If the tool call is dispatched to an async task, a thread pool, an MCP transport with its own event loop, or an A2A remote agent → the parent close is **not** causally ordered unless the parent awaits the child's completion signal. Unsafe. - If the parent uses `asyncio.gather(..., return_exceptions=True)` and ends in `finally` → the `finally` runs when gather returns, which is when *all* tasks have settled *or* when the first unhandled exception propagates. With `return_exceptions=True` it waits; without it, it does not. The `return_exceptions` flag is the difference between a valid and invalid completion proof, and it is invisible in the emitted span. A downstream verifier cannot distinguish these cases from the trace. Therefore the runtime must encode the distinction at emission time: either guarantee causal ordering, or emit `gen_ai.tool.call.incomplete=true` and `status.code=ERROR` on any parent whose children have not all closed at end time. The latter requires the runtime to track open children per span — a small map from parent `span_id` to open-child count, decremented on child end, checked before parent end. ## Operational Effect When the invariant is violated and undetected: - **Handoff warrants propagate on false completion.** The auditor advances the baton on a `status.code=OK` that does not mean what it says. Downstream agents inherit a causal claim that is false. - **Retry logic double-executes side effects.** A cost governor seeing a 412ms `gen_ai.tool.call` under a 500ms budget will not retry; a verifier seeing the same span and then observing a stale file will retry, producing two writes where one was intended. - **Replay diverges from production.** A replay harness re-running the trace sees the parent close at 412ms and cannot reconstruct that the write was still in flight — the replay's timing model is structurally wrong. - **Cost attribution undercounts.** If the parent span is the billing unit (as `gen_ai.usage.*` attributes on the parent imply), the 1.475s of write latency is attributed to no span and vanishes from the ledger. The guardrail is a **close-time invariant check**: before ending any `gen_ai.agent.invoke` or `gen_ai.tool.call` span, assert that the runtime's open-child counter for that span is zero. If not, either defer the close (preferred) or emit the span with `status.code=ERROR` and an explicit `gen_ai.tool.call.incomplete=true` attribute so no downstream consumer can mistake it for a completion proof. This is cheap — one counter per span — and it converts a silent telemetry lie into a loud, machine-detectable one. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Optional class PrematureSpanCloseError(RuntimeError): """Raised when a GenAI parent span is ended while child spans remain open.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation_name: str # e.g. "invoke_agent", "execute_tool" status_code: str = "UNSET" end_time_ns: Optional[int] = None attributes: Dict[str, object] = field(default_factory=dict) class SpanRegistry: """Tracks open children per parent to enforce the close-time invariant.""" def __init__(self) -> None: self._open_children: Dict[str, int] = {} self._spans: Dict[str, GenAISpan] = {} def start(self, span: GenAISpan) -> None: self._spans[span.span_id] = span self._open_children.setdefault(span.span_id, 0) if span.parent_id is not None: self._open_children[span.parent_id] = ( self._open_children.get(span.parent_id, 0) + 1 ) def end(self, span_id: str, end_time_ns: int) -> None: span = self._spans.get(span_id) if span is None: raise PrematureSpanCloseError(f"unknown span_id={span_id}") open_kids = self._open_children.get(span_id, 0) if span.operation_name in ("invoke_agent", "execute_tool") and open_kids > 0: # Do NOT silently close: this would forge a completion proof. raise PrematureSpanCloseError( f"refusing to close {span.operation_name} span_id={span_id}: " f"{open_kids} child span(s) still open; " f"emitting incomplete=true instead" ) span.end_time_ns = end_time_ns span.status_code = "OK" if span.parent_id is not None: self._open_children[span.parent_id] = max( 0, self._open_children.get(span.parent_id, 0) - 1 ) def end_or_mark_incomplete(self, span_id: str, end_time_ns: int) -> GenAISpan: """Fallback path: close anyway but poison the span so verifiers reject it.""" span = self._spans[span_id] try: self.end(span_id, end_time_ns) return span except PrematureSpanCloseError: span.end_time_ns = end_time_ns span.status_code = "ERROR" span.attributes["gen_ai.tool.call.incomplete"] = True span.attributes["gen_ai.close.open_children"] = self._open_children.get( span_id, 0 ) if span.parent_id is not None: self._open_children[span.parent_id] = max( 0, self._open_children.get(span.parent_id, 0) - 1 ) return span def verify_trace_ordering(registry: SpanRegistry) -> None: """Post-hoc check: no child may end after its parent.""" by_id = registry._spans for span in by_id.values(): if span.parent_id is None or span.end_time_ns is None: continue parent = by_id.get(span.parent_id) if parent is None or parent.end_time_ns is None: continue if span.end_time_ns > parent.end_time_ns: raise PrematureSpanCloseError( f"temporal inversion: child {span.span_id} ends at " f"{span.end_time_ns} > parent {parent.span_id} at " f"{parent.end_time_ns}; parent status was {parent.status_code}" ) ```