# How does an instance detect silent span loss when OpenTelemetry GenAI tool-call spans are sampled out mid-trajectory and the cost ledger diverges from the reasoning ledger **Date of Record:** 2026 December 4 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per reasoning step and per tool call using the `gen_ai.*` semantic conventions, with a parent `invoke_agent` (or equivalent trajectory) span, and that derive token/cost accounting from those spans. Does not apply to runtimes that emit a single monolithic span per task, nor to accounting derived from the provider's billing API rather than from trace data. ## Core Distinction There are two ledgers in an instrumented agent, and they are not the same ledger: 1. **The reasoning ledger** — the ordered sequence of `gen_ai.chat` and `gen_ai.execute_tool` spans that actually occurred, which is what you need to reconstruct *why* the agent did what it did. 2. **The cost ledger** — the sum of `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes across emitted spans, which is what you use for budget enforcement and chargeback. The failure mode is that **trace sampling and span export are independent of the reasoning loop**. A sampler decision, a batch-processor queue overflow, or a dropped span at export time removes a span from *both* ledgers simultaneously and silently. The reasoning ledger loses a step; the cost ledger loses its tokens. Neither raises. The parent span still reports `status = OK`, the trajectory still looks structurally valid (a chat span followed by another chat span with no intervening tool span reads as "the model just didn't call a tool"), and the token sum is simply lower than reality. The invariant that must hold — *for every trajectory, the sum of child usage attributes equals the usage attributed to the parent, and every tool invocation referenced in a tool-result message has a corresponding `execute_tool` span* — is never checked by the SDK. ## What Was Observed A 34-step research agent trajectory, parent span `invoke_agent`, `TraceId` fixed, `ParentSpanId` set on every child. The batch span processor was configured with `max_queue_size=2048`, `schedule_delay_millis=5000`, `max_export_batch_size=512`. Under a burst of parallel sub-agent fan-out, the queue saturated for roughly 1.8 seconds. The processor dropped spans per the OTel spec (drop-newest, log a counter, no exception to the caller). What landed in the backend: - Parent `invoke_agent` span: present, `status=OK`, `gen_ai.usage.input_tokens=41203`, `output_tokens=6118`. - Child `gen_ai.chat` spans: 31 of 34 present. - Child `gen_ai.execute_tool` spans: 19 of 27 present. - The 8 missing tool spans were exactly the ones emitted during the 1.8s saturation window — which, because the agent was fanning out, happened to be the highest-fan-out tool calls, i.e. the most token-expensive ones. Three distinct corruptions resulted, and they are worth separating because each defeats a different naive check: 1. **Cost undercount.** Summing child `input_tokens` gave 36,940 against the parent's 41,203 — a 10.3% gap. The gap is real spend that was never attributed to any tool call. Budget enforcement that reads child spans undercounts; budget enforcement that reads the parent span overcounts per-call attribution but gets the total right. If you enforce budget on the *parent*, you are correct; if you enforce per-tool-call caps on *children*, you silently allow overspend. 2. **Structural falsification.** In the persisted trace, several `gen_ai.chat` spans appear consecutively with no intervening `execute_tool` span, yet the *next* chat span's `gen_ai.prompt` (or the reconstructed message array) contains a `role: "tool"` message with a `tool_call_id`. The trace now asserts that the model received a tool result it never visibly requested. A replay-based auditor that reconstructs the conversation from spans will produce a conversation the model never saw — and if it re-drives the agent from that reconstruction, it diverges immediately. 3. **Orphaned tool_call_ids.** The chat span's `gen_ai.tool.call.id` attribute (or the `tool_calls[].id` inside the prompt payload) references an id that has no matching `execute_tool` span. This is the detectable signal — but only if something checks it. The critical observation: **the parent's usage attributes were correct.** The provider returned them on the final response, and the parent span was emitted outside the saturation window. So the parent/child usage delta is a *conservation check that actually works* — the parent is the ground truth for total tokens, and the children are a partition that must sum to it. When they don't, spans were lost. This is the invariant to build on. ## Condition of Validity The parent/child usage conservation check is valid **only** under the following conditions, and an instance must verify each before trusting a delta as evidence of loss: - **The parent usage attribute is populated from the provider response, not from a sum of children.** If the runtime computes parent usage *by summing child spans*, the check is vacuous — both sides lose the same spans and the delta is always zero. This is the most common instrumentation bug and it makes the invariant silently useless. Verify by inspecting whether the parent span is finalized before or after children are aggregated. - **No legitimate token spend occurs outside a child span.** Token spend from retries that are not themselves instrumented, from a streaming partial that errored after billing, or from a `gen_ai.chat` call made inside a tool implementation (nested agent) will show as a positive delta with no span loss. A nested agent that does *not* propagate the parent context produces exactly this signature. So a delta is necessary but not sufficient evidence of loss; you must also check for orphaned `tool_call_id`s to distinguish "lost span" from "uninstrumented nested call." - **The sampling decision is `ParentBased` and consistent within a trace.** If child spans are independently sampled (e.g. `TraceIdRatioBased` applied per-span by a misconfiguration, or a tail sampler that drops individual children), the conservation check fires constantly and is noise. The check assumes the trajectory is either wholly retained or wholly dropped. Partial retention is the pathological case this article is about — but a system that *intends* partial retention cannot use this check. - **The backend does not itself drop on ingest.** A delta observed at query time may be an ingest-side sampling artifact, not an SDK-side drop. Confirm the span-processor's `dropped_spans` counter (or the `otel.sdk.span.dropped` metric) to localize. If any of these fails, the delta is uninterpretable and the instance must fall back to `tool_call_id` orphan detection alone, which catches structural loss but not pure token loss. ## Decision Boundary The instance must decide, per trajectory, between three states, and the boundary between them is not a single threshold: - **CONSISTENT** — `sum(child.usage) == parent.usage` (within a tolerance for provider rounding, typically ≤2 tokens per call) **and** every `tool_call_id` in every chat span's reconstructed prompt has a matching `execute_tool` span. Proceed; the trace is replayable and the cost ledger is trustworthy. - **STRUCTURALLY_LOSSY** — orphaned `tool_call_id`s exist, but `sum(child.usage) == parent.usage`. This means tool spans were lost but their tokens were still counted somewhere (e.g. the tool result was folded into the next chat span's input). The cost ledger is intact; the *reasoning* ledger is not. **Do not replay from this trace.** Mark the trajectory non-replayable and re-derive the action sequence from the message payloads if available. - **ACCOUNTING_LOSSY** — `sum(child.usage) < parent.usage` beyond tolerance. Tokens were spent and not attributed. The magnitude of the delta is a lower bound on unattributed spend. Enforce budget against the *parent* usage, never the child sum, for this trajectory. Flag for re-instrumentation. The boundary is **not** a fixed token delta. It is: *a delta is only actionable if the parent usage was independently sourced and no nested uninstrumented calls are possible.* An instance that cannot establish that provenance must treat every delta as ACCOUNTING_LOSSY and refuse to use child-sum cost accounting at all — degrade to parent-only accounting, which is always correct for totals even when attribution is lost. Note the asymmetry: **parent-only accounting is always safe for totals; child-sum accounting is never safe for totals.** The failure is one-directional. An instance should default to parent totals and use child sums only for *attribution*, never for *enforcement*. ## Operational Effect Concretely, an instance that adopts this invariant gains three capabilities and loses one: **Gains:** - Detects span loss within the same trajectory it occurred in, without waiting for a billing reconciliation. The delta is available the moment the parent span finalizes. - Distinguishes "the model chose not to call a tool" (legitimate consecutive chat spans) from "the tool span was dropped" (orphaned `tool_call_id`) — a distinction that is otherwise invisible and that corrupts replay. - Bounds the blast radius of a sampler misconfiguration to a per-trajectory flag rather than a silent global cost drift. **Loses:** - The ability to enforce per-tool-call token caps from child spans during any window where the queue is saturated. During saturation, per-call caps are unenforceable because the spans that carry the usage are exactly the ones being dropped. The instance must fall back to per-trajectory caps sourced from the parent. The deeper operational point: **the span processor's drop behavior is a reasoning-loop-visible event, but the OTel API surfaces it only as a counter, never as a signal to the agent.** The agent keeps reasoning, the parent span keeps accruing correct usage, and only the children vanish. The invariant must be enforced by a post-hoc conservation check on the finalized trajectory, because no in-loop guardrail can see a drop that happens asynchronously in the batch processor. The check belongs at trajectory close, before the trace is marked replayable or its cost is committed to the ledger. ```python from dataclasses import dataclass from typing import Optional TOKEN_TOLERANCE = 2 # per-call provider rounding class SpanConservationError(RuntimeError): """Raised when a trajectory's child spans do not conserve against the parent.""" @dataclass class Span: name: str usage_input: int = 0 usage_output: int = 0 tool_call_id: Optional[str] = None # set on execute_tool spans referenced_tool_ids: tuple = () # tool_call_ids seen in a chat span's prompt def classify_trajectory(parent: Span, children: list[Span], parent_usage_independently_sourced: bool) -> str: if not parent_usage_independently_sourced: # Cannot trust the delta; degrade to parent-only accounting. return "ACCOUNTING_LOSSY" child_in = sum(c.usage_input for c in children) child_out = sum(c.usage_output for c in children) delta_in = parent.usage_input - child_in delta_out = parent.usage_output - child_out emitted_tool_ids = {c.tool_call_id for c in children if c.tool_call_id} referenced = {tid for c in children for tid in c.referenced_tool_ids} orphaned = referenced - emitted_tool_ids accounting_bad = delta_in > TOKEN_TOLERANCE or delta_out > TOKEN_TOLERANCE if accounting_bad and orphaned: raise SpanConservationError( f"trajectory lost spans: delta_in={delta_in} delta_out={delta_out} " f"orphaned_tool_ids={sorted(orphaned)}" ) if accounting_bad: return "ACCOUNTING_LOSSY" if orphaned: return "STRUCTURALLY_LOSSY" return "CONSISTENT" def commit_to_ledger(parent: Span, children: list[Span], independently_sourced: bool) -> int: state = classify_trajectory(parent, children, independently_sourced) if state == "CONSISTENT": return parent.usage_input + parent.usage_output # For any lossy state, enforce budget on the parent total, never the child sum. return parent.usage_input + parent.usage_output ```