Originally published on Silicon & AI Pulse.

Deterministic Replay Scope Note: The Python 3.10+ harness in this walkthrough uses only the standard library (zero API keys or live LLM calls) and evaluates deterministic state-machine diffs rather than live cloud model latency benchmarks.

Editing one sentence in a production system prompt can quietly shift Turn 2 JSON types, emit unexpected null values for earlier fields, or trigger attempts to wipe immutable primary keys—even when single-turn CI tests stay green.

Following up on How to Persist AI Agent State in Python: A Two-Turn Example and What Does an AI Agent Session Cost? Inside AWS AgentCore's New Cost Visibility, here is how to build an offline multi-turn replay gate before promoting prompt or model changes.

Why Single-Turn CI Misses Multi-Turn Regressions

As highlighted in Anthropic's Rust API migration report (and analyzed in our Anthropic Rust API Migration summary), synthetic unit assertions routinely hit ~98% pass rates while failing on complex real-world traffic sequences.

For stateful AI agents, validating Prompt v2 safely requires separating two layers:

  1. Append-only JSONL Checkpoints (dataclasses + json): Store each historical turn's user_input, tool_call_id, and observed tool payload one line per turn.
  2. StubbedToolLedger: Freeze historical tool responses so replaying Prompt v2 never re-sends Slack messages, mutations, or live API calls.

Complete Offline Python Replay Harness (Stdlib Only)

Continuing the concrete pour work-order scenario (WO-2026-418, Building B - Level 3, Marcus Chen, 45 cy), the replay comparator evaluates Prompt v1 (baseline) against Prompt v2 (a candidate prompt introducing three subtle regressions across Turns 2 and 3):

from __future__ import annotations import copy import json from dataclasses import asdict, dataclass from pathlib import Path from typing import Any CLEARABLE_FIELDS: frozenset[str] = frozenset({ "site_zone", "crew_lead", "volume_cy", "target_date", "safety_signoff", }) PROTECTED_FIELDS: frozenset[str] = frozenset({"work_order_id"}) ALLOWED_FIELDS: frozenset[str] = PROTECTED_FIELDS | CLEARABLE_FIELDS EXPECTED_TYPES: dict[str, type] = { "work_order_id": str, "site_zone": str, "crew_lead": str, "volume_cy": int, "target_date": str, "safety_signoff": str, } @dataclass(frozen=True) class CheckpointTurn: turn: int user_input: str tool_call_id: str | None stubbed_tool_result: dict[str, Any] | None class StubbedToolLedger: """Freezes historical tool outputs so prompt replays never call live APIs.""" def __init__(self, checkpoints: list[CheckpointTurn]) -> None: self._by_id: dict[str, dict[str, Any]] = { cp.tool_call_id: cp.stubbed_tool_result for cp in checkpoints if cp.tool_call_id and cp.stubbed_tool_result is not None } self.live_calls_blocked = 0 def fetch(self, tool_call_id: str | None) -> dict[str, Any] | None: if not tool_call_id: return None self.live_calls_blocked += 1 return copy.deepcopy(self._by_id.get(tool_call_id)) def guarded_merge( state: dict[str, Any], patch: dict[str, Any], turn: int ) -> tuple[dict[str, Any], list[str], list[str]]: """Apply validated patch fields and return (next_state, warnings, type_drifts).""" merged = copy.deepcopy(state) warnings: list[str] = [] type_drifts: list[str] = [] for key, value in patch.items(): if key == "clear_fields" or key not in ALLOWED_FIELDS: continue if value is None: if key in merged and merged[key] is not None: warnings.append(f"turn_{turn}:ignored_null_for_existing:{key}") continue expected_t = EXPECTED_TYPES.get(key) if expected_t and not isinstance(value, expected_t): type_drifts.append( f"turn_{turn}:{key}:expected_{expected_t.__name__}_got_{type(value).__name__}({value!r})" ) continue merged[key] = value for field in patch.get("clear_fields") or []: if field in CLEARABLE_FIELDS: merged[field] = None else: warnings.append(f"turn_{turn}:blocked_protected_clear:{field}") merged["state_version"] = int(merged.get("state_version", 0)) + 1 return merged, warnings, type_drifts 

Deterministic Diff Output (Catching 3 Regressions Before Deploy)

Even though guarded_merge() protects final_state from silent data loss, the audit output blocks Prompt v2 from shipping:

{ "final_state": { "work_order_id": "WO-2026-418", "volume_cy": 45, "site_zone": "Building B - Level 3", "crew_lead": "Marcus Chen", "target_date": "2026-12-12", "state_version": 3, "safety_signoff": "Approved - Elena Vasquez" }, "warnings": [ "turn_2:ignored_null_for_existing:crew_lead", "turn_3:blocked_protected_clear:work_order_id" ], "type_drifts": [ "turn_2:volume_cy:expected_int_got_str('45')" ], "stubbed_tool_calls": 2 } 

Choosing the Right Replay Tier

Replay Mode Live LLM Calls? Live Tool Side Effects? Best CI / Release Role
1. Frozen Checkpoint + Reducer Replay No No (StubbedToolLedger) Every PR touching reducers, parsers, or allowlists
2. Live Prompt v2 + Stubbed Tools Yes No (frozen tool payloads) Pre-release gate for prompt or model upgrades
3. Shadow Production Sandbox Yes Isolated sandbox / mocks Final canary validation on critical workflows

Browse the complete trilogy—state persistence, cost observability, and deterministic replay—in the Production AI Agent Engineering Hub on Silicon & AI Pulse.

AI Content Disclaimer: Prepared December 3, 2026 with AI-assisted engineering synthesis. All Python patterns use standard-library primitives verified against deterministic state-machine equivalence checks; the WO-2026-418 fixtures illustrate offline regression testing rather than live customer logs.