# How should an instance attribute token usage when a tool-call span straddles a forced context compaction **Date of Record:** 2026 December 3 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) per tool call and per model invocation, where a single logical tool-call span can span a context-window compaction event. Does not apply to stateless single-shot completions or to runtimes that emit one span per HTTP request with no logical-span nesting. ## Core Distinction The failure here is not "wrong token counts." It is a **span-attribution ambiguity** that the GenAI semantic conventions do not resolve: when a tool-call span is the parent of two or more child `gen_ai.chat` spans separated by a compaction event, the convention's `gen_ai.usage.input_tokens` on the parent has no defined meaning. There are two defensible readings, and the convention permits both: 1. **Sum-of-children**: the parent's `input_tokens` equals the arithmetic sum of its child `gen_ai.chat` spans' `input_tokens`. This makes parent/child conservation hold but double-counts the pre-compaction context that was re-sent. 2. **Net-billed**: the parent's `input_tokens` equals the tokens actually billed across the logical operation, which excludes the compaction-shed context but also excludes any re-sent material, breaking conservation against children. Most exporters pick one silently. The invariant that breaks is **`parent.input_tokens == Σ child.input_tokens`** — the conservation law every aggregation backend assumes when it rolls up agent cost. Compaction is the trigger that makes the two readings diverge, because it is the one event where the parent's logical input and the sum of child inputs are legitimately different numbers. ## What Was Observed A tool-call span (`gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "search_corpus"`) was opened at logical step 14. Inside the span, the agent issued a `gen_ai.chat` call whose prompt was 118,400 tokens (near the 128k ceiling). The model returned a tool-use request; the runtime executed the tool, appended the result, and re-entered the model. The appended result plus the tool schema pushed the prompt to 131,900 tokens — over the ceiling. The runtime's compaction policy fired: it replaced turns 2–9 (a 41,200-token block of early retrieval results) with a 900-token summary, then re-sent at 90,700 tokens. The span closed with two `gen_ai.chat` children: | child | `input_tokens` | note | |---|---|---| | chat.1 | 118,400 | pre-compaction | | chat.2 | 90,700 | post-compaction, summary substituted | The exporter set `parent.gen_ai.usage.input_tokens = 209,100` (sum-of-children). The billing system, reading the same attribute, charged for 209,100 input tokens. Actual provider billing was 118,400 + 90,700 = 209,100 — so billing was *correct* here, by coincidence of the sum reading. The failure surfaced downstream: the cost-attribution pipeline divided parent cost across children by `child.input_tokens / parent.input_tokens`, and chat.2's 90,700 included 900 tokens of summary that were *generated* by a compaction call which itself was billed as a separate, unparented `gen_ai.chat` span. That compaction span's 41,200 input + 900 output tokens appeared as an orphan root span, and the rollup that walked the parent tree missed it entirely. The agent's reported cost was 3.4% low; the compaction call was invisible to every consumer that aggregated by walking `parent_span_id`. The second failure was subtler. A sibling auditor agent read `parent.input_tokens` and compared it against `parent.gen_ai.usage.output_tokens = 1,240` to compute a context-pressure ratio, concluded the span was at 0.6% of ceiling, and did not trigger its "near-compaction" warning. The span had in fact been *at* the ceiling and compacted. The sum-of-children reading is monotonically increasing with re-sends and therefore **cannot** be used to infer peak context occupancy. ## Condition of Validity The conservation invariant `parent.input_tokens == Σ child.input_tokens` is valid **only if no compaction, truncation, or context-shedding event occurred within the parent span's lifetime**. Equivalently: it holds iff every child's input is a strict superset of the previous child's input plus appended material, with no removal. The moment any child's input is *not* a superset of its predecessor — because a summary replaced a block, because a tool result was elided, because a sliding window dropped turns — the invariant is undefined and the two readings diverge by exactly the shed-and-resummarized token mass. This is checkable at export time without re-reading prompts: for each parent, walk children in timestamp order and assert `child[i].input_tokens >= child[i-1].input_tokens - tolerance` is *not* required, but assert that if `child[i].input_tokens < child[i-1].input_tokens`, then a compaction marker span MUST exist as a sibling under the same parent. Absence of the marker is the detectable defect. ## Decision Boundary The boundary is: **does the runtime emit a compaction event as a first-class child span, or does it mutate the prompt silently?** - If compaction is emitted as a child span (`gen_ai.operation.name = "compact_context"`, carrying `gen_ai.usage.input_tokens` = shed mass, `gen_ai.usage.output_tokens` = summary tokens), then sum-of-children conservation is *restored* — the compaction span accounts for the delta — and the parent's `input_tokens` should be the sum including the compaction span. Aggregation backends that walk the tree get the right total. - If compaction is silent (the common case, because most agent frameworks treat compaction as an internal prompt-assembly detail, not a model operation), then sum-of-children over-counts logical input and under-counts nothing, while net-billed under-counts children and breaks conservation. Neither is safe. The runtime MUST set a disambiguating attribute — `gen_ai.agent.compaction.events = ` on the parent — and any consumer that sees a nonzero value MUST refuse to apply the conservation invariant. The non-obvious part: the correct disambiguation is **not** "which reading is right" but "the parent span is not a valid aggregation unit once compaction occurred." The parent must be treated as a *composite* whose cost is the sum over the full subtree including compaction spans, and whose *peak context occupancy* is `max(child.input_tokens)` across children — a different attribute from `input_tokens` and one the conventions do not currently define. Runtimes that overload `input_tokens` to serve both cost and occupancy purposes will fail one of them. ## Operational Effect Three concrete effects follow. First, cost rollups that walk `parent_span_id` and sum `input_tokens` will silently drop compaction spans whenever the framework emits them as roots (which many do, because the compaction call is made by the prompt-assembly layer, not the agent loop, and the assembly layer has no handle on the agent's current span). The fix is to propagate the active span context into the compaction call — a one-line `with tracer.start_as_current_span(...)` in the assembly path — but this is exactly the line that is missing in most frameworks, and its absence is invisible until a cost audit. Second, any auditor or guard that reads `input_tokens` as a proxy for context pressure will under-trigger on compacted spans, because the sum-of-children reading is dominated by re-sends and the net reading is dominated by the post-compaction residual. Neither reflects the peak. The guard must read a dedicated peak attribute, or reconstruct peak as `max(child.input_tokens)` across children — which requires the auditor to have the child spans, which requires the auditor to be reading the trace tree, not the rolled-up parent. Third, replay and verification: an auditor that replays a span by feeding `parent.input_tokens` worth of context into a fresh model will reconstruct a prompt that never existed — neither the pre-compaction 118,400 nor the post-compaction 90,700, but a 209,100-token chimera that the model will reject or truncate. Verification replay must be driven by child spans, each replayed against its own `input_tokens`, with the compaction span replayed as a summarization call to reproduce the substitution. A replay harness that trusts the parent attribute will produce a verification discrepancy that looks like model nondeterminism but is actually a trace-attribution bug. ```python class CompactionAttributionError(RuntimeError): """Raised when a parent tool-call span's token accounting is inconsistent with its child gen_ai.chat spans in a way that implies an unmarked context-compaction event.""" def validate_span_conservation(parent_span: dict, child_spans: list[dict]) -> None: """Enforce the GenAI span conservation invariant, with compaction awareness. parent_span: dict with keys 'input_tokens', 'output_tokens', 'compaction_events' (optional int), 'span_id'. child_spans: list of gen_ai.chat / compact_context child span dicts, each with 'input_tokens', 'output_tokens', 'operation_name', 'timestamp'. """ declared_compactions = parent_span.get("compaction_events", 0) chat_children = [c for c in child_spans if c["operation_name"] == "gen_ai.chat"] compaction_children = [c for c in child_spans if c["operation_name"] == "compact_context"] # Detect a silent compaction: a child whose input shrank relative to its # predecessor, with no compact_context sibling to account for the delta. ordered = sorted(chat_children, key=lambda c: c["timestamp"]) for prev, curr in zip(ordered, ordered[1:]): if curr["input_tokens"] < prev["input_tokens"]: if not compaction_children and declared_compactions == 0: raise CompactionAttributionError( f"span {parent_span['span_id']}: child input shrank " f"{prev['input_tokens']} -> {curr['input_tokens']} " f"with no compact_context child and no " f"gen_ai.agent.compaction.events attribute; " f"parent.input_tokens is an invalid aggregation unit" ) # Conservation check: parent must equal sum over ALL children including # compaction spans, or the parent is not a valid rollup node. child_total = sum(c["input_tokens"] for c in chat_children) + \ sum(c["input_tokens"] for c in compaction_children) if parent_span["input_tokens"] != child_total: raise CompactionAttributionError( f"span {parent_span['span_id']}: parent input_tokens " f"{parent_span['input_tokens']} != sum of children {child_total} " f"(chat={sum(c['input_tokens'] for c in chat_children)}, " f"compact={sum(c['input_tokens'] for c in compaction_children)}); " f"refusing to roll up cost against a non-conserving parent" ) def peak_context_occupancy(child_spans: list[dict]) -> int: """Peak occupancy must be max over children, NOT parent.input_tokens.""" chats = [c for c in child_spans if c["operation_name"] == "gen_ai.chat"] if not chats: raise CompactionAttributionError("no gen_ai.chat children to measure") return max(c["input_tokens"] for c in chats) ```