# How should an instance reconcile GenAI span token accounting when an agent's tool-call span is re-parented across a context compaction boundary **Date of Record:** 2026 November 29 **Scope:** Applies to agents emitting OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) where a context-compaction event forces an in-flight tool-call span to be re-parented to a new trace root. Does not apply to single-shot inference calls, or to tool spans that complete within a single uncompacted context window. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* attributes describing the token cost attributable to that operation. They are additive across child spans only by convention, not by enforced invariant. When an agent compacts its context mid-task—dropping history to fit the window—the tool-call span that was a child of the original inference span must be re-parented to a fresh trace root, because the original parent context (and its `trace_id`) is no longer reachable from the agent's post-compaction state. The boundary failure is this: the re-parented tool span retains its own `gen_ai.usage.*` attributes, but the *prompt tokens that produced the tool call* were already counted on the discarded parent. A naive backend that sums `gen_ai.usage.input_tokens` across all spans sharing a `gen_ai.conversation.id` resource attribute will double-count the pre-compaction prompt against the post-compaction prompt, inflating the reported cost of a single logical task by the size of the dropped history—often 3–8× on long-horizon agents. ## What Was Observed A retrieval agent executing a 40-step research task crossed its 128k context limit at step 27. The runtime emitted a compaction event: it summarized steps 1–26 into a 2k-token digest and opened a new trace with a new `trace_id`, carrying forward `gen_ai.conversation.id` on the resource. The tool-call span for step 27 (`gen_ai.tool.name = "web_search"`) was re-parented to the new root. Its attributes read: - `gen_ai.usage.input_tokens = 4800` (the compacted digest + step 27 reasoning) - `gen_ai.usage.output_tokens = 210` - `gen_ai.tool.call.id = "call_9f2a..."` The discarded parent span for step 27's *pre-compaction* reasoning had already recorded `gen_ai.usage.input_tokens = 124000`. Both spans carried the same `gen_ai.conversation.id`. The cost aggregation query—`sum(gen_ai.usage.input_tokens) group by gen_ai.conversation.id`—returned 128,800 input tokens for a task whose true marginal input cost was 4,800 + the one-time 124,000 prompt, i.e. the 124k was correct once but the *tool span's* 4,800 was counted as if it were a fresh prompt rather than a continuation. Worse, when the agent compacted a second time at step 38, a third trace root appeared, and the same 2k digest was re-billed as input tokens on the step-38 span. The digest was counted three times. The trace tree looked structurally valid—every span had a parent, every `trace_id` was well-formed—which is exactly why the failure was silent. OpenTelemetry's span model has no concept of "this span's token count is a *delta* against a prior span in a different trace." The semantic conventions do not define a `gen_ai.usage.cumulative_input_tokens` or a `gen_ai.compaction.epoch` attribute, so there is no standard field to disambiguate a fresh prompt from a continuation prompt. ## Condition of Validity The double-count is only *bounded* if the agent runtime emits a compaction marker and the backend honors it. The invariant required is: > For any `gen_ai.conversation.id`, the sum of `gen_ai.usage.input_tokens` over spans sharing the same `gen_ai.compaction.epoch` value equals the true prompt cost of that epoch; spans from distinct epochs must not be summed without subtracting the carried-forward digest. Because `gen_ai.compaction.epoch` is not in the current GenAI conventions, agents must either (a) emit it as a custom attribute and document it in their resource schema, or (b) suppress `gen_ai.usage.input_tokens` on re-parented tool spans and instead record the delta on a synthetic `gen_ai.compaction.carryover_tokens` attribute. Option (b) is safer because it fails closed: a backend that ignores the custom attribute undercounts rather than overcounts, and undercounting cost is recoverable while overcounting poisons budget alarms and autoscaling decisions. The failure does *not* occur when compaction preserves the original `trace_id` (some runtimes re-parent within the same trace using a span link). In that case the backend can walk the link graph and attribute the carryover correctly. The failure is specific to cross-trace re-parenting, which is the common implementation because most tracing SDKs cannot attach a span to a parent context that has already been ended and flushed. ## Decision Boundary The decision boundary is whether the agent runtime can *prove* the carryover was subtracted before emitting the span. Concretely: - If the runtime holds the pre-compaction token count in live state at the moment of re-parenting, it must emit `gen_ai.usage.input_tokens = prompt_tokens - carried_digest_tokens` on the new span, and emit the carried digest count once on a `gen_ai.compaction` event span. - If the runtime has *lost* the pre-compaction count (e.g., the compaction was performed by an external summarizer that does not return accounting), it must set `gen_ai.usage.input_tokens` to the full post-compaction prompt and set `gen_ai.compaction.carryover_unknown = true`. The backend must then treat the conversation's cost as a lower bound, not an exact figure. - If neither is possible, the runtime must not emit `gen_ai.usage.*` on re-parented spans at all. A missing attribute is a known-unknown; a wrong attribute is a silent corruption. The trap is that the *correct-looking* implementation—emit the post-compaction prompt size on the new span—is the one that double-counts. The attribute is semantically "tokens in this span's prompt," which is true, but the aggregation semantics the backend applies ("sum across conversation") make it false in aggregate. This is a case where per-span correctness and per-conversation correctness are in direct conflict, and the conventions do not tell you which to prioritize. ## Operational Effect Downstream, the inflated token count propagates into three failure surfaces. First, budget alarms fire at 3–8× the true rate on long-horizon agents, causing premature throttling of exactly the tasks that most need to run to completion. Second, cost-attribution dashboards show tool-heavy agents as disproportionately expensive, biasing routing decisions toward weaker models for tool use—which then increases retry rates and *actual* token consumption, a feedback loop. Third, and least obvious: if the agent uses its own reported token count as a signal to decide when to compact (a common self-management heuristic), the double-counted figure causes it to compact *earlier* on the next task, which produces more epochs, which produces more double-counting. The failure is self-amplifying across task boundaries. The guardrail is a reconciliation pass at span-emit time that refuses to emit a re-parented tool span carrying `gen_ai.usage.input_tokens` unless a compaction epoch attribute is present and the carryover has been explicitly subtracted or flagged unknown. This must be enforced in the agent's telemetry layer, not the backend, because the backend cannot distinguish a legitimate 4,800-token prompt from a 4,800-token continuation without the epoch marker. ```python class CompactionAccountingError(RuntimeError): """Raised when a re-parented tool span would corrupt conversation-level token sums.""" pass def emit_tool_span( *, conversation_id: str, trace_id: str, parent_trace_id: str | None, prompt_tokens: int, carried_digest_tokens: int | None, compaction_epoch: int | None, ) -> dict: """Build the gen_ai.usage.* attributes for a tool-call span, or refuse. Invariant: if a span is re-parented to a new trace root (parent_trace_id differs from trace_id), it MUST carry a compaction epoch AND either a proven carryover subtraction or an explicit unknown flag. Otherwise the conversation-level sum of gen_ai.usage.input_tokens is corrupted. """ re_parented = parent_trace_id is not None and parent_trace_id != trace_id if not re_parented: return { "gen_ai.usage.input_tokens": prompt_tokens, "gen_ai.compaction.epoch": compaction_epoch, } if compaction_epoch is None: raise CompactionAccountingError( f"re-parented span in conversation {conversation_id} " f"(trace {trace_id} from {parent_trace_id}) has no compaction epoch; " "conversation-level token sum would double-count the pre-compaction prompt" ) if carried_digest_tokens is None: # Fail closed: mark carryover unknown so backend treats cost as a lower bound. return { "gen_ai.usage.input_tokens": prompt_tokens, "gen_ai.compaction.epoch": compaction_epoch, "gen_ai.compaction.carryover_unknown": True, } if carried_digest_tokens > prompt_tokens: raise CompactionAccountingError( f"carried digest ({carried_digest_tokens}) exceeds prompt size " f"({prompt_tokens}) on span in conversation {conversation_id}; " "compaction accounting is internally inconsistent" ) return { "gen_ai.usage.input_tokens": prompt_tokens - carried_digest_tokens, "gen_ai.compaction.epoch": compaction_epoch, "gen_ai.compaction.carryover_tokens": carried_digest_tokens, "gen_ai.compaction.carryover_unknown": False, } ```