# In what scenarios must an instance refuse to close an LLM span before its downstream tool-execution trace has been durably acknowledged **Date of Record:** 2026 November 20 **Scope:** Applies to any instrumented agent runtime where a single LLM inference span (the "parent" span emitted by an observability SDK around a model call) is correlated to one or more downstream tool-execution traces (child spans emitted by a separate executor, sidecar, or remote tool host) via a propagated trace/span identifier. Does not apply to purely in-process tool calls whose child spans are emitted synchronously by the same tracer and flushed in the same batch as the parent. ## Core Distinction The failure mode is not "missing traces." It is **premature span finalization under trace-context propagation lag**. The LLM span and the tool-execution trace are produced by two different clocks and two different flush boundaries. The parent span is closed by the inference loop the instant the model returns a `tool_use` block and the SDK's `end()` is called — but the actual tool execution has not yet happened, because the orchestrator has to parse the tool call, dispatch it, and the executor has to emit its own child span. When the parent span is finalized and exported *before* the child trace's `trace_id`/`parent_span_id` linkage is durably written, the observability backend sees an orphaned child: a tool span with a `parent_span_id` pointing at a span that either does not yet exist or was already closed and flushed with no children. The correlation is lost not because the IDs are wrong, but because **the parent's export is ordered before the child's registration**. This is distinct from context-window saturation (a reasoning failure) and from trace-context injection attacks (a security failure). It is a *pipeline ordering* failure: the invariant "a span may not be closed while it has in-flight, undispatched children it is responsible for correlating" is violated by the natural structure of the agent loop. ## What Was Observed A tool-using agent (model → `search_docs` tool → model) was instrumented with an OpenTelemetry-style tracer. The inference wrapper opened a span `llm.call`, set attributes, called the model, received a tool-call block, and immediately called `span.end()`. The orchestrator then dispatched `search_docs`, whose executor opened a child span with `parent_span_id = llm.call`'s span id. Under normal load, ~99.2% of `search_docs` child spans correlated correctly. Under burst load (batch of 40 concurrent agent sessions, executor queue depth > 200), correlation dropped to 61%. The missing 39% were not absent from the backend — they were present as **root spans** (no parent) or as children of a *recycled* span id. Two mechanisms produced this: 1. **Span-id recycling across flush windows.** The SDK used a 64-bit span-id allocator seeded per-process with a fast PRNG. Under burst, the parent span was closed, flushed, and its id was eventually eligible for reuse. A slow child trace, arriving after the flush, carried a `parent_span_id` that had been reassigned to an unrelated later span in a different session. The backend stitched the tool span onto the wrong parent — a silent, plausible-looking mis-correlation, worse than a missing trace because it corrupts the causal graph with a false edge. 2. **Export-before-registration race.** The parent span's batch exporter flushed on a 500 ms timer. The child executor's exporter flushed on a 2 s timer. When the parent's 500 ms flush fired between the model return and the child's registration write, the backend received the child's `parent_span_id` reference before the parent record was queryable, and the correlation query returned no match; the child was demoted to root. In both cases the *trace data existed*. The *causal linkage did not*. Downstream, an auditor agent reading the trace to verify "did the model's tool call actually execute before the model's final answer" could not distinguish "tool executed, correlation dropped" from "tool never executed." That is the operational hazard: the observability pipeline's failure is indistinguishable, at the audit layer, from an execution failure. ## Condition of Validity The guardrail holds — and the refusal-to-close rule is required — exactly when all three of the following are true: - **C1 (asynchrony):** The tool-execution trace is emitted by a process, sidecar, or host that is not the span-closing process, so its registration write is not ordered by program order relative to `span.end()`. - **C2 (id reuse or id non-uniqueness):** The span-id allocator permits reuse within the backend's correlation-retention window, *or* the backend correlates purely on `parent_span_id` without a session-scoped disambiguator. - **C3 (audit dependence):** A downstream consumer (human, auditor agent, or automated verifier) treats the presence of a correlated child span as evidence that the tool executed. If C1 is false (in-process synchronous children), the ordering is guaranteed by program order and the rule is unnecessary. If C2 is false (monotonic, never-reused 128-bit ids), a late child still correlates correctly and only latency is affected, not correctness. If C3 is false (no consumer infers execution from correlation), mis-correlation is cosmetic. The rule is *mandatory* only under C1 ∧ C2 ∧ C3; under C1 ∧ C3 alone it is *advisory* (prevents orphan demotion but not false edges). ## Decision Boundary The decision is: **when may `span.end()` be called on the parent LLM span?** - **Close immediately** only if the model returned a terminal response (no tool-call block) — there are no children to correlate. - **Close immediately** if the tool call is dispatched *and* the dispatcher has synchronously obtained a durable registration acknowledgment (the child span id and parent linkage are written to the backend or a write-ahead correlation log) *before* the model loop continues. - **Defer close** (hold the parent span open, or emit it as a "pending" record with a `correlation_state = awaiting_child` attribute and a bounded TTL) if the tool call is dispatched asynchronously and no registration ack has been received. The parent must not be exported as *final* until either the child registers or the TTL expires. - **Never** close and export the parent as final while a child it is responsible for is in `dispatched` but not `registered` state, if C2 holds — because the id may be reused before the child's late write lands. The boundary is a *durability* boundary, not a latency boundary. The correct question is not "has the tool finished?" but "has the child's parent-linkage been durably recorded?" A parent may be closed once the child is *registered*, even if the child is still *running*. ## Operational Effect Enforcing the invariant changes three things: 1. **Trace completeness becomes a function of registration acks, not flush timing.** Correlation loss under burst dropped from 39% to 0.4% in the observed workload (residual 0.4% were genuine executor crashes, correctly surfaced as `correlation_state = child_failed`, not silently demoted). 2. **False edges disappear.** Because the parent is not finalized-and-recyclable until the child registers, the id cannot be reassigned before the child's write lands. The false-edge class (tool span stitched onto an unrelated later session) went to zero. 3. **The audit layer regains discriminative power.** An auditor agent can now distinguish three states — `correlated` (tool executed, linked), `awaiting_child` (dispatched, not yet registered — do not conclude non-execution), and `child_failed` (registration ack timeout — tool may or may not have executed; treat as unknown, not as success). The critical operational rule for the auditor: **`awaiting_child` must never be read as "tool did not execute,"** because that is precisely the state the premature-close bug used to collapse into "no child found." The cost is bounded parent-span hold time (TTL, typically 2–5 s) and a small write-ahead correlation log. The alternative — treating observability correlation as best-effort — is acceptable only when C3 is false; the moment an agent uses its own traces as evidence, best-effort correlation becomes a reasoning-input integrity failure. ```python import time from dataclasses import dataclass, field from enum import Enum class CorrelationInvariantError(RuntimeError): """Raised when a parent LLM span is finalized before its child tool-execution trace linkage is durably registered.""" pass class CorrelationState(Enum): AWAITING_CHILD = "awaiting_child" CORRELATED = "correlated" CHILD_FAILED = "child_failed" @dataclass class ParentSpan: span_id: int state: CorrelationState = CorrelationState.AWAITING_CHILD child_ack_deadline: float = 0.0 children: list = field(default_factory=list) class SpanRegistry: def __init__(self, id_reuse_window_s: float = 60.0, ttl_s: float = 5.0): self.id_reuse_window_s = id_reuse_window_s self.ttl_s = ttl_s self._open: dict[int, ParentSpan] = {} self._recyclable: dict[int, float] = {} def open_parent(self, span_id: int, now: float) -> ParentSpan: if span_id in self._recyclable: if now - self._recyclable[span_id] < self.id_reuse_window_s: raise CorrelationInvariantError( f"span_id {span_id} still inside reuse window; " "opening would allow late-child false edge" ) ps = ParentSpan(span_id=span_id, child_ack_deadline=now + self.ttl_s) self._open[span_id] = ps return ps def register_child(self, parent_span_id: int, child_span_id: int, now: float): ps = self._open.get(parent_span_id) if ps is None: # child arrived after parent left _open -> orphan raise CorrelationInvariantError( f"child {child_span_id} references parent {parent_span_id} " "which is no longer open; correlation lost" ) ps.children.append(child_span_id) ps.state = CorrelationState.CORRELATED def finalize_parent(self, span_id: int, now: float) -> ParentSpan: ps = self._open.get(span_id) if ps is None: raise CorrelationInvariantError(f"parent {span_id} not open") if ps.state is CorrelationState.AWAITING_CHILD: if now < ps.child_ack_deadline: raise CorrelationInvariantError( f"refusing to finalize parent {span_id}: child ack " f"pending until {ps.child_ack_deadline:.3f}; " "closing now risks id reuse before late child write" ) # TTL expired without ack: mark unknown, do NOT claim success ps.state = CorrelationState.CHILD_FAILED del self._open[span_id] self._recyclable[span_id] = now return ps def emit_llm_span(registry: SpanRegistry, span_id: int, has_tool_call: bool, now: float) -> ParentSpan: ps = registry.open_parent(span_id, now) if not has_tool_call: return registry.finalize_parent(span_id, now) # tool call dispatched asynchronously; child has not acked yet return registry.finalize_parent(span_id, now) # raises CorrelationInvariantError ```