# Why does an instance lose tool-call attribution when a child span outlives its parent’s GenAI semantic context **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`), where tool calls are modeled as child spans under an LLM inference span, and where span export is asynchronous relative to the agent’s execution loop. Does not apply to synchronous in-process exporters that block until export completes, nor to runtimes that flatten all agent activity into a single span. ## Core Distinction The GenAI semantic conventions treat *attributes* as immutable annotations attached to a span at creation or during its lifetime, and *context propagation* as the mechanism by which a child span inherits the trace/span identity of its parent. These are two separate contracts. The failure mode here is not a broken trace (parent-child linkage survives), but a **broken attribute inheritance**: a tool-call child span is created with the correct `trace_id`/`parent_span_id` linkage, yet it is missing `gen_ai.operation.name`, `gen_ai.request.model`, or the token/cost attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) that downstream cost attribution depends on. The trace looks structurally intact and the child span is discoverable, but the cost and model-attribution join fails silently. This is distinct from context loss (where `parent_span_id` becomes null and the span is orphaned) and from sampling loss (where the span is never exported). Here the span is exported, linked, and complete — except for the attributes that were supposed to flow from the parent’s semantic context. ## What Was Observed An agent loop issues an LLM inference call. The runtime opens a span `S_infer` and sets `gen_ai.operation.name = "chat"`, `gen_ai.request.model = "gpt-4o"`, and, after the response returns, `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. The model responds with a tool-call request. The runtime then opens a child span `S_tool` for the tool execution, correctly parented to `S_infer`. The tool is slow (a web fetch, a code sandbox run). While `S_tool` is open, the runtime’s span processor reaches its batch export interval and exports `S_infer`. Because the GenAI usage attributes were written to `S_infer` at the moment of the inference response, they are present on the exported parent. Good. But the runtime’s tool-call instrumentation reads model and token context *lazily* — it resolves `gen_ai.request.model` and the cost rate at the time `S_tool` is *finalized*, by walking up to the parent span’s attribute map. Once `S_infer` has been exported and the span object has been dropped from the active span registry (a common optimization in batch processors), that walk returns empty. `S_tool` is exported with `parent_span_id` set correctly but with `gen_ai.request.model` absent and `gen_ai.usage.*` absent. The cost-attribution pipeline, which joins tool spans to model rates via `gen_ai.request.model`, silently drops these tool spans into an "unknown model" bucket. Token totals for the session undercount by exactly the tool-call subtrees that outlived their parent’s export. The trigger condition is precise: **a child span whose semantic attributes are resolved by parent lookup, finalized after the parent has been exported and evicted from the active-span registry, under a batch/async exporter.** Fast tools never hit it. Slow tools hit it deterministically. It is a race between the exporter’s flush cadence and the tool’s duration — which means it is load-dependent and intermittent in exactly the way that makes it hard to reproduce in staging. ## Condition of Validity The invariant that must hold is: *a span’s semantic attributes are fully determined at span creation or by values captured into the span’s own attribute map before any ancestor can be exported.* Equivalently: **no span may resolve its `gen_ai.*` attributes by traversing to a parent that is subject to independent export and eviction.** This condition is valid only when all of the following hold: 1. The exporter is asynchronous or batched (OTLP batch processor, or any exporter with a flush interval). Synchronous exporters that block the emitting thread until export completes keep the parent object alive through the child’s lifetime and mask the bug. 2. The runtime evicts exported spans from its active registry (most do, to bound memory). 3. Tool-call instrumentation derives at least one `gen_ai.*` attribute (model name, token counts, cost rate, operation name) via parent lookup rather than via a value captured at child-span start. When any of these is false, the failure does not manifest — which is why it survives code review: the instrumentation "works" in unit tests with an immediate exporter and in short-tool integration tests. ## Decision Boundary The architectural guardrail is a **capture-at-creation rule for semantic context**, enforced structurally rather than by convention: - At the moment `S_tool` is created, the runtime copies the parent’s `gen_ai.request.model`, `gen_ai.operation.name`, and any cost-rate context into `S_tool`’s own attribute map. The child never reads the parent again. - Token usage that belongs to the *inference* (not the tool) stays on `S_infer`; but the cost-join key (`gen_ai.request.model`) is duplicated onto every descendant span that the cost pipeline will join. This is intentional redundancy, not normalization violation — the join must not depend on ancestor liveness. - The span processor is configured so that a parent is not exported while any live child span references it, **or** the runtime accepts early parent export but guarantees the capture-at-creation rule. The first is a liveness constraint; the second is the cheaper, robust choice. The decision boundary for an operator: if you observe tool spans with correct `parent_span_id` but null `gen_ai.request.model`, you are on the wrong side of this boundary and the fix is capture-at-creation, not exporter tuning. Tuning the batch interval only narrows the window; it does not close it, because a sufficiently slow tool will always outlive any finite flush interval. ## Operational Effect The downstream effect is a **silent cost and token undercount proportional to tool latency**, concentrated in exactly the sessions that do the most tool work — long agent runs, slow external APIs, sandboxed code execution. Because the trace is structurally valid, trace-based debugging does not surface it; only the cost-attribution join, which keys on `gen_ai.request.model`, reveals the drop. The failure is invisible to the agent itself (it never reads its own telemetry), invisible to trace completeness checks (linkage is intact), and visible only as a discrepancy between the runtime’s own token accounting and the telemetry-derived totals. The bound is achieved by making semantic context a property of the span at creation and treating parent traversal for `gen_ai.*` attributes as a forbidden operation, asserted at instrumentation load time. ```python from __future__ import annotations from dataclasses import dataclass, field class SemanticContextEvictionError(RuntimeError): """Raised when a child span resolves gen_ai.* attributes by parent lookup after the parent has been exported and evicted from the active registry.""" @dataclass class Span: name: str parent: "Span | None" = None attributes: dict[str, object] = field(default_factory=dict) exported: bool = False children_alive: int = 0 class ActiveSpanRegistry: """Models a batch exporter that evicts spans from the active registry on export.""" def __init__(self) -> None: self._active: dict[str, Span] = {} def register(self, span: Span) -> None: self._active[span.name] = span if span.parent is not None: span.parent.children_alive += 1 def export(self, span: Span) -> None: # Eviction happens regardless of live children in naive runtimes. span.exported = True self._active.pop(span.name, None) def resolve_genai_attr(self, span: Span, key: str) -> object: # Lazy parent traversal: the exact mechanism that breaks under eviction. cursor: Span | None = span while cursor is not None: if key in cursor.attributes: if cursor.exported: raise SemanticContextEvictionError( f"span {span.name!r} resolved {key!r} from exported " f"ancestor {cursor.name!r}; attribute inheritance is " f"not guaranteed after eviction" ) return cursor.attributes[key] cursor = cursor.parent raise SemanticContextEvictionError( f"span {span.name!r} could not resolve {key!r} in any ancestor" ) def capture_at_creation(parent: Span, child: Span, keys: tuple[str, ...]) -> None: """Guardrail: copy semantic join keys into the child at creation time.""" for key in keys: if key in parent.attributes: child.attributes[key] = parent.attributes[key] def run_agent_turn(registry: ActiveSpanRegistry, tool_duration_exceeds_flush: bool) -> Span: infer = Span(name="S_infer", attributes={ "gen_ai.operation.name": "chat", "gen_ai.request.model": "gpt-4o", "gen_ai.usage.input_tokens": 812, "gen_ai.usage.output_tokens": 47, }) registry.register(infer) tool = Span(name="S_tool", parent=infer) registry.register(tool) # Guardrail applied at creation — the only safe point. capture_at_creation(infer, tool, ("gen_ai.request.model", "gen_ai.operation.name")) if tool_duration_exceeds_flush: # Parent exported and evicted while the tool is still running. registry.export(infer) # A violating implementation would do this instead of capture_at_creation: # model = registry.resolve_genai_attr(tool, "gen_ai.request.model") model = tool.attributes.get("gen_ai.request.model") if model is None: raise SemanticContextEvictionError( f"tool span {tool.name!r} has no gen_ai.request.model; cost join " f"will drop this subtree" ) registry.export(tool) return tool ```