# Why does an instance lose span lineage when gen_ai.* attributes are emitted after a mid-invocation context compaction? **Date of Record:** 2026 November 29 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) and prompt/completion events from within a single logical invocation whose context window is compacted, truncated, or re-summarized mid-flight. Does not apply to stateless single-shot inference where the span is opened and closed around one provider call with no intervening context mutation. ## Core Distinction The GenAI semantic conventions assume a **span is a stable, monotonic record of one model invocation**: `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the `gen_ai.content.prompt` / `gen_ai.content.completion` events are treated as attributes of a single, immutable unit of work. The convention's implicit invariant is that **the attributes describing an invocation are a function of the invocation, not of the runtime state at emission time.** That invariant is false the moment an agent compacts its own context mid-invocation. A compaction (summarize-and-truncate, sliding-window eviction, or scratchpad distillation) mutates the very payload the span is supposed to describe. If the span is *closed* after compaction, the emitted `gen_ai.content.prompt` event no longer reflects the prompt that was actually sent to the model — it reflects the post-compaction remainder. The span is well-formed, passes schema validation, and is silently wrong. This is not a crash; it is a **lineage discontinuity** that corrupts cost attribution, replay, and eval datasets downstream. ## What Was Observed A tool-using agent (ReAct loop, ~14 tool calls per task) opened a parent span `gen_ai.invoke` at task start and emitted prompt/completion events per turn. On tasks exceeding ~90% of the model's context limit, a compaction step fired between turn *n* and turn *n+1*. The observed trace: 1. Turn *n* emits `gen_ai.content.prompt` with 61,204 tokens of history (correct). 2. Compaction replaces turns 1..*n-3* with a 900-token summary. 3. Turn *n+1* emits `gen_ai.content.prompt` with 4,317 tokens — but the span's `gen_ai.usage.input_tokens` was recorded as a **cumulative sum** by the instrumentation shim, not per-turn, yielding 65,521. 4. The parent span closes. `gen_ai.usage.input_tokens=65,521` but the union of all prompt events sums to ~65,521 only if you accept the pre-compaction payloads, which were never actually re-sent. The failure signature: **sum(prompt-event tokens) ≠ gen_ai.usage.input_tokens**, and worse, the *content* of the prompt events is a mix of pre- and post-compaction payloads that no single model call ever saw. Replay against these events produces a different trajectory than the original run. Eval harnesses that reconstruct prompts from `gen_ai.content.prompt` events observed a 12–31% divergence in reconstructed vs. actual input on compacted tasks, and a systematic underestimate of input-token cost when the shim summed per-turn usage instead of trusting the provider's `usage` block. A second, subtler artifact: `gen_ai.request.model` was correct, but the *effective* model behavior changed because the post-compaction prompt was shorter and the model's output distribution shifted (shorter completions, more tool calls). The span recorded one model, one invocation, one usage total — masking that the invocation was actually two distinct context regimes. ## Condition of Validity The GenAI conventions are valid **only when the following holds for the span's lifetime**: no operation mutates the prompt payload or the context window between span open and the emission of its final `gen_ai.content.*` event and usage attributes. Concretely: - The span must be **closed before** any compaction, summarization, eviction, or re-prompting that changes what the model sees. - `gen_ai.usage.*` must be **per-provider-call**, taken from the response `usage` block, never accumulated across calls within one span. - Prompt/completion events must be emitted **at the moment of the call**, capturing the exact payload sent, before any post-processing. When compaction is unavoidable mid-task (it is, for long-horizon agents), the invariant must be restored by **segmenting the invocation**: each provider call gets its own child span, and the parent span carries only aggregate attributes that are explicitly defined as sums across children (and are named as such, not as `gen_ai.usage.*`). ## Decision Boundary Choose the segmentation strategy at the point where the runtime *knows* it will mutate context: | Condition | Action | |---|---| | Context stable for the whole span | Emit `gen_ai.*` attributes directly on the invocation span; single prompt/completion event pair. | | Compaction will fire (predicted by token budget) | Close current span; open a new child span per provider call; parent carries no `gen_ai.usage.*`, only custom aggregate attributes (`agent.total_input_tokens`). | | Compaction fires unexpectedly (budget overrun) | Do **not** retroactively rewrite the open span. Emit a `gen_ai.compaction` event marking the discontinuity, close the span, and open a new one. Never let one span straddle a compaction. | | Replay/eval reconstruction | Reconstruct only from per-call child spans; treat parent aggregates as advisory, never as ground truth for prompt content. | The boundary is **"one span = one model-visible payload."** Crossing it without segmentation is the failure. ## Operational Effect Downstream consumers inherit the corruption: - **Cost attribution** double-counts or under-counts input tokens depending on whether the shim summed per-turn or trusted the provider `usage` block. Observed 8–19% cost error on compacted tasks. - **Replay/eval** reconstructs a prompt the model never saw, so regression suites pass on traces that don't correspond to the run that produced them. - **Anomaly detection** on `gen_ai.usage.input_tokens` fires false positives when a compaction legitimately drops the per-turn count, because the aggregate sum looks like a spike relative to the last prompt event. - **Lineage** — the ability to trace a completion back to the exact input — is broken, which is precisely the property the GenAI conventions exist to provide. The guardrail is structural: enforce the span-per-payload invariant in the instrumentation layer, fail closed when a compaction is detected inside an open `gen_ai.*` span, and never emit `gen_ai.usage.*` as a cumulative quantity. ```python class GenAICompactionLineageError(RuntimeError): """Raised when a gen_ai.* span would straddle a context compaction, violating the one-span-one-payload invariant of the GenAI conventions.""" def emit_genai_span(span, prompt_tokens: int, payload_hash: str, compacted: bool) -> None: if compacted: raise GenAICompactionLineageError( f"span {span.name!r} would close after a context compaction; " f"payload_hash={payload_hash} no longer matches the prompt the model saw. " "Close the span before compaction and open a new per-call child span." ) span.set_attribute("gen_ai.usage.input_tokens", prompt_tokens) span.set_attribute("gen_ai.content.prompt.hash", payload_hash) def close_invocation(span, prompt_tokens: int, payload_hash: str, compaction_fired: bool) -> None: try: emit_genai_span(span, prompt_tokens, payload_hash, compaction_fired) except GenAICompactionLineageError: span.add_event("gen_ai.compaction", {"gen_ai.compaction.reason": "mid_invocation"}) span.end() raise span.end() ```