# What structural signals indicate span-attribute lineage collapse when GenAI semantic conventions meet multi-turn tool-call fan-out **Date of Record:** 2026 November 29 **Scope:** Applies to OpenTelemetry-instrumented agent runtimes that emit `gen_ai.*` span attributes across multi-turn tool-call loops and reconcile token counts per span. Does not cover single-shot inference spans, non-instrumented agents, or billing reconciliation against provider invoices. ## Core Distinction The GenAI semantic conventions treat a span as the atomic unit of a model interaction: one `gen_ai.chat` or `gen_ai.tool` span carries `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` for *that* call. Multi-turn agent loops, however, are not atomic. A single logical "turn" fans out into N tool-call spans, each of which re-sends a growing conversation prefix. The conventions have no first-class attribute for "this span's input tokens are a re-count of the previous span's prefix." The result is a structural ambiguity: **token accounting is additive per span but the underlying prompt is cumulative per turn.** Any aggregation that sums `input_tokens` across a turn's spans double-counts the prefix by a factor that grows with turn depth. The non-obvious boundary is this: the conventions are internally consistent per span and silently wrong per trace. Nothing in the schema flags the overlap. Lineage collapse is not an instrumentation bug—it is a direct consequence of applying a per-call accounting model to a per-turn execution topology. ## What Was Observed A three-turn agent loop with two tool calls per turn produced seven spans: three `gen_ai.chat` spans and four `gen_ai.tool` spans (turn 3 resolved without a second tool call). Each chat span reported `input_tokens` equal to the full accumulated context: 1,200 → 3,400 → 6,100. Summing `input_tokens` across the three chat spans yielded 10,700. The provider's actual billed input was 6,100—the final prefix only, since providers bill the last full prompt per turn, not the sum of intermediate prefixes. Two structural signals marked the collapse: 1. **Monotonic prefix growth with no `gen_ai.parent` link to the prior chat span.** Each `gen_ai.chat` span in the loop was a sibling under the agent's root span, not a child of the previous chat span. The lineage was topologically flat where it was semantically linear. A trace viewer rendered them as parallel calls; the token accounting treated them as independent; the runtime treated them as sequential. 2. **Tool spans carrying `gen_ai.usage.*` attributes that duplicated the parent chat span's output accounting.** The tool-call argument tokens were counted in the chat span's `output_tokens` *and* re-emitted on the tool span as its own `input_tokens`. The overlap was invisible because both spans were schema-valid. The failure surfaced downstream: a cost dashboard summing `input_tokens` across all `gen_ai.*` spans over-reported spend by 41% for the trace, and a context-budget guard that read the *sum* rather than the *final prefix* tripped its 8,000-token ceiling one turn early, truncating the loop. ## Condition of Validity The additive-accounting interpretation holds only when each span's input is disjoint from every other span's input. That condition is satisfied for: - Independent, non-chained inferences (batch classification, parallel sampling). - Single-turn tool calls where the tool span carries no `gen_ai.usage` attributes of its own. It is violated whenever a span's input prompt is a superset of a prior span's input prompt within the same trace. The structural test is: **for any two `gen_ai.chat` spans in a trace, if span B's input token count is ≥ span A's and B's start time is after A's end time and B shares A's agent root, assume prefix containment unless a `gen_ai.request.prefix_hash` or equivalent attribute proves disjointness.** The conventions do not mandate such an attribute, so the conservative default is to treat chained chat spans as cumulative and de-duplicate by taking the maximum prefix per turn, not the sum. ## Decision Boundary The boundary between "safe to sum" and "must take max" is crossed at the first tool-call fan-out within a turn. Concretely: - **Sum** `input_tokens` only across spans that are siblings in time (concurrent) or provably disjoint (different `gen_ai.request.model` sessions, different conversation IDs). - **Take max** `input_tokens` across chained `gen_ai.chat` spans sharing an agent root and a monotonically growing prefix. - **Never** derive a context-budget guard from a summed `input_tokens` across a multi-turn loop; derive it from the *last* chat span's `input_tokens` plus its `output_tokens`, which is the true occupancy at the next turn's start. The guardrail invariant: **context occupancy at turn N+1 = last_chat.input_tokens + last_chat.output_tokens + tool_result_tokens, and this value must be computed from the terminal span of turn N, not aggregated across the turn.** Any aggregator that cannot identify the terminal span must refuse to emit a budget decision rather than emit a summed one. ## Operational Effect Instrumentation that ignores this boundary produces three predictable regressions: cost over-reporting proportional to turn depth (roughly O(N²) in tokens for N turns of linear growth), premature context-budget truncation, and lineage graphs that misattribute tool-call causality because sibling-flat topology hides the sequential dependency. The corrective is not a schema change but a collector-side reconciliation pass that reconstructs turn boundaries from span timestamps and agent-root grouping, then collapses chained chat spans to their terminal prefix before any accounting or guard decision. Runtimes that emit an explicit `gen_ai.conversation.turn_index` attribute make this reconstruction deterministic; those that do not force the collector to infer turn boundaries from timing gaps, which is fragile under concurrent tool fan-out. ```python from dataclasses import dataclass from typing import Sequence class LineageCollapseError(RuntimeError): """Raised when a token-accounting decision is requested over a trace whose GenAI spans exhibit cumulative-prefix overlap but no turn boundary attribute, making sum-vs-max ambiguous.""" @dataclass(frozen=True) class GenAISpan: span_id: str parent_id: str | None kind: str # "chat" | "tool" start_ns: int end_ns: int input_tokens: int output_tokens: int turn_index: int | None # gen_ai.conversation.turn_index if present def reconcile_turn_tokens(spans: Sequence[GenAISpan]) -> dict[int, int]: """Return per-turn terminal context occupancy. Collapses chained chat spans to their terminal prefix per turn rather than summing input_tokens across the loop. """ chat_spans = [s for s in spans if s.kind == "chat"] if not chat_spans: raise LineageCollapseError("no gen_ai.chat spans present; cannot reconcile") # Detect chained cumulative prefixes without turn_index. missing_turn = [s for s in chat_spans if s.turn_index is None] if missing_turn: # Chained chat spans ordered by time with monotonic input growth # cannot be safely summed; refuse rather than guess. ordered = sorted(chat_spans, key=lambda s: s.start_ns) monotonic = all( ordered[i + 1].input_tokens >= ordered[i].input_tokens for i in range(len(ordered) - 1) ) if monotonic and len(ordered) > 1: raise LineageCollapseError( "chained gen_ai.chat spans show monotonic prefix growth but " "carry no gen_ai.conversation.turn_index; sum-vs-max is " "ambiguous and additive accounting would double-count the prefix" ) occupancy: dict[int, int] = {} for s in chat_spans: if s.turn_index is None: continue # Terminal span of a turn wins; later start_ns overrides. prev = occupancy.get(s.turn_index) candidate = s.input_tokens + s.output_tokens if prev is None or candidate > prev: occupancy[s.turn_index] = candidate return occupancy def guard_context_budget(spans: Sequence[GenAISpan], ceiling: int) -> None: occupancy = reconcile_turn_tokens(spans) if not occupancy: raise LineageCollapseError("reconciliation produced no turn occupancy") peak = max(occupancy.values()) if peak > ceiling: raise LineageCollapseError( f"terminal context occupancy {peak} exceeds ceiling {ceiling}; " f"do not fall back to summed input_tokens" ) ```