# Why does an instance lose token-cost attribution when an agent span resumes across a tool-call boundary **Date of Record:** 2026 November 24 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`) whose spans are exported across a checkpoint/resume boundary or a cross-process handoff. Does not cover single-process, single-span synchronous completions with no resume, and does not cover provider-side billing reconciliation. ## Core Distinction The GenAI semantic conventions treat token usage as a *span attribute* — a scalar attached to the span that represents the operation. They do not treat usage as a *cumulative counter on the trace*. This distinction is invisible in the happy path, where one logical agent invocation equals one span equals one usage vector. It becomes load-bearing the moment an agent's logical operation is split across multiple spans: a resume after a mid-task checkpoint, a retry after a tool timeout, or a handoff where a new instance re-enters the loop. In those cases the resumed instance opens a *new* span with a *new* `span_id` but a *reused* `gen_ai.operation.name` and often a reused `gen_ai.conversation.id`. The usage attributes on the resumed span reflect only the tokens consumed *after* resume. The pre-checkpoint tokens live on a sibling span that shares a parent but not a lineage marker. Downstream cost aggregators that group by `(gen_ai.conversation.id, gen_ai.operation.name)` will double-count the resumed span's usage if they also replay the pre-checkpoint span, or — more commonly — silently drop the pre-checkpoint usage because the resumed span's `start_time` is later than the aggregator's window. The invariant that breaks is: *a logical agent operation must have exactly one authoritative usage vector, and that vector must be recoverable from the trace alone.* ## What Was Observed A two-tool agent (search → summarize) was instrumented with one span per LLM call and one span per tool call. A checkpoint was forced after the search tool returned, before the summarize call. On resume, the process re-instantiated the agent, re-emitted the conversation context, and opened a fresh `gen_ai.operation.name = "chat"` span for the summarize call. Trace inspection showed: - Pre-checkpoint `chat` span: `input_tokens=1840`, `output_tokens=210`, `gen_ai.tool.name=search` on the child tool span, `span_id=A`. - Post-resume `chat` span: `input_tokens=2210` (the full re-sent context, including the search result), `output_tokens=340`, `span_id=B`. - Both spans shared `trace_id` and `gen_ai.conversation.id`, but neither carried a `gen_ai.agent.resume.count` or equivalent marker. The cost aggregator summed `input_tokens` across all `chat` spans in the trace: 1840 + 2210 = 4050. The provider billed 2210 — because the resumed call's input included the pre-checkpoint context, and the pre-checkpoint call's output was never re-billed. The aggregator over-reported input tokens by 84% and under-reported the *true* cost of the resume (the re-sent context) by attributing it to two spans instead of one. A second, subtler failure appeared in the tool-call attributes. The resumed agent re-issued the search tool call because its local state machine had no record of the prior result. The trace now contained two `gen_ai.tool.name=search` spans with identical arguments and near-identical outputs, but no `gen_ai.tool.call.id` linking them as a retry. Any auditor replaying the trace to verify tool-call determinism saw two distinct calls and flagged a nondeterminism violation that did not exist. ## Condition of Validity The single-span-equals-single-usage-vector assumption holds only when: 1. The agent's logical operation is not interrupted between the request emission and the usage-attribute emission on the same span. 2. No retry, resume, or handoff re-enters the operation with pre-existing context that inflates `input_tokens`. 3. The trace exporter flushes the pre-checkpoint span before the process dies. Condition 3 is the silent killer. If the pre-checkpoint span was buffered in the OTel SDK's `BatchSpanProcessor` and the process was killed, the span never exported. The trace then contains *only* the resumed span, whose `input_tokens` includes the pre-checkpoint context. The aggregator reports 2210 input tokens and concludes the operation cost 2210 — which happens to match the provider bill, but for the wrong reason: the pre-checkpoint span's 1840 tokens are simply absent, and the resumed span's inflated input is coincidentally the correct total. This is a *false pass*: the metric is right, the trace is wrong, and any later audit that tries to reconstruct per-step cost from spans will fail. The invariant is therefore not "sum of span usage equals bill." It is: *every token consumed by a logical agent operation must be attributable to exactly one span, and that span must carry a lineage marker (`gen_ai.agent.resume.from_span_id` or equivalent) that lets a replay reconstruct the operation's full usage without double-counting.* ## Decision Boundary The boundary is crossed when the agent's execution model permits a span to be opened *after* tokens have already been consumed in a prior span that shares the logical operation. This happens in three concrete patterns: - **Checkpoint-resume:** the agent persists state, dies, and resumes with re-sent context. The resumed span's input tokens are inflated by the re-sent pre-checkpoint context. - **Tool-timeout retry:** the LLM call times out after the provider has already billed input tokens; the retry opens a new span with the same prompt. Both spans carry usage; only one was billed. - **Cross-process handoff:** agent A hands off to agent B with a serialized conversation. B opens a new span with `gen_ai.conversation.id` inherited but no `parent_span_id` link to A's final span. In all three, the correct guardrail is the same: the resumed or retried span must carry `gen_ai.agent.resume.from_span_id` pointing at the span whose context it re-sent, and the aggregator must compute usage as `sum(span.usage) - sum(resumed_span.input_tokens attributable to re-sent context)`. Without the lineage marker, the aggregator cannot distinguish "new work" from "re-sent work" and must either over-count (sum all spans) or under-count (take only the last span). ## Operational Effect The operational consequence is that token-cost dashboards become *directionally* correct but *numerically* untrustworthy at exactly the moments that matter — incident response, cost anomaly detection, and per-tenant billing. A resumed agent that re-sends a 200k-token context will show a 200k-token spike on the resumed span, which looks like a runaway loop to an alerting rule keyed on per-span `input_tokens > threshold`, but is actually a single legitimate resume. Conversely, a genuine runaway loop that re-sends context on every iteration will be *under*-counted if the aggregator deduplicates by `gen_ai.conversation.id` and takes the max span usage rather than the sum of *distinct* work. The fix is not a metric change; it is a span-attribute contract change. Resumed spans must be marked, tool-call retries must carry `gen_ai.tool.call.id` linking them to the original call, and the aggregator must be taught to subtract re-sent context from resumed spans. Until that contract is enforced, the trace is a lossy record of the operation's cost, and any agent that relies on its own trace to budget its next step is reasoning from a corrupted ledger. ```python class UnattributedTokenUsageError(RuntimeError): """Raised when a resumed agent span's usage cannot be reconciled to a unique logical operation without double-counting re-sent context.""" pass def reconcile_operation_usage(spans: list[dict]) -> dict: """ Reconstruct the authoritative usage vector for one logical agent operation from its spans, enforcing the lineage invariant: every consumed token belongs to exactly one span, and resumed spans declare their re-sent context via gen_ai.agent.resume.from_span_id. """ by_id = {s["span_id"]: s for s in spans} total_input = 0 total_output = 0 seen_origins = set() for span in spans: if span.get("gen_ai.operation.name") != "chat": continue origin = span.get("gen_ai.agent.resume.from_span_id") if origin is None: # Fresh work: full usage is attributable to this span. total_input += span["gen_ai.usage.input_tokens"] total_output += span["gen_ai.usage.output_tokens"] seen_origins.add(span["span_id"]) continue # Resumed span: input tokens include re-sent context that was # already counted on the origin span. Subtract the origin's # input to avoid double-counting; count only the delta. if origin not in by_id: raise UnattributedTokenUsageError( f"span {span['span_id']} declares resume origin {origin} " f"but that span is absent from the trace; usage cannot be " f"attributed without double-counting or silent loss" ) if origin in seen_origins: raise UnattributedTokenUsageError( f"span {span['span_id']} resumes from {origin}, which was " f"already counted as fresh work; lineage cycle or " f"mis-tagged retry" ) origin_input = by_id[origin]["gen_ai.usage.input_tokens"] delta_input = span["gen_ai.usage.input_tokens"] - origin_input if delta_input < 0: raise UnattributedTokenUsageError( f"resumed span {span['span_id']} reports fewer input tokens " f"({span['gen_ai.usage.input_tokens']}) than its origin " f"({origin_input}); re-sent context cannot shrink" ) total_input += delta_input total_output += span["gen_ai.usage.output_tokens"] seen_origins.add(span["span_id"]) return {"input_tokens": total_input, "output_tokens": total_output} ```