# Where must an instance attribute span cost when OTel context propagation severs at a tool-call boundary **Date of Record:** 2026 November 27 **Scope:** Applies to multi-turn LLM agents emitting per-turn cost and latency attribution as OpenTelemetry metrics/spans, where turn boundaries are inferred from span parentage. Does not apply to single-shot inference calls or to systems that bill from an out-of-band ledger keyed on request IDs rather than trace topology. ## Core Distinction The distinction that governs everything below is between **logical turn identity** and **trace-tree parentage**. A turn is a logical unit: one model invocation plus the tool calls it spawns and the synthesis that consumes their results. Trace parentage is a *transport artifact*: whichever `traceparent` header survived serialization across each hop. Most observability pipelines assume these two are isomorphic — that a child span's parent is the turn that caused it. They are not isomorphic the moment a tool executes in an environment that does not inherit the ambient `context.Context`. The non-obvious consequence: attribution is not lost *visibly*. It is reassigned. Orphaned tool spans do not vanish; they are reparented to whatever root the SDK synthesizes, and the cost they carry is then billed to a turn that did not incur it — or to no turn, silently inflating the "unattributed" bucket that nobody alerts on. ## What Was Observed A three-tool agent turn (retrieve → rerank → summarize). The orchestrator opened turn span `T1` with `trace_id=X`, `span_id=a`. It invoked the retrieve tool over a subprocess boundary. The subprocess was launched without `TRACEPARENT` in its environment, so its OTel SDK initialized a **new root**: `trace_id=Y`, `span_id=b`. The rerank tool, invoked over HTTP by the same orchestrator, *did* propagate headers and correctly joined `trace_id=X` as child of `a`. Downstream aggregation grouped by `trace_id`. Result: - `trace_id=X` accumulated: model prefill/decode tokens for `T1`, the rerank tool's latency, and the final synthesis. Cost looked *low* per the turn's token count because the retrieve tool's embedding cost (the largest single line item) was absent. - `trace_id=Y` accumulated: the retrieve tool's embedding cost, latency, and retries — with **no parent turn span**. It surfaced as a standalone root trace, classified by the cost pipeline as "background/uncategorized." - The per-turn cost dashboard showed the summarize turn at ~40% of its true cost. The gap was not flagged; the "uncategorized" bucket grew by a steady trickle that matched the retrieve tool's invocation rate, which no one correlated. The failure was latent for eleven days because the *total* spend metric — summed across all trace roots — remained correct. Only the *attribution* was wrong. Every alert keyed on total cost stayed green. ## Condition of Validity Per-turn attribution via trace parentage is valid **if and only if** every span that incurs cost is a descendant, within a single `trace_id`, of exactly one active turn span, and no cost-bearing span is a trace root. This invariant holds only when all three of the following are true: 1. **Context propagation is total** across every execution boundary the turn crosses — subprocess, container, sandbox, remote tool server, queued job. Any boundary that drops `traceparent` breaks the invariant. 2. **Turn spans are opened before, and closed after, all descendant work completes.** An async tool that outlives the turn span's `end()` produces a child whose parent is already closed; some backends drop or reparent it. 3. **No span is shared across turns.** A cached tool result reused by turn `T2` but originally emitted under `T1` carries `T1`'s `trace_id`; attributing its cost to `T2` requires an explicit re-emission, not inheritance. The moment any one of these fails, the invariant is violated and attribution silently degrades to a *best-effort* mapping that is wrong in a direction that under-reports the expensive turns. ## Decision Boundary The boundary is whether to **trust parentage** or **assert lineage explicitly**. Trust parentage when the turn executes entirely in-process and all tools are synchronous. Assert explicit lineage — carry a turn token (`turn_id`) as a span attribute on *every* emitted span regardless of trace topology, and aggregate on `turn_id`, not `trace_id` — the instant any of these hold: - Any tool crosses a process, container, or network boundary you do not control. - Any tool may be invoked asynchronously or fire-and-forget. - Any result may be cached and reused across turns. The decision is not "add more instrumentation." It is: **stop deriving the billing key from the trace tree.** The trace tree is a debugging convenience; the turn token is the accounting primitive. They must be allowed to diverge, and the aggregator must key on the one that survives transport, which is the attribute, not the parent pointer. A secondary boundary: when a tool span is discovered to be a root (no parent, but carries a `turn_id` attribute), the correct action is to **rejoin** it to its turn for accounting while leaving the trace topology alone for debugging. Do not attempt to rewrite `trace_id` after the fact — that corrupts the trace store and races with late-arriving spans. ## Operational Effect With explicit turn-token attribution, the retrieve tool's cost rejoins `T1` even though its spans live under a different `trace_id`. The per-turn dashboard reconciles with total spend. Crucially, the reconciliation itself becomes a **guardrail**: define the invariant `sum(per-turn cost) == sum(all cost-bearing spans)` and alert on any residual. A nonzero residual means a span is carrying cost but no `turn_id` — which is exactly the orphan condition, now caught in minutes instead of eleven days. The residual is the observable. It is the difference between what the trace tree claims and what the ledger asserts, and it is the only signal that fires when context propagation severs at a boundary you did not instrument. Treat a persistent nonzero residual as a hard failure of the attribution invariant, not as noise to be smoothed. ```python class AttributionInvariantViolation(RuntimeError): """Raised when per-turn cost attribution cannot be reconciled to the span ledger.""" pass def reconcile_turn_costs(spans: list[dict], tolerance_usd: float = 1e-6) -> dict[str, float]: """ Reconcile cost-bearing spans against explicit turn tokens. Invariant: every span carrying cost_usd > 0 MUST carry a turn_id attribute. A span that is a trace root (parent_span_id is None) but has cost is the orphan condition produced by severed context propagation across a tool boundary. We refuse to silently bucket it as 'unattributed'. """ per_turn: dict[str, float] = {} orphans: list[dict] = [] for span in spans: cost = span.get("cost_usd", 0.0) if cost <= 0: continue turn_id = span.get("attributes", {}).get("turn_id") if turn_id is None: # Cost exists but no accounting key survived transport. orphans.append(span) continue per_turn[turn_id] = per_turn.get(turn_id, 0.0) + cost total_ledger = sum(s.get("cost_usd", 0.0) for s in spans) total_attributed = sum(per_turn.values()) residual = total_ledger - total_attributed if orphans: raise AttributionInvariantViolation( f"{len(orphans)} cost-bearing span(s) lack a turn_id; " f"residual ${residual:.6f} across trace roots " f"{[s.get('trace_id') for s in orphans][:5]}. " f"Context propagation severed at a tool boundary; " f"rejoin via explicit turn token before trusting per-turn cost." ) if abs(residual) > tolerance_usd: raise AttributionInvariantViolation( f"Attribution residual ${residual:.6f} exceeds tolerance " f"${tolerance_usd:.6f}; ledger and turn aggregation diverged." ) return per_turn ```