# Where must an instance stop attributing cost when its own token stream is the only clock: span-relative attribution drift under streamed generation **Date of Record:** 2026 November 29 **Scope:** Applies to per-agent token-cost and latency attribution built by reading usage counters and inter-token timestamps off a single LLM instance's streamed response, where that instance also emits spans/tool calls multiplexed onto the same logical turn. Does not apply to out-of-band billing reconciliation against provider invoices, nor to batch (non-streamed) calls where usage arrives atomically at completion. ## Core Distinction The distinction that matters is between **wall-clock attribution** and **stream-clock attribution**. Wall-clock attribution timestamps spans and tool calls against a monotonic host clock and subtracts them from a turn boundary. Stream-clock attribution instead infers the turn's internal timeline from the arrival times of tokens on the response stream, treating those arrival times as the only ground truth for "when did generation actually happen." These two clocks diverge in a specific, non-obvious way. When an agent instance is mid-generation and issues a tool call, the provider's stream is *paused* — no tokens flow — while the agent executes the tool. The host wall clock keeps running. The stream clock does not. An attribution layer that prices tokens by `(token_index / total_tokens) * wall_clock_duration` will silently assign the tool-execution gap to the generation phase, inflating per-token latency and mis-billing the tool's own token cost to the LLM span. The invariant that holds in batch mode — *turn duration is generation duration* — is false under streaming with interleaved tool calls, and the observability system must know which clock it is actually reading before it attributes anything. ## What Was Observed A single-agent coding loop generated a 4,200-token plan, paused to invoke a filesystem tool (12.4 s of sandbox execution), then resumed generation for 900 more tokens. The attribution layer reported: - Total turn wall clock: 31.8 s. - Tokens attributed to the generation span: 5,100, at a computed 6.2 ms/token. - Tool span wall clock: 12.4 s, with 0 tokens. The provider's own usage record reported 5,100 completion tokens but a generation-active duration of 19.4 s. The 12.4 s tool gap had been distributed proportionally across every token in the turn, so the first 4,200 tokens each carried a phantom ~2.4 ms of tool latency, and the 900 post-resume tokens carried the same phantom share even though they were generated after the gap had closed. Per-token latency for the resumed segment was reported as 6.2 ms; the true post-resume inter-token interval was 4.1 ms. The error is not a rounding artifact — it is a systematic redistribution of one span's wall time onto another span's tokens, triggered purely by the presence of a mid-turn pause. A second, sharper symptom: when the tool call itself made a nested LLM call (a sub-agent summarizer), the sub-agent's tokens were attributed to the *parent* instance's stream because the parent stream had not yet emitted a segment boundary. The parent was billed for 1,300 tokens it never generated, and the sub-agent's span reported zero cost. This is the failure mode proper: **stream-relative attribution has no concept of a segment boundary that is not marked by a token**, so any pause that spawns a nested generator leaks cost upward. ## Condition of Validity Stream-clock attribution is valid only under the conjunction of three conditions: 1. **No interleaved execution.** The generation span contains no pause during which another span (tool, sub-agent, retrieval) executes. Equivalently: the set of tokens emitted by the instance is contiguous in stream time. 2. **Segment boundaries are token-marked.** Every transition into or out of the instance's generation is accompanied by a stream event (a `tool_use` block start/stop, a `message_delta`, a stop reason) that the attribution layer consumes *before* it assigns the next token. 3. **Usage counters are per-segment.** The provider reports `input_tokens`/`output_tokens` at segment granularity, not per-turn, so that a resumed segment can be reconciled against its own counter rather than the turn total. When any of these fails — and in agentic loops with tool use, condition 1 fails on essentially every turn — the attribution layer must fall back to explicit span bracketing: open a generation segment at the first token, close it at the pause event, and refuse to attribute the gap to either span until the executing span reports its own usage. The invariant to enforce is a **segment-closure invariant**: *no token may be attributed to a span whose segment was not open at the token's arrival time.* Violating it is the root cause of every drift above. ## Decision Boundary The decision boundary is the pause event. Before the pause, the instance's stream is the authoritative clock and per-token latency is well-defined as the inter-arrival delta. At the pause, the stream clock stops being a clock at all — it becomes a *sequence*, and only the host clock plus the executing span's own telemetry can price the interval. The boundary rule: - If a pause event is observed and the executing span has not yet reported usage, the attribution layer must **hold** the turn open and emit an `attribution_pending` state, not a computed cost. - If a nested generator is detected (a new stream opened while the parent stream is paused), the parent must be marked **non-attributable** for the nested span's tokens; the nested instance owns them. - If the provider reports per-turn usage only (condition 3 fails), the layer must refuse to split the turn and report a single turn-level cost with an explicit `granularity: turn` marker rather than fabricate per-token numbers. The failure to enforce this boundary is what produced the 1,300-token leak: the layer had no `attribution_pending` state, so it defaulted to "attribute to the currently open parent stream," which is the wrong default precisely when a nested generator exists. ## Operational Effect The operational effect is that **cost dashboards built on stream-clock attribution under-report sub-agent cost and over-report parent generation latency, and the error is correlated with tool-use frequency rather than with volume.** A high-tool-use agent will show inflated per-token latency and understated sub-agent spend; a low-tool-use agent will look accurate. This makes the metric useless for the one decision it is usually built to serve — deciding whether to split a workload across more agents — because splitting increases tool-call frequency and therefore increases the drift, making the split look more expensive than it is. The guardrail is to instrument the pause explicitly and make the attribution layer's default state `attribution_pending` rather than "attribute to open span." Concretely, the layer must raise on any attempt to price a token whose segment was not open at arrival, and must surface the turn as `granularity: turn` rather than fabricate segment numbers when the provider does not cooperate. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum class AttributionDriftError(RuntimeError): """Raised when a token is priced against a span whose segment was not open at the token's arrival time, or when a nested generator's tokens are attributed to a paused parent stream.""" class SegmentState(Enum): OPEN = "open" PAUSED = "paused" CLOSED = "closed" @dataclass class Segment: span_id: str state: SegmentState = SegmentState.OPEN token_count: int = 0 generation_active_ns: int = 0 pending_nested: bool = False @dataclass class AttributionLedger: segments: dict[str, Segment] = field(default_factory=dict) granularity: str = "token" def open_segment(self, span_id: str) -> Segment: seg = Segment(span_id=span_id) self.segments[span_id] = seg return seg def pause(self, span_id: str, nested_generator: bool = False) -> None: seg = self.segments[span_id] seg.state = SegmentState.PAUSED seg.pending_nested = nested_generator def resume(self, span_id: str) -> None: seg = self.segments[span_id] seg.state = SegmentState.OPEN seg.pending_nested = False def attribute_token(self, span_id: str, inter_token_ns: int) -> None: seg = self.segments.get(span_id) if seg is None: raise AttributionDriftError(f"no segment for span {span_id}") if seg.state is not SegmentState.OPEN: # The exact invariant: a token may only be priced against a # segment that was open at the token's arrival time. raise AttributionDriftError( f"token arrived for span {span_id} in state {seg.state.value}; " f"refusing to attribute across a pause boundary" ) seg.token_count += 1 seg.generation_active_ns += inter_token_ns def close_turn(self, span_id: str, provider_turn_tokens: int, provider_segment_tokens: int | None) -> dict: seg = self.segments[span_id] seg.state = SegmentState.CLOSED if provider_segment_tokens is None: # Condition 3 failed: cannot split the turn honestly. self.granularity = "turn" return { "span_id": span_id, "granularity": "turn", "tokens": provider_turn_tokens, "note": "provider did not report per-segment usage; " "per-token attribution suppressed", } if provider_segment_tokens != seg.token_count: raise AttributionDriftError( f"segment token mismatch for {span_id}: " f"streamed {seg.token_count}, provider {provider_segment_tokens}" ) return { "span_id": span_id, "granularity": "token", "tokens": seg.token_count, "generation_active_ns": seg.generation_active_ns, "per_token_ns": seg.generation_active_ns / max(seg.token_count, 1), } def price_turn(ledger: AttributionLedger, span_id: str, *, provider_turn_tokens: int, provider_segment_tokens: int | None) -> dict: seg = ledger.segments.get(span_id) if seg is None: raise AttributionDriftError(f"unknown span {span_id}") if seg.pending_nested: raise AttributionDriftError( f"span {span_id} has a pending nested generator; " f"parent cost cannot be closed until child reports usage" ) return ledger.close_turn(span_id, provider_turn_tokens, provider_segment_tokens) ```