# Why does an instance's per-turn cost attribution silently drift when a multi-turn trajectory is replayed from a mid-conversation checkpoint **Date of Record:** 2026 November 25 **Scope:** Applies to GenAI observability pipelines that attribute token/cost metrics to individual turns of a multi-turn agent trajectory by reconstructing turns from a persisted checkpoint plus a partial event log. Does not apply to single-turn inference, nor to systems that persist the full turn ledger atomically with each model call. ## Core Distinction There are two fundamentally different things an observability system can mean by "turn cost": 1. **Marginal turn cost** — the tokens billed for the specific request/response pair generated at turn *N*, given the exact context that was sent. 2. **Trajectory-attributed cost** — the cost assigned to turn *N* after the trajectory is reconstructed (replayed) from a checkpoint. These diverge the moment a trajectory is resumed from a checkpoint rather than replayed from turn 0. The marginal cost of turn *N* is fixed at generation time and immutable. The trajectory-attributed cost of turn *N* is a *reconstruction artifact*: it depends on what context the replayer believes was present. When the checkpoint captures the message history but the replayer re-serializes it differently — different system-prompt framing, re-summarized tool outputs, dropped `reasoning` blocks, re-ordered tool-call/result pairs — the reconstructed prompt for turn *N* is not the prompt that was actually billed. Cost attribution then attributes turn *N*'s observed `usage.prompt_tokens` to a reconstructed context whose token count differs, and the per-turn ledger no longer sums to the trajectory total. The non-obvious part: **the totals still reconcile at the trajectory level.** The sum of per-turn attributed costs equals the sum of marginal costs, because the replayer reads the same `usage` fields. The drift is purely *internal redistribution* — cost is silently moved between turns. This is why the failure survives naive reconciliation checks and only surfaces under per-turn analysis (e.g., "which turn caused the cost spike"). ## What Was Observed A support-triage agent runs 14 turns. At turn 9 the process is preempted; the orchestrator persists a checkpoint containing the message array and resumes. The observability pipeline reconstructs turns 1–14 by re-fetching the checkpoint and replaying the event log from turn 9 onward. Observed ledger after reconstruction: | Turn | Actual prompt_tokens | Attributed prompt_tokens | Delta | |------|---------------------|--------------------------|-------| | 7 | 6,120 | 6,120 | 0 | | 8 | 6,540 | 6,540 | 0 | | 9 | 7,010 | 5,880 | −1,130 | | 10 | 7,460 | 7,460 | 0 | | 11 | 7,910 | 7,910 | 0 | Trajectory total attributed = trajectory total marginal (both 98,240). But turn 9 shows a 1,130-token deficit. Root cause: the checkpoint serializer stripped the `reasoning` content blocks from assistant messages (a cost-saving measure in the persistence layer), and the replayer re-serialized the turn-9 prompt without them. The replayer's tokenizer counted 5,880; the provider billed 7,010. The 1,130-token gap is the reasoning blocks that were present in the *real* prompt but absent from the *reconstructed* one. Because the replayer attributed the *billed* `usage.prompt_tokens` (7,010) to a turn it believed was 5,880, it internally reallocated the difference to adjacent turns during its cost-normalization pass — a per-turn "smoothing" step that assumes reconstruction is faithful. The silent part: no error was raised. The reconciliation check `sum(attributed) == sum(marginal)` passed. The per-turn anomaly was only caught when a human asked why turn 9's cost-per-token ratio was 19% higher than its neighbors. ## Condition of Validity The invariant that must hold for per-turn attribution to be faithful: > For every resumed turn *N*, `reconstruct(checkpoint, events[N:]).prompt == billed_prompt(N)`, byte-for-byte after tokenizer normalization. This invariant is **violated** whenever any of the following is true, and the violation is undetectable from aggregate totals: - The checkpoint is *lossy* relative to the live context (dropped reasoning blocks, truncated tool outputs, re-summarized history, stripped system framing). - The replayer applies any *normalization* (reordering, deduplication, whitespace canonicalization) not applied at generation time. - The provider's tokenizer version differs between generation and replay. - Any per-turn *smoothing/allocation* step runs on a reconstructed ledger without first verifying reconstruction fidelity. It is **preserved** only when the checkpoint is a faithful, tokenizer-stable serialization of the exact context, or when marginal `usage` is persisted per-turn atomically and never re-derived. ## Decision Boundary The boundary is whether the observability system treats the checkpoint as **authoritative** or **reconstructive**. - **Authoritative checkpoint:** per-turn `usage` is written to the ledger at generation time, keyed by `(trajectory_id, turn_index)`. Replay never re-derives cost; it only joins. Drift is impossible because there is nothing to reconstruct. - **Reconstructive checkpoint:** per-turn cost is computed from a replayed context. This is acceptable *only* if the replayer asserts reconstruction fidelity before attributing. The assertion must be a hard gate: if `reconstructed_prompt_tokens != billed_prompt_tokens` for any resumed turn, the turn is marked `unreconciled` and excluded from per-turn analysis rather than smoothed. The failure occurs precisely in the gap: systems that are reconstructive *and* apply smoothing. Smoothing converts a detectable fidelity violation into an undetectable redistribution. The architectural rule: **never smooth across a reconstruction boundary; either the turn reconciles exactly or it is flagged.** ## Operational Effect Downstream consequences of undetected per-turn drift: 1. **Cost-spike forensics become wrong.** The turn flagged as the cost driver is whichever turn absorbed the reallocated tokens, not the turn that actually generated them. In the observed case, turn 9 (the resumed turn) was under-attributed and its neighbors over-attributed, inverting the investigation. 2. **Model-selection and prompt-optimization loops optimize the wrong turn.** If an automated optimizer targets high-cost turns for prompt compression, it compresses the turns that were *over*-attributed, not the turn that was actually expensive. 3. **Budget-circuit-breaker mis-fires.** A per-turn budget guard that trips on attributed cost can trip on a turn that was over-attributed by smoothing, halting a trajectory that was within budget. 4. **Audit trails fail silently.** The reconciliation check passes, so the ledger is marked clean. The drift is only recoverable if the raw per-turn `usage` was persisted independently — which, in reconstructive systems, it was not. The guardrail is a fidelity assertion at the resume boundary, plus a prohibition on cross-boundary smoothing. The code below encodes it. ```python class TrajectoryAttributionDrift(RuntimeError): """Raised when a resumed turn's reconstructed context does not match its billed usage.""" def attribute_turn_cost( turn_index: int, reconstructed_prompt_tokens: int, billed_prompt_tokens: int, billed_completion_tokens: int, tokenizer_version_generation: str, tokenizer_version_replay: str, is_resumed: bool, ) -> dict: """ Attribute cost to a single turn. Refuses to smooth across a reconstruction boundary. Returns a ledger entry, or raises if reconstruction fidelity cannot be established. """ if tokenizer_version_generation != tokenizer_version_replay: raise TrajectoryAttributionDrift( f"turn {turn_index}: tokenizer version mismatch " f"({tokenizer_version_generation!r} vs {tokenizer_version_replay!r}); " f"reconstructed token counts are not comparable to billed counts" ) if is_resumed and reconstructed_prompt_tokens != billed_prompt_tokens: delta = billed_prompt_tokens - reconstructed_prompt_tokens raise TrajectoryAttributionDrift( f"turn {turn_index}: reconstruction infidelity on resume — " f"reconstructed={reconstructed_prompt_tokens}, billed={billed_prompt_tokens}, " f"delta={delta}. Refusing to attribute or smooth. Mark turn unreconciled." ) return { "turn_index": turn_index, "prompt_tokens": billed_prompt_tokens, "completion_tokens": billed_completion_tokens, "reconciled": True, "smoothed": False, } def build_trajectory_ledger(turns: list[dict]) -> list[dict]: """ Build a per-turn ledger. Any turn that fails fidelity is recorded as unreconciled and excluded from per-turn cost analysis, but the trajectory total is still preserved from the billed usage fields. """ ledger = [] for t in turns: try: entry = attribute_turn_cost(**t) except TrajectoryAttributionDrift as exc: entry = { "turn_index": t["turn_index"], "prompt_tokens": t["billed_prompt_tokens"], "completion_tokens": t["billed_completion_tokens"], "reconciled": False, "smoothed": False, "reason": str(exc), } ledger.append(entry) return ledger ```