# When must an instance refuse to close an OpenTelemetry GenAI `execute_tool` span: the orphaned-child invariant across mid-tool checkpoint/resume **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, span parent/child linkage) and that supports mid-tool checkpoint/resume, replay, or process restart between the tool-call span's start and end. Does not apply to stateless single-shot inference where the tool span is created and closed inside one uninterruptible call frame. ## Core Distinction A `gen_ai.tool` span is *not* a log line. It is a **stateful, parent-linked object with a mandatory single close event**, and the OpenTelemetry GenAI conventions bind two independent lifecycles to it: the **execution lifecycle** (the tool actually ran and returned) and the **serialization lifecycle** (the span was started on a tracer and must be ended exactly once on the same tracer/provider that started it). The non-obvious boundary is that these two lifecycles can *diverge* under checkpoint/resume, and the convention gives you no field to express "this span was started by a dead process." Most runtimes resolve this divergence by re-emitting a fresh child span on resume, which silently **double-counts token usage and orphans the original child**, or by force-closing a span they did not start, which **corrupts the trace's structural invariant** (a child span whose `end_time_unix_nano` precedes its parent's `start_time_unix_nano`, or a child with no resolvable parent at all). The invariant that must hold: **every emitted `gen_ai.tool` span must have exactly one `end` event, emitted by the tracer provider that emitted its `start`, with `end_time >= start_time`, and a parent span that is still open or closed-after-it.** Checkpoint/resume is the exact condition that breaks this invariant, because the resume process holds the *span context* (a serializable `SpanContext` tuple: trace_id, span_id, flags) but *not the span object* — and `SpanContext` is not a handle. ## What Was Observed A multi-step agent executing a long-running tool (`gen_ai.tool.name = "fetch_and_index"`, a 40-second retrieval-and-embedding call) checkpointed its agent state at token-budget exhaustion mid-tool. The checkpoint serialized: the agent's message history, the pending tool call arguments, and — critically — the `trace_id`/`span_id` of the in-flight `execute_tool` span, because the runtime wanted "trace continuity across resume." The process was killed by the orchestrator's 30-second wall-clock limit. On resume, the new process: 1. Reconstructed the pending tool call and re-executed it (the tool was not idempotent; it re-embedded and re-indexed, producing a second real side effect). 2. Called `tracer.start_span("execute_tool", context=extracted_context)` — which, because the extracted context carried the *old* parent span_id, created a **new child span with the old span_id as parent**, but the old parent span object no longer existed in any live tracer provider. The resulting span was emitted with `parent_span_id = ` and no corresponding parent span in the batch. 3. Emitted `gen_ai.usage.input_tokens = 1840, output_tokens = 312` on the *new* span, while the original span (started before the kill) was flushed by the dying process as an *unended* span with `status = UNSET` and **zero recorded usage**. Downstream, the trace backend received: one orphaned parent span_id with no parent record, one child span whose parent is unresolvable, and a **token total that undercounted the first tool invocation's usage to zero and double-counted the second**. The cost-attribution pipeline, which sums `gen_ai.usage.*` per trace, reported 1,840 input tokens for an operation that actually consumed ~3,700. The auditor agent that replayed the trace for verification flagged a *consistency violation* — not because the numbers were wrong in isolation, but because the sum of child token usage exceeded the parent `gen_ai.operation.name = "invoke_agent"` span's recorded `gen_ai.usage.input_tokens`, a monotonicity violation the auditor's invariant checker caught. The failure trace, precisely: ``` T0 parent invoke_agent span S_p started (input_tokens=0, will be set at close) T1 child execute_tool span S_c1 started, parent=S_p.span_id T2 tool runs 40s; checkpoint written: {trace_id, S_c1.span_id, tool_args} T3 wall-clock kill. S_c1 never ended. S_p never ended. T4 dying process flushes S_c1 with status=UNSET, usage absent. S_p flushed UNSET. T5 resume: new tracer provider P2. extracts (trace_id, S_c1.span_id) as parent ctx. T6 P2.start_span("execute_tool", parent=S_c1.span_id) -> S_c2, parent_span_id=S_c1.span_id T7 tool re-runs (side effect duplicated). S_c2 records usage=1840/312. T8 S_c2 ends. S_c1 is referenced as parent but was never emitted by P2 and is already closed by P1. => orphan: S_c2.parent_span_id -> S_c1, but S_c1's end (T4) < S_c2's start (T6) AND S_c1 was emitted by a different provider. => token sum: 0 (S_c1) + 1840 (S_c2) = 1840, actual 3700. ``` The key mechanical point: **`SpanContext` is a value, not a capability.** Serializing it into a checkpoint and re-injecting it on resume creates a *reference* to a span that the new provider cannot end, cannot amend, and cannot prove it owns. The OTel SDK's `Span` object carries the only legal `end()` handle, and that handle does not survive process death. There is no `gen_ai.*` attribute defined to record "this span was resumed from a checkpoint and its predecessor is abandoned." ## Condition of Validity The failure is *bounded* — meaning it does not occur, and you must not apply the guardrail — under any one of these conditions: - **The tool span's start and end are within a single uninterruptible call frame** (no checkpoint boundary between them). Then the serialization lifecycle and execution lifecycle are coextensive and the invariant is trivially satisfied. - **The runtime checkpoints only *before* starting a tool span or *after* ending it**, never in the interval `(start, end)`. This is the only safe checkpoint placement, and it must be enforced structurally, not by convention. - **The tool is idempotent and the runtime explicitly re-emits a *new root* span on resume** (parent = the resumed `invoke_agent` span, not the dead tool span), accepting that the pre-kill tool span is emitted as `status = ERROR` with attribute `gen_ai.tool.call.id` matching, and that its usage is recorded as *unknown* rather than zero. This is a deliberate, documented divergence, not a silent one. The failure is *in scope* — and the guardrail must fire — whenever a checkpoint is written in the open interval `(tool_span.start, tool_span.end)` **and** the resume path re-injects the dead span's `SpanContext` as a parent. The distinguishing test is not "was there a checkpoint" but "**does the resume process hold a `SpanContext` for a span whose `end()` was never called by any live provider?**" That predicate is decidable at resume time: you have the span_id, and you can query whether *this* provider emitted it (it did not — providers are process-scoped). ## Decision Boundary The decision boundary is a single predicate evaluated at resume, before any span is started: ``` orphaned = (checkpoint contains in_flight_tool_span_id) AND (in_flight_tool_span_id not in current_provider.emitted_span_ids) AND (checkpoint.tool_span_end_was_recorded == False) ``` If `orphaned` is true, the instance **must not**: 1. Re-inject the dead `SpanContext` as a parent for the re-executed tool. Doing so manufactures an orphan child and a temporal inversion (`child.start > parent.end`). 2. Emit `gen_ai.usage.*` on a *new* span while leaving the dead span's usage at zero. Zero is a *value*, not an *absence*; the convention has no "unknown" sentinel for usage, so writing zero is a lie that the cost pipeline will sum. It **must** instead: 1. Emit a **synthetic closure record** for the orphaned span_id: a span with the *original* span_id, `status = ERROR`, `status.message = "orphaned by checkpoint at token-budget exhaustion"`, and **explicitly omit** usage fields (absence, not zero) so downstream aggregation treats it as unknown. 2. Start the re-executed tool span as a **sibling** of the orphan (parent = the same `invoke_agent` parent), not a child of it, and carry `gen_ai.tool.call.id` linking the two so the auditor can reconcile. 3. Reject the resume if the runtime *cannot* prove it has not already emitted a span with that id under a different provider — because emitting a second span with the same span_id on a different provider is a **trace-identity collision**, worse than an orphan. The boundary is sharp: **you may resume the tool; you may not resume the span.** The execution lifecycle is recoverable from a checkpoint; the serialization lifecycle is not, because the `end()` handle is process-local and non-serializable. Any design that treats the span as recoverable has conflated the two. ## Operational Effect Without this guardrail, three silent corruptions compound: - **Cost undercount.** Orphaned spans contribute zero to `gen_ai.usage.*` sums; the re-executed span contributes full usage. Traces with N resume cycles undercount by the sum of pre-kill invocations. In the observed case, 50% of input tokens vanished from attribution. - **Trace-graph invalidity.** Auditors that enforce "child.end >= parent.start" and "every parent_span_id resolves" will reject the trace. A verification-replay agent that trusts the trace as ground truth will conclude the tool ran once, when it ran twice. - **Side-effect divergence.** Because the tool is re-executed on resume, the *actual* world state (indexed documents, charged API calls) diverges from the *traced* state (one span). The trace is the agent's only memory of what it did; a trace that says "one tool call" while two occurred is a memory that lies, and the agent's subsequent reasoning will be built on it. The architectural invariant to enforce: **a checkpoint may not be written in the open interval of a tool span, and a `SpanContext` may never be used as a parent unless the current provider emitted it.** Encode both as hard preconditions — the first on the checkpoint writer, the second on the span starter — so that the failure is converted from a silent trace corruption into a loud, resumable error. ```python class OrphanedToolSpanError(RuntimeError): """Raised when a resumed agent attempts to re-parent a tool span whose end() was never called by a live tracer provider. Re-parenting would manufacture an orphan child and a temporal inversion in the trace graph.""" pass class TokenAccountingViolationError(RuntimeError): """Raised when a resumed tool span would record gen_ai.usage.* while the orphaned predecessor's usage is written as zero (a value) instead of absent (unknown), causing silent cost undercount.""" pass def resume_tool_span(checkpoint: dict, provider) -> str: """Decide whether the in-flight tool span from a checkpoint may be re-parented. Returns the parent span_id to use for the re-executed tool span, or raises if the invariant cannot be satisfied.""" in_flight = checkpoint.get("in_flight_tool_span_id") end_recorded = checkpoint.get("tool_span_end_was_recorded", False) if in_flight is None: # No tool was open at checkpoint time; safe to start fresh. return checkpoint["invoke_agent_span_id"] if end_recorded: # Span closed before checkpoint; it is a legal, closed ancestor. return in_flight # Open interval at checkpoint. The span object is gone; only its # SpanContext survives. The current provider never emitted it. if in_flight not in provider.emitted_span_ids: # Invariant: do NOT re-parent. Emit a synthetic closure for the # orphan, and start the re-executed tool as a sibling. if checkpoint.get("usage_written_as_zero"): raise TokenAccountingViolationError( f"orphaned span {in_flight} has usage=0; " "must be absent (unknown), not zero, to avoid undercount" ) provider.emit_synthetic_closure( span_id=in_flight, status="ERROR", message="orphaned by checkpoint mid-tool; end() never called", omit_usage=True, ) # Sibling, not child: same invoke_agent parent as the orphan. return checkpoint["invoke_agent_span_id"] # The provider claims to have emitted this span_id. On a fresh process # this is impossible and indicates a trace-identity collision. raise OrphanedToolSpanError( f"span_id {in_flight} already emitted by provider " f"{provider.id}; refusing to resume span across providers" ) ```