# Why does an instance lose tool-call lineage when OpenTelemetry GenAI spans batch token accounting across a mid-execution context compaction? **Date of Record:** 2026 December 1 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*`) for tool invocations while a context-management layer compacts or truncates history mid-run. Does not apply to single-shot, non-tool-using inference calls or to agents whose context never exceeds the window. ## Core Distinction The GenAI semantic conventions treat a span as the atomic unit of attribution: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are recorded per span, and tool lineage is expressed through parent/child span relationships plus `gen_ai.tool.name` / `gen_ai.tool.call.id`. This model assumes the *content* of a span's input is stable for the life of the span. Context compaction violates that assumption: it rewrites the conversation history that a *later* tool-call span will send as its input, but the token counters of *earlier* spans were already flushed and are immutable. The distinction that matters operationally is between **span-local token accounting** (what one call consumed) and **run-level lineage reconstruction** (which tool output fed which later decision). Compaction preserves neither cleanly: it invalidates the reconstruction while leaving the arithmetic untouched, so dashboards look healthy while lineage is silently broken. ## What Was Observed An agent running a 40-step tool loop hit ~92% of a 128k context window at step 22. The context manager triggered a summarization pass: it replaced steps 1–18's raw tool outputs with a ~1.8k-token summary, then resumed. Spans continued to be emitted normally. Two anomalies appeared downstream: 1. **Lineage orphaning.** A tool-call span at step 26 carried `gen_ai.tool.call.id` referencing a prior call whose output had been evicted by compaction. The parent span link resolved (span IDs are preserved in the trace), but the *referenced content* no longer existed anywhere in the trace or the active context. Trace-UI "click-through to the tool result that produced this input" dead-ended. The lineage edge was structurally present and semantically dangling. 2. **Token-accounting divergence.** Summing `gen_ai.usage.input_tokens` across all spans overcounted the run's actual cost by ~23%, because steps 19–40 each re-sent the *compacted* history whose tokens were already billed once in the pre-compaction spans. The per-span numbers were individually correct; the run-level sum double-counted the summary and the retained tail. Conversely, a naive "sum of outputs" undercounted because the summarizer's own token spend was emitted under a generic span with no `gen_ai` attributes at all — the compaction step was invisible to GenAI accounting. The failure is non-obvious because nothing errors. Spans are valid, IDs resolve, totals reconcile to *something*. The corruption is in the *semantics* of the aggregates and the *reachability* of lineage edges. ## Condition of Validity The invariant that holds in the absence of compaction: **for any tool-call span S, the token count on S equals the tokens of the input actually presented at S, and every `gen_ai.tool.call.id` referenced by S resolves to a span whose recorded output is still retrievable.** Compaction breaks the second clause unconditionally (evicted outputs are gone) and breaks the first clause's *additivity* (retained tail is re-billed across every subsequent span). The invariant is only restorable if the compaction event is itself modeled as a first-class span that (a) records tokens in and out, (b) declares which call IDs it evicted, and (c) is linked as a parent to the post-compaction spans so lineage is *redirected* through the summary rather than left dangling. Without that span, no downstream consumer can distinguish "call ID never existed" from "call ID was compacted away." ## Decision Boundary The boundary is whether the accounting consumer needs **per-span truth** or **run-level truth**, and whether lineage consumers tolerate dangling edges. - If only per-span cost attribution is needed (e.g., chargeback per tool), the immutable flushed spans are correct — do nothing. - If run-level cost or lineage reconstruction is needed, the un-instrumented compaction step is a hard failure: you cannot recover the evicted outputs, and you cannot de-duplicate the re-billed tail without knowing the compaction boundary. - The decision rule: **the moment a context manager mutates history that a future span will re-send, it must emit a `gen_ai.compaction` span carrying `input_tokens`, `output_tokens`, and `evicted_tool_call_ids`.** Absent that span, treat any run-level token sum spanning a compaction as *unreconcilable* and refuse to publish it rather than publish a plausible-but-wrong number. ## Operational Effect Teams that skip the compaction span get dashboards that are confidently wrong: lineage graphs with edges that resolve to nothing, and cost totals that drift upward with every compaction cycle in proportion to how much retained history is re-sent. The fix is cheap but must be enforced at emit time, because the information needed to reconcile (which call IDs were evicted, how many tokens the summary cost) exists only at the instant of compaction and is destroyed immediately after. The guardrail below fails the *emission* of a post-compaction tool span when the compaction event was not recorded, converting a silent semantic corruption into a loud, localized error at the only point where it can still be repaired. ```python from dataclasses import dataclass, field class LineageAccountingError(RuntimeError): """Raised when a GenAI span would be emitted across an unrecorded compaction boundary.""" @dataclass class CompactionEvent: evicted_tool_call_ids: set[str] input_tokens: int output_tokens: int recorded: bool = True @dataclass class RunLedger: live_tool_call_ids: set[str] = field(default_factory=set) compaction: CompactionEvent | None = None billed_input_tokens: int = 0 def emit_tool_span(self, call_id: str, referenced_ids: list[str], input_tokens: int) -> None: # A referenced ID that is neither live nor explained by a compaction event # produces a dangling lineage edge we cannot reconcile. for ref in referenced_ids: if ref not in self.live_tool_call_ids: if self.compaction is None or not self.compaction.recorded: raise LineageAccountingError( f"tool span {call_id} references {ref}, which is not live and " f"has no recorded compaction event to explain its eviction" ) if ref not in self.compaction.evicted_tool_call_ids: raise LineageAccountingError( f"tool span {call_id} references {ref}, evicted-set does not " f"contain it; lineage edge is unreconstructable" ) self.billed_input_tokens += input_tokens self.live_tool_call_ids.add(call_id) def compact(self, evicted: set[str], in_tok: int, out_tok: int) -> None: # The compaction itself must be billed and its evictions declared, or # every later span that re-sends the retained tail double-counts. self.compaction = CompactionEvent(evicted_tool_call_ids=evicted, input_tokens=in_tok, output_tokens=out_tok) self.billed_input_tokens += in_tok + out_tok self.live_tool_call_ids -= evicted def run_total(self) -> int: if self.compaction is not None and not self.compaction.recorded: raise LineageAccountingError("cannot publish run total across unrecorded compaction") return self.billed_input_tokens # Misuse: compaction happened but was never recorded, then a later span re-sends history. ledger = RunLedger() ledger.live_tool_call_ids = {"call_a"} ledger.live_tool_call_ids.discard("call_a") # evicted without a CompactionEvent ledger.emit_tool_span("call_b", ["call_a"], 4200) # raises LineageAccountingError ```