# Under what conditions must an instance refuse to emit `gen_ai.tool.call.id` lineage when token attribution crosses a compaction boundary **Date of Record:** 2026 November 29 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single logical tool-call lineage spans a context-compaction or checkpoint/resume event and per-token cost must be attributed back to the originating `gen_ai.tool.call.id`. Does not apply to single-turn, single-span invocations where the tool call and its completion share one span envelope. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` and `gen_ai.tool.call.id` as sibling attributes on a span. Cost attribution tooling downstream assumes this sibling relationship is *stable across the span's lifetime*: the `tool.call.id` on the span that carries the usage counters is presumed to be the same `tool.call.id` the model actually invoked. That presumption breaks at compaction. When an agent compacts its context mid-task, the tool call that originally produced a given chunk of tokens is no longer present in the active context window; the tokens that flow into the *next* LLM span are a mixture of (a) replayed/compacted summary tokens attributable to the original call and (b) fresh tokens attributable to whatever call the model makes next. Emitting a single `gen_ai.tool.call.id` on that post-compaction span silently *re-parents* the summary tokens to the new call. The distinction that matters: **lineage is a property of the token, not of the span.** A span that carries tokens from more than one originating call has no single valid `tool.call.id`, and emitting one is a false invariant, not a lossy approximation. ## What Was Observed Trace from a 14-step research agent, single OTel trace, `gen_ai.client.invoke_agent` root span. At step 9 the context hit 92% of the model's window; the orchestrator triggered summarization. The summarization itself was a separate `gen_ai.chat` span with correct usage counters. But the *next* invocation — step 10, a `gen_ai.tool.call` span for `web_search` — carried `gen_ai.usage.input_tokens = 18,442`, of which roughly 11,900 were the compacted summary of steps 1–8 and only ~6,500 were the fresh step-10 prompt. The span exported `gen_ai.tool.call.id = "call_10_websearch"`. Downstream attribution reported step 10's `web_search` as consuming 18.4k input tokens at the tool-call level. Replaying the trace, the step-10 tool call's *own* prompt was 6.5k tokens; the remaining 11.9k belonged to calls 1–8, whose spans were already closed and whose usage was already accounted. The result was double-counting in the cost ledger (steps 1–8 counted once on their own spans, once again folded into step 10) and a phantom "expensive tool call" that never happened. The failure is silent. No OTel validation error fires because `gen_ai.tool.call.id` is a valid string and `gen_ai.usage.input_tokens` is a valid int. The invariant violation is only visible when you reconcile the sum of per-call input tokens against the sum of per-span input tokens across the trace and find they disagree by exactly the compacted prefix. ## Condition of Validity A span may legitimately emit `gen_ai.tool.call.id` alongside usage counters **iff** every input token counted on that span was contributed by the prompt assembled for that specific call. This holds when: 1. The span's prompt was assembled from the live context window with no summarized or replayed prefix, **or** 2. The span explicitly partitions usage via a non-standard attribute (e.g., `genai.attribution.replayed_tokens` vs `genai.attribution.fresh_tokens`) and the `tool.call.id` refers only to the fresh partition. It does **not** hold when a compaction, checkpoint restore, or memory-injection step has spliced tokens from earlier calls into the current prompt. The condition is checkable: compare the span's `gen_ai.usage.input_tokens` against the token count of the live, un-compacted portion of the prompt. If they differ by more than the tokenizer's rounding tolerance, the span is contaminated and lineage must be withheld or partitioned. ## Decision Boundary The boundary is a single boolean the emitter must evaluate *before* setting `gen_ai.tool.call.id`: - **Clean span** (no replayed prefix): emit `gen_ai.tool.call.id` and full `gen_ai.usage.*`. Cost attribution is sound. - **Contaminated span** (replayed prefix present): either (a) omit `gen_ai.tool.call.id` and emit only aggregate usage with a `genai.lineage.ambiguous = true` marker, or (b) emit partitioned usage attributes and scope `tool.call.id` to the fresh partition. Emitting a single `tool.call.id` with unpartitioned usage is the boundary violation. The subtle part: the emitter cannot decide this from the span alone. It needs the prompt-assembly layer to report how many tokens came from replay. That report must be plumbed as a span attribute *before* the usage counters are finalized, because the OTel SDK flushes on span end and there is no post-hoc correction. ## Operational Effect When the boundary is respected, per-tool-call cost is reconcilable: summing `gen_ai.usage.input_tokens` over spans grouped by `gen_ai.tool.call.id` equals the trace-level total minus explicitly-marked replayed tokens. When violated, cost dashboards drift upward monotonically with compaction frequency — a long-running agent that compacts every N steps will show inflated per-call costs that grow with task length, and the inflation is indistinguishable from genuine prompt growth unless you have the replay marker. The practical guardrail is to make `tool.call.id` conditional on a prompt-provenance flag the assembler sets, and to fail the span export loudly (not silently drop the attribute) when a contaminated span attempts to claim lineage. ```python class LineageAttributionError(RuntimeError): """Raised when a GenAI span attempts to claim tool-call lineage over tokens that were not contributed by that call's own prompt.""" pass def emit_tool_call_span( tool_call_id: str, total_input_tokens: int, fresh_input_tokens: int, replayed_input_tokens: int, tokenizer_tolerance: int = 3, ) -> dict: """Build the gen_ai.* attribute dict for a tool-call span. Enforces the invariant: a span may carry gen_ai.tool.call.id only if every input token it reports was contributed by this call's prompt. """ if fresh_input_tokens + replayed_input_tokens != total_input_tokens: raise LineageAttributionError( f"usage partition does not sum: fresh={fresh_input_tokens} " f"replayed={replayed_input_tokens} total={total_input_tokens}" ) attrs = { "gen_ai.usage.input_tokens": total_input_tokens, "gen_ai.usage.fresh_input_tokens": fresh_input_tokens, "gen_ai.usage.replayed_input_tokens": replayed_input_tokens, } contaminated = replayed_input_tokens > tokenizer_tolerance if contaminated: # Lineage is ambiguous: refuse to re-parent replayed tokens. attrs["genai.lineage.ambiguous"] = True if fresh_input_tokens == 0: raise LineageAttributionError( f"span for {tool_call_id} is entirely replayed tokens; " "no legitimate tool.call.id can be claimed" ) # Scope lineage to the fresh partition only, explicitly partitioned. attrs["gen_ai.tool.call.id"] = tool_call_id attrs["genai.attribution.scope"] = "fresh_partition_only" else: attrs["gen_ai.tool.call.id"] = tool_call_id attrs["genai.attribution.scope"] = "full_span" return attrs def reconcile_trace_cost(spans: list[dict]) -> int: """Sum per-call input tokens and assert it matches per-span totals minus explicitly-marked replayed tokens.""" per_call = 0 per_span = 0 replayed = 0 for s in spans: per_span += s.get("gen_ai.usage.input_tokens", 0) replayed += s.get("gen_ai.usage.replayed_input_tokens", 0) if "gen_ai.tool.call.id" in s: scope = s.get("genai.attribution.scope") if scope == "fresh_partition_only": per_call += s.get("gen_ai.usage.fresh_input_tokens", 0) elif scope == "full_span": per_call += s.get("gen_ai.usage.input_tokens", 0) else: raise LineageAttributionError( f"span claims tool.call.id without attribution scope: {s}" ) if per_call != per_span - replayed: raise LineageAttributionError( f"cost ledger drifted: per_call={per_call} " f"per_span={per_span} replayed={replayed}" ) return per_call ```