# In what scenarios must an instance refuse to emit a completed `gen_ai.agent` span when tool-call child spans were evicted from the SDK's batch processor **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes emitting OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.agent.id`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) through a `BatchSpanProcessor` whose export queue can drop spans under backpressure. Does not apply to synchronous `SimpleSpanProcessor` deployments or to agents whose tool calls are traced as span events on a single parent span. ## Core Distinction The GenAI semantic conventions treat a tool call as a **child span** of the agent invocation span, with cost and token usage attributed via `gen_ai.usage.*` on each span where the model was actually called. The critical invariant is *referential completeness of the agent trace*: a `gen_ai.agent` span that declares `gen_ai.operation.name = "invoke_agent"` asserts, by its very existence, that its tool-call children executed and are representable. When the SDK's batch processor evicts child spans—because the export queue overflowed during a token-budget-exhausting reasoning loop—the parent span survives (it is typically closed last and thus enqueued last, or is retained by a priority exporter) while its children are silently dropped. The result is not "missing telemetry" in the benign sense. It is a **structurally valid but semantically false trace**: a parent span whose `gen_ai.usage.output_tokens` reflects the *aggregate* of a multi-turn tool loop, but which has zero child spans, forcing downstream cost attribution and audit replay to treat a 12-tool-call agent run as a single monolithic model invocation. The distinction that matters operationally: *dropped spans are recoverable; a parent span that lies about its own topology is not.* A missing child is an absence. A parent with mismatched aggregate usage and no children is a **positive assertion of a false structure**, and any auditor or cost-reconciliation pipeline that trusts `gen_ai.operation.name = "invoke_agent"` will mis-attribute spend and mis-reconstruct the agent's decision path. ## What Was Observed A research agent performing a 9-step retrieval-and-synthesis loop (each step: one `execute_tool` span for a web fetch, one `chat` span for the model turn) exhausted its `max_tokens` budget on step 7. The runtime's retry logic re-invoked the model with a truncated context, and the SDK's `BatchSpanProcessor` (default `max_queue_size=2048`, but configured here to 256 to bound memory on the agent pod) began dropping spans once the retry storm produced ~40 spans per second for 6 seconds. The eviction policy is FIFO on the queue: the *oldest* spans drop first—which are exactly the early tool-call children (steps 1–4). The agent span itself, opened first but closed last, was enqueued at the end and survived. Observed export: - One span: `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.id=research-agent-v3`, `gen_ai.usage.input_tokens=184,220`, `gen_ai.usage.output_tokens=9,410`, duration 41.2s, `status=OK`. - Zero child spans. No `gen_ai.tool.name` attributes anywhere in the trace. - The downstream cost reconciler, which sums `gen_ai.usage.*` over *leaf* spans (spans with no children) to avoid double-counting, attributed the entire 193,630 tokens to a single "model call" and flagged the agent as a cost-anomaly outlier—triggering a false incident. The failure trace: `on_end(agent_span)` → `queue.put(agent_span)` succeeds → exporter drains → parent emitted with `child_count=0` but `usage` reflecting 9 turns. The invariant "a parent's aggregate usage equals the sum of its children's usage" was violated by eviction, and nothing in the SDK or the semantic conventions enforces it at emit time. ## Condition of Validity The guardrail is only sound under these conditions, and an instance must check them before deciding whether to emit or suppress the parent: 1. **The agent span carries aggregate usage that was accumulated across child model calls.** If the agent span's `gen_ai.usage.*` is populated only from its *own* single model call (no aggregation), eviction of tool children does not corrupt cost attribution—the parent is self-consistent. Suppression is unnecessary and harmful (it deletes valid data). 2. **The runtime maintains an expected-child count.** The agent loop knows how many tool calls it dispatched (`dispatched_tool_calls`). If `observed_child_spans < dispatched_tool_calls` at parent close time, referential incompleteness is *detectable*. If the runtime does not track dispatched count, it cannot distinguish "agent made 0 tool calls" from "all tool spans were evicted," and must not guess. 3. **The exporter exposes drop counters.** `BatchSpanProcessor` reports `dropped_spans` via `otel.sdk.span.processor.dropped` metrics; the instance must read this delta over the agent's lifetime, not infer eviction from wall-clock. If condition 1 fails, emit normally. If condition 2 fails, the instance must annotate rather than suppress (see Decision Boundary). Only when 1 and 2 both hold—aggregate usage present *and* child-count mismatch detectable—is suppression or quarantine licensed. ## Decision Boundary The boundary is **not** "emit vs. drop." Dropping the parent span destroys the only evidence that the agent ran at all, which is worse for audit than a flagged-but-present span. The correct boundary is a three-way decision keyed on `(aggregate_usage_present, child_count_mismatch_detectable, dropped_span_delta > 0)`: - **All three true → quarantine, do not emit as `OK`.** Emit the agent span with `status=ERROR`, `otel.status_description="child_spans_evicted"`, and a custom attribute `gen_ai.agent.trace_incomplete=true`. Strip or zero the aggregate `gen_ai.usage.*` (since it cannot be reconciled to children) and instead emit the raw aggregate under a non-standard `agent.local.aggregate_tokens` attribute that cost pipelines are configured to *ignore*. This preserves the run's existence without asserting a false topology. - **Aggregate present, mismatch undetectable → emit with `gen_ai.agent.usage_unverified=true`.** The span is honest about its own uncertainty. - **No aggregate, or no eviction → emit normally.** The invariant the instance enforces: *a span with `gen_ai.operation.name=invoke_agent` and populated `gen_ai.usage.*` must either have child spans summing to that usage, or carry an explicit incompleteness marker.* Silent emission of the former without the latter is the prohibited state. ## Operational Effect Enforcing this boundary converts a silent cost-attribution corruption into a loud, greppable signal. Cost reconcilers keyed on `gen_ai.agent.trace_incomplete` can route these traces to a manual-replay queue rather than the anomaly detector, eliminating the false-incident class observed above. Audit replay tools that reconstruct agent decision paths from child spans now see an explicit "this trace is not replayable" flag instead of an empty child list that they previously interpreted as "agent reasoned without tools"—a catastrophic misreading for any post-hoc safety review. The cost: the agent pod must hold a small per-invocation counter and read the processor's drop metric at span close, adding ~microseconds and one metric read per agent run. That overhead is bounded and independent of token volume, unlike the eviction it guards against. ```python from dataclasses import dataclass from typing import Optional class TraceIncompletenessError(RuntimeError): """Raised when an agent span cannot be emitted without violating the referential-completeness invariant of the GenAI semantic conventions.""" pass @dataclass class AgentSpanClosure: dispatched_tool_calls: int observed_child_spans: int aggregate_usage_present: bool dropped_span_delta: int def classify_agent_span(closure: AgentSpanClosure) -> str: """Return the emission decision for a closing gen_ai.agent span. Decisions: 'emit', 'emit_unverified', 'quarantine'. Raises TraceIncompletenessError only when the runtime cannot make a sound decision (missing child-count tracking while eviction occurred). """ child_mismatch = closure.observed_child_spans < closure.dispatched_tool_calls eviction_observed = closure.dropped_span_delta > 0 if not closure.aggregate_usage_present: # Parent usage is self-consistent; eviction of children is benign. return "emit" if child_mismatch and eviction_observed: # Aggregate usage present AND we can prove children were lost. return "quarantine" if child_mismatch and not eviction_observed: # Mismatch without eviction signal: cannot distinguish a bug in # child-span creation from silent loss. Refuse to assert either way. raise TraceIncompletenessError( f"agent dispatched {closure.dispatched_tool_calls} tool calls but " f"only {closure.observed_child_spans} child spans observed with no " f"drop signal; cannot emit a truthful invoke_agent span" ) if eviction_observed and closure.dispatched_tool_calls > 0 and not child_mismatch: # Eviction happened but child count matches: eviction hit non-agent # spans. Parent is still consistent; emit but mark usage unverified. return "emit_unverified" return "emit" def build_agent_span_attributes(closure: AgentSpanClosure) -> dict: decision = classify_agent_span(closure) attrs = { "gen_ai.operation.name": "invoke_agent", "gen_ai.agent.id": "research-agent-v3", } if decision == "quarantine": attrs["otel.status_code"] = "ERROR" attrs["otel.status_description"] = "child_spans_evicted" attrs["gen_ai.agent.trace_incomplete"] = True # Strip aggregate usage; move to a locally-ignored attribute so cost # pipelines do not attribute tokens to a topology that does not exist. attrs["agent.local.aggregate_tokens"] = closure.aggregate_usage_present elif decision == "emit_unverified": attrs["gen_ai.agent.usage_unverified"] = True return attrs ```