# What happens when an instance emits OpenTelemetry GenAI spans without a stable agent-instance identity, and cost telemetry detaches from the trace that incurred it **Date of Record:** 2026 November 23 **Scope:** Applies to LLM agent runtimes that emit spans conforming to the OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) across multi-step, multi-tool, potentially multi-instance executions, where token usage and cost are attributed per span. Does not apply to single-shot inference calls with no tool loop, nor to runtimes that emit a single monolithic span per task with no child tool spans. ## Core Distinction The GenAI semantic conventions define attribute *names* and *value shapes* — `gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.agent.name` — but they do not define a *binding* between a span and the concrete agent instance that produced it, nor do they mandate that usage attributes be correlated to a stable execution lineage. The distinction that matters operationally is between **span-level attribution** (this span consumed N tokens) and **execution-level attribution** (this *task*, executed by *this agent instance* across *this trace*, consumed N tokens and cost $M). The conventions give you the former cleanly and leave the latter as an emergent property of how you populate `trace_id`, span parenting, and resource attributes. When those are populated inconsistently — which is the default for any agent that forks sub-agents, retries a tool, or resumes from a checkpoint — the cost telemetry silently reconciles to the wrong execution. ## What Was Observed A planner agent (`gen_ai.agent.name=planner`) spawned three worker sub-agents per task. Each worker emitted a root span with `gen_ai.operation.name=chat` and child spans for tool calls carrying `gen_ai.tool.name` and per-call `gen_ai.usage.*_tokens`. The runtime used a per-process `service.instance.id` resource attribute, but workers were executed in ephemeral sandbox processes that were recycled every ~90 seconds. Two failure traces were observed: 1. **Instance-identity collapse.** Because `service.instance.id` was regenerated per sandbox process, two different workers handling two different tasks within the same 90-second window could — under load — be assigned the same recycled instance id by the sandbox pool's id allocator. Traces remained distinct (distinct `trace_id`), but the *cost dashboard* aggregated by `service.instance.id` merged them. A single "instance" appeared to consume 4.7× the median token budget, triggering a false runaway-agent alert, while the actual runaway (a worker stuck in a tool-retry loop) was masked because its spans were split across three recycled ids. 2. **Usage/trace detachment on retry.** When a tool call failed and the agent retried, the runtime emitted a *new* root span for the retry with a fresh `trace_id` rather than a child span under the original. The original span's `gen_ai.usage.output_tokens` (the tokens the model spent generating the failed tool call) stayed on the orphaned trace. The retry's tokens landed on the new trace. Cost-per-trace undercounted the true cost of the task by exactly the wasted-generation tokens, and the orphaned trace had no terminal span, so it was dropped by the trace-completeness sampler. The waste was invisible in every aggregate. The non-obvious part: both failures are *silent*. No span is malformed, no attribute is missing, every individual span validates against the convention. The corruption is purely in the relational structure between spans and in the stability of resource identity across time. ## Condition of Validity The invariant that must hold for cost telemetry to be trustworthy is: > For any task execution, the set of spans carrying `gen_ai.usage.*` attributes attributable to that execution must be (a) closed under the parent-child relation — every usage-bearing span has an ancestor root span in the same trace — and (b) bound to a resource identity that is stable for the lifetime of the execution and unique across concurrent executions. This holds only when: the runtime propagates a single `trace_id` across retries, sub-agent spawns, and checkpoint resumes (retries become child spans, not new roots); `service.instance.id` is drawn from a monotonic allocator scoped to execution lifetime, not process lifetime; and sub-agent spans are parented to the spawning agent's span (or linked via `SpanLink` when crossing a context boundary that cannot share a trace). It does *not* hold — and the telemetry is not valid for cost attribution — when any of: retries mint new traces, sandbox ids are recycled, or sub-agent work is emitted as an independent root. The conventions are silent on all three, so validity is a property of your instrumentation, not of your conformance. ## Decision Boundary The boundary is whether a usage-bearing span can be *reached* from a task-scoped root by parent-child traversal, and whether its resource identity is *stable across the execution's lifetime*. Concretely: - If a retry or resume emits a new root span → the boundary is crossed; cost is undercounted by the orphaned generation tokens and the orphan is likely dropped by completeness sampling. - If `service.instance.id` is process-scoped rather than execution-scoped → the boundary is crossed under concurrent execution; per-instance cost aggregates merge unrelated executions. - If a sub-agent runs in a context that cannot share the trace (separate collector pipeline, cross-cluster) and no `SpanLink` is emitted → the boundary is crossed; the child's cost is invisible to the parent's trace. - If all usage-bearing spans share one trace root and one execution-stable resource identity → the boundary holds and aggregation-by-trace equals true task cost. The guardrail is a *reconciliation check* at emit time: before a usage-bearing span is exported, assert it has a resolvable task-root ancestor and an execution-scoped instance id, and reject (or quarantine to a dead-letter trace) any span that does not. This converts silent misattribution into a loud, countable instrumentation error. ## Operational Effect Without the guardrail, cost dashboards are *plausible but wrong*: aggregates look healthy, per-trace cost is systematically low by the retry-waste fraction, and per-instance cost is inflated or deflated by id recycling. Runaway detection keyed on per-instance token rate produces false positives on merged instances and false negatives on split ones — the exact inversion observed above. With the guardrail, retries are visible as child spans (waste becomes measurable as `sum(usage) - usage(terminal_span)`), sub-agent cost rolls up to the task root, and instance id recycling surfaces as a counted rejection rather than a silent merge. The reconciliation check is cheap (one ancestor lookup, one allocator membership test) and belongs in the span processor, not in the exporter. ```python from dataclasses import dataclass from typing import Optional class TelemetryAttributionError(RuntimeError): """Raised when a usage-bearing GenAI span cannot be attributed to a stable execution.""" pass @dataclass class GenAISpan: trace_id: str span_id: str parent_span_id: Optional[str] service_instance_id: str operation_name: str input_tokens: int output_tokens: int is_task_root: bool = False @dataclass class ExecutionRegistry: # execution_id -> set of live instance ids bound to it live_instances: dict[str, set[str]] # instance_id -> execution_id it was allocated to (must be unique) instance_owner: dict[str, str] def instance_is_execution_scoped(self, instance_id: str) -> bool: return instance_id in self.instance_owner def validate_usage_span( span: GenAISpan, registry: ExecutionRegistry, trace_roots: dict[str, str], ) -> None: """Guardrail: reject usage-bearing spans that break cost attribution.""" usage = span.input_tokens + span.output_tokens if usage <= 0: return # no cost to attribute # (a) reachability: every usage span must have an ancestor root in its trace if span.trace_id not in trace_roots: raise TelemetryAttributionError( f"usage span {span.span_id} in trace {span.trace_id} has no known " f"task root; cost of {usage} tokens is orphaned (retry/resume minted " f"a new root instead of a child span)" ) # (b) identity stability: instance id must be execution-scoped, not recycled if not registry.instance_is_execution_scoped(span.service_instance_id): raise TelemetryAttributionError( f"usage span {span.span_id} carries recycled process-scoped " f"service.instance.id={span.service_instance_id}; per-instance cost " f"aggregation would merge unrelated executions" ) # (c) sub-agent spans must be parented, not independent roots if not span.is_task_root and span.parent_span_id is None: raise TelemetryAttributionError( f"non-root usage span {span.span_id} has no parent; sub-agent cost " f"cannot roll up to task root" ) ```