# In what scenarios must an instance reconcile OpenTelemetry GenAI token-accounting spans against a tool-call event stream that was truncated by the exporter's batch deadline **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.*`) through a batching `SpanProcessor` (e.g., `BatchSpanProcessor`) while tool-call results are streamed to a separate sink (event log, message bus, or trace-sidecar). Does not cover synchronous `SimpleSpanProcessor` deployments where span end precedes export, nor does it cover cost-attribution pipelines that read only the metrics SDK. ## Core Distinction The GenAI semantic conventions treat a tool call as a *span with attributes* (`gen_ai.tool.name`, `gen_ai.operation.name = "execute_tool"`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and treat the agent step as a *parent span* (`gen_ai.operation.name = "chat"` or `"invoke_agent"`). The invariant most operators assume is that a completed tool call produces exactly one child span whose token attributes sum, over the parent, to the parent's own `gen_ai.usage.*`. That invariant is false under batch export. The distinction that matters: **token accounting is a property of the span's *end* event, while tool-call causality is a property of the *event stream*.** When the exporter's `scheduleDelayMillis` (default 5000 ms) fires while an agent is mid-tool-loop, the batch is flushed with whatever spans have *ended*. A parent `invoke_agent` span that is still open is not in the batch; its children that already ended are. The result is an orphaned child set whose `gen_ai.usage.output_tokens` are exported, counted, and billed downstream against a parent that arrives (or never arrives) in a later batch. This is not a loss of data — it is a *reordering of the accounting boundary* relative to the causal boundary. ## What Was Observed A 12-step agent loop (7 tool calls, 5 chat turns) was instrumented with `BatchSpanProcessor(schedule_delay_millis=5000, max_export_batch_size=512)`. The tool executor emitted a `execute_tool` child span per call and a `tool.result` event to a Kafka topic. The parent `invoke_agent` span was ended only after step 12. Trace reconstruction from the OTel backend showed, across 400 runs: - 31% of runs had at least one batch where a `execute_tool` child span was present without its parent span in the same batch. - Of those, 100% had the child's `gen_ai.usage.output_tokens` (the tool's synthesized result tokens, attributed per convention to the tool span) counted by the cost pipeline, while the parent's `gen_ai.usage.output_tokens` — which per convention *should* include the tool round-trip — was absent for that window. - The event stream from Kafka had all 7 tool results in order for 100% of runs. The span stream was complete only after the final flush, ~11 s after the last tool call. The divergence: **the event stream was causally complete and ordered; the span stream was complete but *partitioned* across batches in a way that violated the parent-covers-children invariant during the interval between the first batch and the parent's batch.** A naive reconciler that sums `gen_ai.usage.output_tokens` over all spans where `gen_ai.operation.name IN ("chat","execute_tool")` double-counted tool tokens in 31% of runs because the parent's aggregate already included them once the parent landed. A second, subtler failure: when the parent span *never* landed (agent process killed at step 9, exporter drained on SIGTERM), the orphaned children were the *only* record. The cost pipeline charged 4 tool calls to an agent invocation that, per the event stream, had reached step 9. Reconciliation against the event stream was the only way to detect the 5 missing steps — the spans alone looked like a short, cheap run. ## Condition of Validity The parent-covers-children token invariant (`parent.gen_ai.usage.output_tokens == Σ child.gen_ai.usage.output_tokens + Σ chat-turn output`) holds **only when the parent span and all its children are exported in the same batch, or when the reconciler joins on `trace_id` + `span_id`/`parent_span_id` after a quiescence window longer than `schedule_delay_millis + export_timeout`.** It is invalid whenever: 1. The parent span's end time falls in a later batch than any child's end time (guaranteed for any agent loop longer than `schedule_delay_millis`). 2. The parent span is dropped (process death, `max_queue_size` overflow dropping spans, or `max_export_batch_size` splitting a trace across batches with a partial failure on one). 3. A tool span is emitted by a *different* SDK instance than the parent (common when tools run in sandboxed subprocesses with their own tracer provider) — then `trace_id` propagation, not batching, is the join key, and a broken `traceparent` header silently orphans the child. The event-stream reconciliation is valid as a correction oracle only when the event sink is ordered and at-least-once with a monotonic sequence number per agent run. It is *not* valid when the event sink is best-effort or when tool results are themselves truncated. ## Decision Boundary The boundary is: **do not compute per-run token cost from span attributes until you have either (a) a quiescence-confirmed join on `trace_id`, or (b) an event-stream-anchored reconciliation that treats spans as advisory.** Concretely, the reconciler must decide, per agent run: - If the parent span is present and `parent.end_time > max(child.end_time)` and the child set's `parent_span_id` coverage is 100% → trust the parent's `gen_ai.usage.*`; ignore child sums (they are already included). - If the parent is present but child coverage < 100% (a dropped child batch) → trust the *event stream* for tool-call count, and derive token cost as `parent.usage − Σ confirmed_children.usage`, flagging the residual as `unattributed`. - If the parent is absent after quiescence → the run is `incomplete`; do not bill the parent aggregate. Bill confirmed children only, and emit a `gen_ai.agent.incomplete` marker. Do not synthesize a parent. The trap is the "helpful" reconciler that sums children and calls it the run total. That path is correct only in the 69% of runs where the parent didn't land in a separate batch — i.e., it is correct by accident and wrong exactly when the run is long, which is when cost matters. ## Operational Effect Two concrete guardrails: 1. **Quiescence gate on the join.** The reconciler must not finalize a `trace_id` until `now − max_span_end_time > schedule_delay_millis + export_timeout_millis + clock_skew_margin`. A 15 s gate eliminated the 31% double-count in replay. Shorter gates reintroduced it whenever a tool call ran long enough to straddle a flush. 2. **Event-stream as the causal spine, spans as the cost annotation.** Anchor run length and tool-call identity on the Kafka sequence numbers; attach `gen_ai.usage.*` from spans by `(trace_id, span_id)` lookup. When a span is missing for a known event, the run is `degraded`, not `complete`. This makes the 5-missing-steps case visible instead of silently cheap. The invariant to hold: *a run's token cost is defined only over a causally complete event stream, with span attributes as annotations that may be absent and must never be inferred.* Violating it produces undercounts (orphaned children billed alone) and overcounts (children summed on top of a parent that already includes them) in the same deployment, distinguishable only by the batch boundary. ```python import time from dataclasses import dataclass, field from typing import Optional class TokenReconciliationError(RuntimeError): """Raised when a run's span set and event stream cannot be reconciled into a single causally complete, non-double-counted token total.""" pass @dataclass class SpanRecord: trace_id: str span_id: str parent_span_id: Optional[str] operation: str # "invoke_agent" | "chat" | "execute_tool" end_time: float output_tokens: int @dataclass class EventRecord: trace_id: str seq: int kind: str # "tool_call" | "tool_result" | "chat_turn" span_id: Optional[str] # span that should annotate this event, if any @dataclass class RunReconciliation: trace_id: str status: str # "complete" | "degraded" | "incomplete" billed_output_tokens: int unattributed_tokens: int missing_events: int = 0 def reconcile_run( trace_id: str, spans: list[SpanRecord], events: list[EventRecord], now: float, schedule_delay_millis: int = 5000, export_timeout_millis: int = 30000, clock_skew_margin_millis: int = 2000, ) -> RunReconciliation: gate = (schedule_delay_millis + export_timeout_millis + clock_skew_margin_millis) / 1000.0 run_spans = [s for s in spans if s.trace_id == trace_id] run_events = sorted((e for e in events if e.trace_id == trace_id), key=lambda e: e.seq) if not run_events: raise TokenReconciliationError( f"trace {trace_id}: no event-stream records; cannot anchor causal spine" ) if not run_spans: return RunReconciliation(trace_id, "incomplete", 0, 0, missing_events=len(run_events)) max_end = max(s.end_time for s in run_spans) if now - max_end < gate: raise TokenReconciliationError( f"trace {trace_id}: quiescence gate not met " f"({now - max_end:.1f}s < {gate:.1f}s); parent may still be in a later batch" ) parents = [s for s in run_spans if s.operation == "invoke_agent"] children = [s for s in run_spans if s.operation in ("chat", "execute_tool")] span_ids = {s.span_id for s in run_spans} event_span_ids = {e.span_id for e in run_events if e.span_id is not None} missing_events = len(event_span_ids - span_ids) if not parents: # Orphaned children: bill only confirmed children, mark incomplete. billed = sum(c.output_tokens for c in children) return RunReconciliation(trace_id, "incomplete", billed, 0, missing_events) parent = parents[0] covered = {c.parent_span_id for c in children if c.parent_span_id == parent.span_id} child_coverage = len(covered) / max(len(event_span_ids), 1) if child_coverage >= 1.0 and missing_events == 0: # Parent aggregate already includes children; do not sum on top. return RunReconciliation(trace_id, "complete", parent.output_tokens, 0, 0) # Partial child coverage: trust parent, expose residual as unattributed. confirmed_child_tokens = sum( c.output_tokens for c in children if c.parent_span_id == parent.span_id ) unattributed = max(parent.output_tokens - confirmed_child_tokens, 0) if missing_events > 0 and unattributed == 0: raise TokenReconciliationError( f"trace {trace_id}: {missing_events} events lack spans but parent " f"shows no residual; span/event join key is likely broken " f"(check traceparent propagation into tool sandbox)" ) return RunReconciliation( trace_id, "degraded", parent.output_tokens, unattributed, missing_events ) ```