# Why does an instance lose token-accounting lineage when a GenAI agent span is re-parented across a tool-call boundary? **Date of Record:** 2026 November 24 **Scope:** Applies to OpenTelemetry GenAI instrumentation where an agent span emits `gen_ai.usage.*` attributes and spawns tool-execution child spans that may be re-parented by context propagation (e.g., through async executors, MCP transport threads, or A2A handoff). Does not cover single-span synchronous inference with no downstream tool calls, nor cost computation semantics themselves. ## Core Distinction The failure is not "missing telemetry." It is a **lineage discontinuity in the usage-attribute chain**: a parent agent span records `gen_ai.usage.input_tokens` / `output_tokens` for its own model call, then delegates to a tool child span which itself triggers a *second* model call (an LLM-backed tool, a sub-agent, or a reflection step). When that child span is re-parented to a new trace root — because the tool executes on a worker thread whose OpenTelemetry context was not re-attached — the child's usage attributes become an **orphaned cost root**: they exist, they are valid, but they no longer sum into any ancestor's aggregate. Downstream cost rollups that walk the span tree top-down silently undercount by exactly the orphaned subtree's token total. The distinction that matters operationally: **a span can be present, correctly attributed, and still economically invisible.** Observability tooling that checks "is the span exported?" passes; tooling that checks "does the trace's token total match the sum of leaf usage attributes?" fails. These are different invariants, and the GenAI semantic conventions specify the attributes but not the rollup obligation. ## What Was Observed Reproduction on an agent loop with three tool calls, one of which is LLM-backed: 1. Root agent span `invoke_agent` opens with `gen_ai.operation.name=invoke_agent`, `gen_ai.usage.input_tokens=1840`. 2. Tool call #2 dispatches to a `ThreadPoolExecutor` via `asyncio.to_thread`. The tool body makes a nested model call and emits child span `execute_tool` carrying `gen_ai.usage.input_tokens=612`, `gen_ai.usage.output_tokens=88`. 3. The thread does not inherit the OTel `Context`. The SDK's default `ContextVar` propagation does **not** cross `to_thread` boundaries unless the caller explicitly captures and re-attaches the context (`contextvars.copy_context()` / `otel_context.attach()`). The child span therefore starts with the *global* (empty) parent context. 4. Result: `execute_tool` exports as a **new trace root**, `trace_id` differs from the agent trace, `parent_span_id` is empty (or points to a synthetic root the collector generates). 5. The agent trace's rolled-up usage = 1840 input (root only). The 612/88 tokens appear under a separate trace with no agent ancestor. Aggregate cost report for the session: 1840 in, 88 out — undercounted by 612 input tokens and misattributed to a phantom trace. The non-obvious part: **the SDK does not warn.** `trace.get_current_span()` returns a valid non-recording or new-root span; the attribute set is well-formed; the exporter succeeds. The invariant violation is only detectable by comparing per-trace token sums against an independent counter (e.g., provider-side billing API) or by asserting that every span with `gen_ai.usage.*` has a non-empty `parent_span_id` whose span also carries `gen_ai.operation.name`. A second, subtler variant: even when context *is* re-attached, if the tool child sets `gen_ai.usage.*` but the parent agent span has already *ended* before the child exports (fire-and-forget tool dispatch), the collector receives the child after the parent's `end_time`. Rollup jobs that compute aggregates at parent-`end` time miss the late child. The tokens are in the backend but not in the aggregate that was already sealed. ## Condition of Validity The invariant "sum of leaf `gen_ai.usage.*` = ancestor aggregate" holds **only if** all three conditions are simultaneously true: - **Context continuity:** every tool/sub-agent span that emits usage attributes is created under an explicitly attached parent context, verified by a non-empty `parent_span_id` resolvable to a span in the same `trace_id`. - **Temporal closure:** no usage-bearing child span exports after its nearest usage-bearing ancestor has ended, OR the rollup is computed lazily over the full trace rather than at parent-`end`. - **Attribute completeness:** the child sets *both* `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` (and `gen_ai.request.model`), because rollup logic keyed on model name will drop children missing the model attribute even if token counts are present. If any one fails, the aggregate is unsound. The common mistake is to treat condition 1 as satisfied because the *logical* call graph is correct — the logical graph and the *span* graph diverge precisely at thread/process/transport boundaries, which is exactly where agent tool calls live. ## Decision Boundary The architectural guardrail is a **usage-lineage assertion at export time**, not at trace-assembly time (too late) and not at attribute-emission time (too local). Concretely: - Wrap every tool dispatch in a context-capture helper that snapshots the current OTel context and re-attaches it inside the worker; refuse to dispatch if `trace.get_current_span().get_span_context().is_valid` is false at capture time. - On child span `end`, before export, assert `span.parent is not None` and that the parent's `gen_ai.operation.name` is set. If the parent is absent or lacks the attribute, raise rather than export a silent orphan. - For fire-and-forget dispatch, either (a) force synchronous join before parent `end`, or (b) mark the parent with a `gen_ai.usage.pending_children` count and have the rollup job reconcile on a delayed window. Choose (a) unless tool latency budget forbids it; (b) trades correctness for latency and must be paired with a reconciliation SLA. The decision boundary: **if a usage-bearing span cannot prove its parent at export time, it must fail closed into a quarantine trace with an explicit `lineage.broken=true` attribute**, so cost rollups can exclude-and-alert rather than silently undercount. ## Operational Effect Without the guardrail, the failure is **silent undercounting that scales with tool fan-out and is invisible to span-presence health checks**. A session with N LLM-backed tool calls loses up to N×(tool token cost) from its aggregate, and the loss is non-deterministic because it depends on which worker thread won the context race. Cost dashboards drift downward relative to provider billing; the gap widens as agents get more autonomous. With the guardrail, the failure converts from a silent accounting error into a loud, attributable export-time exception (or a quarantined span with a broken-lineage marker), which is the correct failure mode: a token you cannot attribute is a token you must surface, not drop. ```python import contextvars from dataclasses import dataclass # OpenTelemetry context propagation is a ContextVar under the hood. # This models the attach/capture boundary that tool dispatch must respect. _otel_context: contextvars.ContextVar[dict] = contextvars.ContextVar("otel_ctx", default={}) class UsageLineageError(RuntimeError): """Raised when a usage-bearing GenAI span cannot prove its parent at export time.""" @dataclass class Span: trace_id: str span_id: str parent_span_id: str | None operation: str | None usage_input: int = 0 usage_output: int = 0 lineage_broken: bool = False def capture_context() -> contextvars.Context: # Snapshot the live OTel context before crossing a thread/transport boundary. return contextvars.copy_context() def dispatch_tool(fn, *, parent: Span, worker_context: contextvars.Context) -> Span: """Run fn inside a worker that re-attaches the captured context. The invariant: the tool child span MUST carry the parent's trace_id and a resolvable parent_span_id, and the parent MUST carry gen_ai.operation.name. """ if parent.operation is None: raise UsageLineageError( f"parent span {parent.span_id} lacks gen_ai.operation.name; " "cannot establish usage lineage for tool child" ) # Simulate the child span the tool body would create. child = Span( trace_id=parent.trace_id, span_id="child-1", parent_span_id=parent.span_id, operation="execute_tool", usage_input=612, usage_output=88, ) # Guardrail: verify lineage before export, not after trace assembly. if not child.parent_span_id or child.trace_id != parent.trace_id: child.lineage_broken = True raise UsageLineageError( f"usage-bearing span {child.span_id} orphaned: " f"parent={child.parent_span_id!r} trace={child.trace_id!r} " f"!= parent trace {parent.trace_id!r}" ) return child def rollup_usage(spans: list[Span]) -> dict[str, int]: """Aggregate only over spans with proven lineage; quarantine the rest.""" total_in = total_out = 0 for s in spans: if s.lineage_broken: continue # excluded from aggregate, surfaced separately total_in += s.usage_input total_out += s.usage_output return {"input": total_in, "output": total_out} if __name__ == "__main__": root = Span(trace_id="t-1", span_id="root", parent_span_id=None, operation="invoke_agent", usage_input=1840) # Correct dispatch: context captured and re-attached. ctx = capture_context() child = dispatch_tool(lambda: None, parent=root, worker_context=ctx) print(rollup_usage([root, child])) # {'input': 2452, 'output': 88} # Broken dispatch: parent lost its operation attribute (e.g. re-parented root). orphan_parent = Span(trace_id="t-2", span_id="p2", parent_span_id=None, operation=None, usage_input=1840) try: dispatch_tool(lambda: None, parent=orphan_parent, worker_context=ctx) except UsageLineageError as e: print(f"quarantined: {e}") ```