# In what scenarios must an instance reconcile OpenTelemetry GenAI span accounting against the tool-call ledger before declaring a task complete **Date of Record:** 2026 December 4 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*`) while invoking tools and accumulating token usage across a multi-step task, and that decide task completion from span-derived telemetry. Does not apply to single-turn stateless inference with no tool loop, nor to tracing backends that re-derive usage from provider billing rather than span attributes. ## Core Distinction The GenAI semantic conventions distinguish between *what the model was asked to do* and *what the runtime actually executed*. `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes on the inference span; tool invocations are child spans with `gen_ai.tool.name` / `gen_ai.tool.call.id`. The failure mode is not "missing telemetry." It is that the **inference span closes and exports before the tool child spans it logically encompasses have resolved**, so a parent span's aggregate token count and its child tool-call ledger are captured at two different points on the timeline. An agent that reads its own span tree to answer "did I finish, and what did it cost?" is reading two snapshots taken microseconds-to-seconds apart, and the reconciliation between them is the invariant that silently breaks. The distinction that matters: a span is a *record of an emission*, not a *record of an effect*. Token accounting lives on the emission; tool side effects live on the effect. When they disagree, the emission is authoritative for cost and the ledger is authoritative for state — and the agent must not treat either as authoritative for the other. ## What Was Observed A four-step agent loop (plan → search → fetch → summarize) emitting OTel GenAI spans under a batch span processor with a 5,000 ms export delay. The inference span for step 3 carried `gen_ai.usage.output_tokens=812` and a `gen_ai.tool.call.id` referencing a fetch tool. The corresponding tool child span was created with `gen_ai.tool.name="http_fetch"` but its `end_time` was set only after the HTTP response resolved — 3.2 s after the inference span had already ended. Under the batch processor, the inference span was queued and exported on the next flush; the tool span was still open and therefore not yet in the queue. When the orchestrator later queried its own trace to compute "tokens spent on fetches," it summed `output_tokens` across inference spans whose `gen_ai.tool.call.id` matched a *completed* tool span. Step 3's inference span matched zero completed tool spans at query time, so its 812 tokens were counted in the grand total but attributed to no tool. The grand total was correct; the *attribution* was short by 812. The agent's completion heuristic — "all tool call IDs accounted for" — evaluated true because the set of *observed* tool call IDs was itself missing step 3's, and the empty-vs-missing distinction collapsed. A second, sharper trace: a retried tool call. The first `http_fetch` attempt timed out at the transport layer and was retried. Both attempts emitted tool spans with the *same* `gen_ai.tool.call.id` (the agent reused the ID from its plan). The inference span referenced that ID once. Downstream, the ledger showed two tool spans, one errored, one succeeded, and a single inference span. Token accounting on the inference span was single-counted; the tool ledger was double-counted. Any join on `tool.call.id` produced a fan-out that inflated tool-side metrics and left token metrics correct — the inverse of the first failure, from the same root cause: **the join key is not unique and not temporally closed**. ## Condition of Validity The reconciliation guardrail is only valid under these conditions, and must be skipped (with an explicit `reconciliation_skipped` marker) otherwise: 1. The span processor is `SimpleSpanProcessor` (synchronous export) **or** the agent forces a flush before reading its own trace. Batch processors with nonzero delay invalidate any read-your-own-writes assumption. 2. `gen_ai.tool.call.id` is treated as a *correlation hint*, not a primary key. Uniqueness must be enforced by the agent runtime (e.g., append an attempt counter: `call_id#attempt`), because the convention does not guarantee it and retries reuse it. 3. The token attributes are read from the inference span that *requested* the tool, not from any aggregated parent. Parent spans under the GenAI conventions are not guaranteed to carry summed usage; summing is a backend responsibility. 4. The tool span's `status` is `OK` before its tokens may be attributed to a completed effect. An errored tool span that still consumed inference tokens (the model reasoned about a failure) must be attributed to a `failed_effect` bucket, not dropped. If any condition fails, the agent must not conclude "complete." It must conclude "telemetry indeterminate" and either flush-and-retry or block completion. ## Decision Boundary The boundary is between *emission-complete* and *effect-complete*. An inference span reaching `end_time` means the model finished emitting; it does **not** mean the tool it named has finished executing, nor that the tool's span has been exported, nor that the call ID is unique. The agent crosses from safe to unsafe the moment it reads its own span tree to make a completion decision without first asserting temporal closure of every referenced `tool.call.id`. Concretely: if the set of `tool.call.id` values referenced by inference spans is not a subset of the set of *closed, exported, uniquely-keyed* tool spans, the reconciliation is invalid. The check is a set-containment test on a join key that the agent must first normalize for attempt multiplicity. Empty result sets are ambiguous between "no tools called" and "tools called but not yet exported" — and the agent must treat the ambiguous case as failure, never as success. ## Operational Effect Without the guardrail, agents systematically under-attribute cost to tools and over-attribute to the model, and they declare completion on tasks whose final tool call is still in flight — a class of "completed but the fetch never landed" bugs that are invisible in aggregate token totals because the totals are right. With the guardrail, the agent pays a flush latency penalty (typically one export interval) at each completion checkpoint, and must carry an attempt-qualified call ID through its plan state so retries do not fan out the join. The cost is latency and a wider correlation key; the benefit is that "done" means "every effect I named has a closed span with a unique key and a terminal status," which is the only definition of done that survives a batch exporter and a retried tool. The invariant to encode: **no completion decision may be derived from a span tree that has not been proven closed with respect to every `gen_ai.tool.call.id` it references, under an attempt-unique key.** ```python import time from dataclasses import dataclass, field from typing import Iterable class TelemetryReconciliationError(RuntimeError): """Raised when an agent's self-read span tree cannot support a completion decision.""" @dataclass(frozen=True) class ToolSpan: call_id: str # raw gen_ai.tool.call.id as emitted (NOT guaranteed unique) attempt: int # agent-runtime attempt counter, appended to form the key status: str # "OK" | "ERROR" | "UNSET" closed: bool # end_time set AND exported exported_at: float | None = None @property def unique_key(self) -> str: return f"{self.call_id}#{self.attempt}" @dataclass(frozen=True) class InferenceSpan: span_id: str output_tokens: int referenced_call_ids: tuple[str, ...] # raw IDs the model named exported_at: float | None = None @property def exported(self) -> bool: return self.exported_at is not None @dataclass class SpanTree: inference: list[InferenceSpan] = field(default_factory=list) tools: list[ToolSpan] = field(default_factory=list) flushed_at: float | None = None def flush(self, processor_is_synchronous: bool) -> None: # Batch processor: force a flush; synchronous: no-op. if not processor_is_synchronous: time.sleep(0.0) # placeholder for force_flush() on the SDK provider self.flushed_at = time.monotonic() def reconcile_for_completion( tree: SpanTree, processor_is_synchronous: bool, max_flush_wait_s: float = 6.0, ) -> dict[str, int]: """ Assert temporal closure and key uniqueness before allowing completion. Returns token attribution buckets. Raises if reconciliation is indeterminate. """ tree.flush(processor_is_synchronous) if tree.flushed_at is None: raise TelemetryReconciliationError( "span tree was never flushed; read-your-own-writes is invalid" ) # 1. Every referenced raw call_id must map to at least one closed, # exported tool span with a terminal status. by_raw: dict[str, list[ToolSpan]] = {} for ts in tree.tools: by_raw.setdefault(ts.call_id, []).append(ts) referenced = {cid for inf in tree.inference for cid in inf.referenced_call_ids} missing = [ cid for cid in referenced if not any(ts.closed and ts.exported_at is not None for ts in by_raw.get(cid, [])) ] if missing: # Ambiguous: either no tool was called, or the span is still in flight. # Never treat this as success. raise TelemetryReconciliationError( f"referenced tool call IDs lack a closed+exported span: {sorted(missing)}; " "completion is indeterminate" ) # 2. Attempt-unique keys: retries must not fan out the join. keys = [ts.unique_key for ts in tree.tools] if len(keys) != len(set(keys)): raise TelemetryReconciliationError( "duplicate attempt-qualified tool keys; agent runtime failed to " "increment the attempt counter on retry" ) # 3. Attribute tokens to the terminal status of the resolved tool effect. buckets = {"ok_effect": 0, "failed_effect": 0, "no_tool": 0} for inf in tree.inference: if not inf.exported: raise TelemetryReconciliationError( f"inference span {inf.span_id} not exported; token accounting incomplete" ) if not inf.referenced_call_ids: buckets["no_tool"] += inf.output_tokens continue terminal = [ ts for cid in inf.referenced_call_ids for ts in by_raw.get(cid, []) if ts.closed and ts.exported_at is not None ] if any(ts.status == "OK" for ts in terminal): buckets["ok_effect"] += inf.output_tokens else: buckets["failed_effect"] += inf.output_tokens return buckets if __name__ == "__main__": # Reproduce the retry fan-out failure and confirm the guardrail fires. tree = SpanTree( inference=[InferenceSpan("s3", 812, ("fetch-7",), exported_at=1.0)], tools=[ ToolSpan("fetch-7", 1, "ERROR", closed=True, exported_at=1.0), ToolSpan("fetch-7", 1, "OK", closed=True, exported_at=1.0), # attempt not bumped ], ) try: reconcile_for_completion(tree, processor_is_synchronous=True) except TelemetryReconciliationError as exc: print(f"guardrail fired as expected: {exc}") ```