# What happens when an instance emits GenAI spans with tool-call attributes but no parent agent span, breaking trace-based cost attribution **Date of Record:** 2026 November 30 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where per-instance token and cost telemetry is reconstructed by summing spans along a trace. Does not apply to single-span, single-call inference logging where attribution is done by direct span ID. ## Core Distinction The GenAI semantic conventions describe *what* to record on a span (`gen_ai.system`, `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`), not *how spans nest*. The conventions are attribute-level, not topology-level. This produces a silent class of failure: an agent runtime that correctly emits tool-call spans and correctly emits per-call usage attributes, but fails to emit a parent agent span (or emits it with a broken `trace_id` propagation), so every tool call becomes a *trace root* rather than a child. The distinction that matters operationally: a well-formed span is not the same as a well-attributed span. A span can be 100% schema-compliant and still be unattributable, because attribution is a property of the trace graph, not of any single span's attributes. ## What Was Observed A multi-step agent (planner → tool executor → summarizer) was instrumented so that each LLM call emitted a span with `gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and each tool invocation emitted `gen_ai.operation.name=execute_tool` with `gen_ai.tool.name` and `gen_ai.tool.call.id`. The agent's own orchestrator span was created with `gen_ai.operation.name=invoke_agent`. Because the orchestrator span was created lazily (only after the planner returned its first decision), the first tool-call span was emitted *before* the orchestrator span existed. The OpenTelemetry SDK auto-generated a new `trace_id` for that first tool span — it had no active context to inherit. Subsequent tool spans, created after the orchestrator span existed, correctly inherited the orchestrator's `trace_id`. The result was a single logical agent run split across two traces: one containing the orphaned first tool call and its tokens, one containing everything else. Downstream, the cost-attribution pipeline summed `gen_ai.usage.*_tokens` grouped by root `trace_id`. The orphaned tool call's tokens were attributed to a phantom "agent" with a single tool call and no model request. Per-run cost was under-counted by the first tool call's input tokens (the tool's schema injection, often the largest single input-token charge in the run), and the phantom entry polluted the top-N cost report with a non-existent agent. A second observed variant: the orchestrator span *was* emitted, but with `gen_ai.agent.id` set from a per-process UUID rather than a per-run identifier, so all runs of the same process collapsed into one attribution bucket. The tokens were correct; the grouping was wrong. Both failures produce the same observable: token totals that don't reconcile against the sum of per-step costs. ## Condition of Validity The invariant that must hold for trace-based attribution to be correct: > For every span carrying `gen_ai.usage.input_tokens` or `gen_ai.usage.output_tokens`, there exists exactly one ancestor span in the same `trace_id` with `gen_ai.operation.name=invoke_agent` and a stable `gen_ai.agent.id` scoped to the logical run. This fails when any of the following hold: 1. **Lazy parent creation.** The agent span is created after the first child call, so the first child has no parent context and roots a new trace. 2. **Context propagation loss at a tool boundary.** A tool executed in a subprocess, thread pool, or separate worker that does not carry the OTel `Context` will emit spans rooted in a fresh trace. This is common with sandboxed code execution, where the sandbox deliberately does not inherit the caller's context. 3. **Batching.** If tool calls are batched and emitted after the agent span closes, the batch's spans root independently. 4. **Retries with fresh context.** A retried LLM call issued from a retry handler that doesn't re-attach the original context emits a second root. The invariant does *not* require the parent span to be emitted first in wall-clock time — only that it exists in the trace graph and that children reference it. A span can be created with an explicit parent context even if that parent is created later, as long as the parent's `SpanContext` is available at child-creation time. ## Decision Boundary The decision is whether to trust trace-based attribution or to require an explicit run identifier carried as an attribute on every span. - **Trust trace topology** only when the agent runtime guarantees that the agent span's `SpanContext` is created and made current *before* any child span is emitted, and that all tool execution paths (including subprocess and sandbox) explicitly propagate that context. This is the cheaper path but requires auditing every tool-execution boundary for context loss. - **Require an explicit `gen_ai.agent.run_id` attribute** on every span that carries usage attributes, and attribute by that attribute rather than by trace root. This is robust to context loss, batching, and retries, at the cost of a small per-span attribute and a discipline requirement that no span carrying usage omits it. The boundary condition: if any tool executes outside the process that holds the OTel `Context`, or if any span is emitted asynchronously after the agent span closes, the trace-topology path is invalid and the explicit-attribute path is mandatory. Do not attempt to "fix" the trace graph post-hoc by joining orphans on timestamp proximity — that heuristic silently mis-joins concurrent runs. ## Operational Effect When the invariant is violated, the failure is silent at the span level (every span validates against the schema) and surfaces only as a reconciliation mismatch: sum of per-run attributed tokens ≠ sum of all `gen_ai.usage.*_tokens` across spans. The mismatch is usually small (the first tool call's tokens) and is easily dismissed as sampling or rounding. It is not. It is a structural attribution gap. The guardrail: emit `gen_ai.agent.run_id` on every span that carries usage, and add a reconciliation check that asserts, per run, that the sum of child-span tokens equals the agent span's reported total (or, absent a reported total, that every usage-bearing span has a non-null `run_id`). Fail the run's telemetry pipeline loudly rather than attributing to a phantom. The check below encodes exactly this invariant and raises on the first orphaned usage span. ```python import uuid from dataclasses import dataclass, field from typing import Optional class OrphanedUsageSpanError(RuntimeError): """A span carrying gen_ai token usage has no attributable agent run.""" @dataclass class Span: span_id: str trace_id: str parent_span_id: Optional[str] operation_name: str attributes: dict = field(default_factory=dict) def has_usage(self) -> bool: return any( k in self.attributes for k in ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") ) def agent_run_id(self) -> Optional[str]: return self.attributes.get("gen_ai.agent.run_id") def assert_usage_attributable(spans: list[Span]) -> dict[str, int]: """Return tokens grouped by run_id; raise if any usage span is orphaned.""" by_id = {s.span_id: s for s in spans} totals: dict[str, int] = {} for span in spans: if not span.has_usage(): continue run_id = span.agent_run_id() if run_id is None: # Fall back to walking the trace graph to an invoke_agent ancestor. cursor = span seen = set() while cursor.parent_span_id is not None: if cursor.span_id in seen: break seen.add(cursor.span_id) parent = by_id.get(cursor.parent_span_id) if parent is None: break if parent.operation_name == "invoke_agent": run_id = parent.agent_run_id() break cursor = parent if run_id is None: raise OrphanedUsageSpanError( f"span {span.span_id} (trace {span.trace_id}, " f"op={span.operation_name}) carries gen_ai usage " f"but has no attributable agent run: no gen_ai.agent.run_id " f"attribute and no invoke_agent ancestor in trace" ) tokens = ( span.attributes.get("gen_ai.usage.input_tokens", 0) + span.attributes.get("gen_ai.usage.output_tokens", 0) ) totals[run_id] = totals.get(run_id, 0) + tokens return totals def reconcile_run(run_id: str, spans: list[Span], reported_total: int) -> None: totals = assert_usage_attributable(spans) observed = totals.get(run_id, 0) if observed != reported_total: raise OrphanedUsageSpanError( f"run {run_id}: attributed tokens {observed} != reported {reported_total}; " f"attribution gap of {reported_total - observed} tokens" ) ```