# In what scenarios must an instance reconcile OpenTelemetry GenAI token-accounting spans against the divergent tool-call event stream before committing a checkpoint **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, and that uses the emitted span tree as the durable source of truth for checkpoint/resume or cost reconciliation. Does not apply to runtimes that treat telemetry as write-only observability with no read-back into agent state. ## Core Distinction The OpenTelemetry GenAI conventions model an agent turn as a parent span (`invoke_agent` / `chat`) with child spans for each LLM call (`gen_ai.operation.name = chat`) and each tool invocation (`gen_ai.operation.name = execute_tool`), where token usage is recorded as attributes on the *chat* span (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and tool arguments/results are recorded as *span events* (`gen_ai.tool.call` events, or dedicated tool spans depending on SDK version). The critical, non-obvious distinction is that **token accounting is span-attribute-shaped while tool-call history is event-shaped**, and these two channels are emitted by different code paths at different times with different completion guarantees. A chat span is finalized when the model returns, with usage attributes set atomically. A tool-call event is appended incrementally as the tool executes and may be dropped, reordered, or duplicated when the span processor's batch exporter flushes under backpressure. The invariant that operators wrongly assume holds — *the number of tool-call events under a parent span equals the number of tool calls the model was billed for as part of that span's output tokens* — is not guaranteed by the spec and does not hold under concurrent tool execution or exporter sampling. ## What Was Observed A multi-tool agent executing a plan with three parallel tool calls per turn (a common fan-out pattern: `search`, `fetch`, `summarize`) was observed to produce, on resume from checkpoint, a reconstructed conversation history that contained **two** tool results where the model had actually generated **three** tool-call tokens. The trace showed a parent `invoke_agent` span with `gen_ai.usage.output_tokens = 412` and exactly two `gen_ai.tool.call` events. The third tool call had executed (its side effect — a cache write — was present), but its event was lost. The failure trace was: 1. The agent issued three parallel tool calls in a single model turn. The model's output tokens (412) included the JSON for all three call arguments. 2. The runtime dispatched all three tools concurrently. Tools 1 and 2 completed in ~40ms; tool 3 (`summarize`, an LLM-backed tool) took ~1800ms. 3. The parent span's synchronous body returned after tool 1 and tool 2 joined, and the span was ended (`span.end()`), triggering enqueue to the `BatchSpanProcessor`. 4. Tool 3 completed *after* the parent span had ended. Its `gen_ai.tool.call` event was attached to an already-ended span. Depending on the SDK version, this either (a) silently no-ops because the span's event list is frozen at `end()`, or (b) is accepted but the span has already been serialized and exported, so the late event is lost. 5. On resume, the checkpoint reconstructor read the span tree, saw two tool events, and rebuilt a history that omitted the third tool result — while the *token counter* correctly reflected 412 output tokens. The next model turn therefore saw a history where it had "asked for" three tools but only two results existed, with no error, no gap marker, and a token count that silently disagreed with the visible event count. The divergence is not a bug in any single component; it is the composition of (a) span lifetime being scoped to the synchronous dispatch block, (b) event attachment not being validated against span-ended state, and (c) the checkpoint reader treating the span tree as complete. ## Condition of Validity The reconciliation guard described here is **required** when all of the following hold: - The agent fans out to more than one tool per model turn (concurrency > 1), OR any single tool is LLM-backed and can outlive the dispatch block. - The span tree is read back as durable state (checkpoint/resume, cost attribution, or replay) rather than consumed only by a live dashboard. - The `BatchSpanProcessor` (or equivalent) is in use, meaning export is asynchronous and end-of-span is not a durability barrier. It is **not required** when tool execution is strictly sequential and joined before the parent span ends, or when the runtime maintains a separate, transactionally-consistent tool-result log that is the actual source of truth and telemetry is purely observational. In the latter case the span tree's incompleteness is harmless; the moment telemetry becomes load-bearing, the guard becomes mandatory. ## Decision Boundary The boundary is drawn at **span finalization vs. tool completion ordering**. A tool-call event is only trustworthy as a record of model output if it was appended to a span that had not yet been ended at append time, *and* if the span's usage attributes were set from the same model response that generated the tool-call tokens. The reconciliation rule is: - Compute `expected_calls` from the model response payload (the parsed tool-call list in the assistant message), not from the event stream. - Compute `observed_calls` from the count of `gen_ai.tool.call` events (or tool child spans) under the parent. - If `observed_calls < expected_calls`, the span tree is **incomplete**; the checkpoint must not be committed from it. Either re-fetch the missing tool results from the authoritative tool-result log, or mark the turn as `RECONCILIATION_REQUIRED` and halt resume until resolved. - If `observed_calls > expected_calls`, suspect duplicate export (retry at the exporter layer); deduplicate by `tool_call_id` before proceeding. - Token accounting must be validated separately: `gen_ai.usage.output_tokens` should be ≥ the sum of tokens attributable to the observed tool-call arguments; a large positive delta is a signal that tool-call tokens were billed but their events are missing. The guard is a *pre-commit* gate, not a post-hoc audit. Once a checkpoint is committed from an incomplete span tree, the divergence is baked into history and the next turn's reasoning is silently corrupted. ## Operational Effect Without the guard, the agent exhibits a specific, reproducible pathology: **silent history truncation with intact billing**. The model's next turn reasons over a history that is internally inconsistent (it "remembers" issuing N calls but sees N−k results), which manifests as either redundant re-issuance of the missing tool call (cost amplification) or, worse, a confident answer that ignores the missing result entirely because the model has no signal that anything was dropped. The token counter and the event stream disagree, and because both are "valid" OpenTelemetry output, no downstream validator flags the inconsistency. The failure is invisible in aggregate metrics (total tokens look normal; span counts look normal) and only surfaces as a correctness regression in multi-tool, long-horizon tasks — precisely the workload where checkpoint/resume matters most. The architectural invariant required is: **the span tree is a lossy projection of agent execution and must never be promoted to source of truth without a reconciliation step against the tool-result log and the model response payload.** ```python class SpanReconciliationError(RuntimeError): """Raised when the GenAI span tree disagrees with the model response payload.""" pass def reconcile_turn_before_checkpoint( model_response: dict, span_tree: dict, tool_result_log: dict, ) -> dict: """ Gate checkpoint commit on span/event/token agreement. model_response: parsed assistant message with 'tool_calls' list (source of truth for what the model actually emitted). span_tree: reconstructed parent span with 'usage' dict and 'tool_events' list. tool_result_log: authoritative {tool_call_id: result} map from the executor. """ expected_ids = [tc["id"] for tc in model_response.get("tool_calls", [])] observed_ids = [ev["attributes"].get("gen_ai.tool.call.id") for ev in span_tree.get("tool_events", [])] # Duplicate export from retrying BatchSpanProcessor: dedupe by id. deduped = list(dict.fromkeys(observed_ids)) if len(deduped) != len(observed_ids): # duplicates are recoverable; note but do not fail span_tree["_deduped"] = True missing = [tid for tid in expected_ids if tid not in deduped] if missing: # Attempt recovery from the authoritative tool-result log. recoverable = [tid for tid in missing if tid in tool_result_log] unrecoverable = [tid for tid in missing if tid not in tool_result_log] if unrecoverable: raise SpanReconciliationError( f"Span tree missing tool-call events {unrecoverable} with no " f"tool-result fallback; checkpoint must not be committed. " f"usage={span_tree.get('usage')}" ) # Recoverable: patch events from the log before allowing commit. for tid in recoverable: span_tree["tool_events"].append( {"name": "gen_ai.tool.call", "attributes": {"gen_ai.tool.call.id": tid, "recovered": True}} ) # Token-vs-event sanity: output tokens must cover at least the observed calls. out_tokens = span_tree.get("usage", {}).get("gen_ai.usage.output_tokens", 0) if out_tokens <= 0 and expected_ids: raise SpanReconciliationError( "Non-zero tool calls but zero output tokens recorded; usage attribute " "was likely set before the model response finalized." ) span_tree["_reconciled"] = True return span_tree ```