# Which invariants prevent forensic replay from silently diverging when an agent resumes mid-tool-call **Date of Record:** 2026 November 30 **Scope:** Applies to deterministic reconstruction of agentic sessions from OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) when a session is checkpointed and resumed across process boundaries. Does not apply to live tracing, single-shot inference, or sessions whose tool calls are fully idempotent and side-effect-free. ## Core Distinction A GenAI telemetry stream is a *record of what an agent observed*, not a *record of what the environment was*. The two coincide only when every span attribute that the agent's decision depended on is captured and every span boundary is causally ordered. The subtle boundary is this: **an agent that resumes mid-tool-call emits a span whose `parent_span_id` points to a span from a prior process, but whose `gen_ai.input.messages` reflect a context window the prior process never observed.** Replay engines that reconstruct state by replaying spans in `start_time` order will silently produce a divergent transcript, because the resumed process's first span carries a re-serialized history that has already been mutated (truncated, summarized, or re-ordered) by the checkpoint layer. The invariant that must hold for forensic fidelity is not "spans are complete" — it is **"the union of `gen_ai.input.messages` across all spans in a trace, deduplicated by content hash, equals the context window at every decision point."** This is a stronger and frequently violated property. ## What Was Observed A three-hour agentic session (retrieval-augmented task agent, ~180 tool calls) was checkpointed at a `tool_call` boundary — specifically, after the model emitted a tool call but before the tool result span closed. The process was killed by an OOM killer; the orchestrator resumed from the last durable checkpoint. Post-mortem replay from the OTel collector produced a transcript that diverged from the ground-truth side-effect log at step 94. The mechanics: 1. The checkpoint captured `gen_ai.conversation.id` and the last *completed* span. The in-flight tool call had an open span with `start_time = T` but no `end_time`. 2. On resume, the orchestrator re-issued the tool call. The new span had a fresh `span_id` but the same `gen_ai.tool.call.id` attribute (the tool's own idempotency key, which the SDK had *not* persisted — it was regenerated). 3. The replay engine, sorting spans by `start_time`, saw the orphaned open span at `T`, then the resumed span at `T+47s`. It reconstructed the context as: `[system, user, ...history..., assistant_tool_call(A)]` → tool result → `assistant_tool_call(A')`. But the *actual* resumed process had been given a context window where the assistant turn was `assistant_tool_call(A)` with a result already injected by the checkpoint layer's "optimistic completion" heuristic. 4. The replay's reconstructed transcript therefore contained **one fewer assistant turn** than the live process executed. Downstream verification (an auditor agent replaying the same trace) disagreed with the primary agent's own reported outcome, and the disagreement was attributed to the *agent* rather than to the *telemetry gap*. The failure was not a crash. It was a **silent forensic divergence**: the replay looked valid, the span tree was well-formed, and the reconstructed token counts matched within 0.3%. The divergence was only detectable by comparing `gen_ai.tool.call.id` values across the resumed boundary — and in this session, they were identical because the SDK regenerated them deterministically from a seed that the checkpoint had preserved. ## Condition of Validity Deterministic replay from GenAI telemetry is valid **iff** all four of the following hold: - **Span-closure invariant:** every `gen_ai.tool.call` span has a matching `end_time` and a `gen_ai.tool.call.result` attribute, OR is explicitly marked `gen_ai.tool.call.status = "aborted"` with a `gen_ai.checkpoint.orphan = true` flag. An open span at checkpoint time that is *not* marked orphaned is an unresolvable ambiguity. - **Context-hash invariant:** each span carries `gen_ai.input.messages.hash` (a stable hash over the serialized message list it was conditioned on). Replay must verify that the hash of the reconstructed context at span *n* equals the recorded hash before executing span *n*'s decision. - **Idempotency-key persistence invariant:** `gen_ai.tool.call.id` must be persisted in the checkpoint and reused verbatim on resume. Regeneration — even deterministic regeneration — breaks the ability to correlate pre- and post-resume spans, because the replay engine cannot know whether two spans with the same call id represent a retry or a duplicate emission. - **Causal-order invariant:** `parent_span_id` edges must form a tree rooted at the session span; any span whose `parent_span_id` references a span in a *different* trace id (i.e., the resumed process started a new trace) must be linked by an explicit `gen_ai.resume.from_span_id` attribute. Absent this, the replay engine cannot stitch the two traces without guessing. If any of these fail, the replay is *plausible but not provably faithful*. The distinction matters because forensic reconstruction is used to attribute failures — and misattribution is worse than no attribution. ## Decision Boundary The operational decision is: **when a replay detects a violated invariant, does it (a) halt and flag the trace as unreplayable, or (b) proceed with a best-effort reconstruction and annotate the divergence?** The boundary is drawn by **downstream use**: - If the replay feeds an *auditor agent* whose output is used for safety gating, **halt** (option a). A best-effort reconstruction that diverges by one turn can flip a safety verdict. The auditor must receive a `ReplayIntegrityError` and escalate to human review; it must not receive a "mostly correct" transcript. - If the replay feeds a *debugging tool* for human inspection, **proceed with annotation** (option b) — but the annotation must be machine-readable and must include the exact span id where the context-hash invariant first failed, so the human can inspect the gap directly rather than reading the whole transcript. The failure mode in the observed session was that the replay engine chose (b) unconditionally, and the downstream auditor had no way to distinguish "replay was faithful" from "replay was best-effort." The auditor's confidence score was computed over the reconstructed transcript, not over the *fidelity* of the reconstruction. This is the core anti-pattern: **fidelity is a property of the replay pipeline, and it must be propagated as a first-class signal alongside the transcript, not inferred from the transcript's internal consistency.** ## Operational Effect Enforcing the four invariants changes the checkpoint protocol in three concrete ways: 1. **Checkpoints must be span-aligned, not message-aligned.** The checkpoint boundary is the last *closed* span, and any in-flight span is recorded with `gen_ai.checkpoint.orphan = true` and its `gen_ai.tool.call.id`. On resume, the orchestrator must either re-issue with the *same* call id (and the tool must deduplicate) or emit an explicit `gen_ai.tool.call.retry_of` edge. 2. **Context hashes must be emitted per-span, not per-session.** A session-level hash is insufficient because it cannot localize the divergence; a per-span hash localizes it to the first span whose reconstructed context disagrees with the recorded hash. 3. **Replay must be a two-pass operation.** Pass one reconstructs the span tree and verifies structural invariants (closure, causal order). Pass two replays decisions and verifies context-hash invariants. A single-pass replay cannot distinguish "span missing" from "span present but conditioned on wrong context," and these require different remediations. The cost is roughly 4–7% additional span bytes (hashes and orphan flags) and a second pass over the trace. The benefit is that forensic divergence becomes *detectable at the span where it occurs* rather than *inferred from a downstream disagreement* — which is the difference between attributing a failure to the agent and attributing it to the telemetry layer. ```python import hashlib import json from dataclasses import dataclass from typing import Optional class ReplayIntegrityError(RuntimeError): """Raised when a GenAI telemetry trace cannot be deterministically replayed.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] trace_id: str start_time: float end_time: Optional[float] attrs: dict def _hash_messages(messages: list) -> str: return hashlib.sha256( json.dumps(messages, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() def verify_replayable(spans: list[Span], checkpoint_span_id: str) -> None: """ Enforce the four replay invariants before any reconstruction is attempted. Raises ReplayIntegrityError on the first violated invariant, with the offending span id so downstream tooling can localize the gap. """ by_id = {s.span_id: s for s in spans} # Invariant 1: span closure (or explicit orphan marking). for s in spans: if s.end_time is None: if not s.attrs.get("gen_ai.checkpoint.orphan"): raise ReplayIntegrityError( f"open span {s.span_id} at checkpoint {checkpoint_span_id} " f"is not marked gen_ai.checkpoint.orphan=true" ) # Invariant 2: per-span context hash present. for s in spans: if "gen_ai.input.messages.hash" not in s.attrs: raise ReplayIntegrityError( f"span {s.span_id} missing gen_ai.input.messages.hash; " f"context-hash invariant cannot be verified" ) # Invariant 3: idempotency-key persistence across resume boundary. call_ids = {} for s in spans: cid = s.attrs.get("gen_ai.tool.call.id") if cid is None: continue if cid in call_ids and call_ids[cid] != s.span_id: prev = by_id[call_ids[cid]] if prev.trace_id != s.trace_id and not s.attrs.get("gen_ai.tool.call.retry_of"): raise ReplayIntegrityError( f"tool call id {cid} reused across trace boundary " f"({prev.trace_id} -> {s.trace_id}) without retry_of edge" ) call_ids[cid] = s.span_id # Invariant 4: causal order across resume (cross-trace parent). for s in spans: if s.parent_span_id and s.parent_span_id not in by_id: if "gen_ai.resume.from_span_id" not in s.attrs: raise ReplayIntegrityError( f"span {s.span_id} references parent {s.parent_span_id} " f"outside trace {s.trace_id} without gen_ai.resume.from_span_id" ) def replay_decision(span: Span, reconstructed_messages: list) -> None: """Replay a single decision, verifying the context-hash invariant first.""" recorded = span.attrs["gen_ai.input.messages.hash"] actual = _hash_messages(reconstructed_messages) if recorded != actual: raise ReplayIntegrityError( f"context-hash divergence at span {span.span_id}: " f"recorded={recorded[:12]} actual={actual[:12]}" ) ```