Skip to main content
Back to all articles
AI Engineering 7 min readUpdated August 31, 2026

You Cannot Debug an Agent Run You Cannot Replay

LLM agents combine nondeterministic models, time, randomness, retrieval, and external tools. A replayable run records those boundaries so developers can reproduce decisions without re-triggering real side effects.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#deterministic-replay#debugging#observability#durable-execution#typescript#python
On this page

A production agent fails once. You copy the user's input into a local environment, run it again, and everything works.

That is not surprising.

The second run may use a different model snapshot, different retrieved documents, a newer database row, another random ID, a different clock value, and tool APIs whose responses have changed. If the first run crossed several external boundaries, “run it again” is not reproduction. It is a new experiment.

For difficult agent bugs, I want a replay mode that can reconstruct what the application actually observed at those boundaries while preventing real side effects from happening again.

This is not about making the language model deterministic. It is about recording enough nondeterministic inputs that we can replay the *same execution environment from the agent's point of view*.

The example here is a deployment assistant that reads service state, asks a model to plan, calls tools, and may propose a production change.

Start by naming the nondeterministic boundaries

A typical run depends on more than the user message.

I record at least these categories when they affect behavior:

  • model request configuration and returned output;
  • retrieval query and returned ranked IDs/scores;
  • tool name, normalized arguments, result or normalized error;
  • current time when business logic depends on it;
  • generated random IDs/idempotency keys;
  • mutable resource versions;
  • feature flags/configuration versions;
  • approval events;
  • cancellation/deadline events.

The goal is not to dump the whole process memory. It is to capture values that entered the decision path from outside deterministic application logic.

Give every boundary call a stable event shape

TypeScript
type RecordedBoundary =  | {      kind: "model";      key: string;      requestHash: string;      response: unknown;      metadata: {        provider: string;        model: string;      };    }  | {      kind: "tool";      key: string;      toolName: string;      argumentsHash: string;      result: unknown;    }  | {      kind: "clock";      key: string;      value: string;    }  | {      kind: "random";      key: string;      value: string;    };

The key identifies the logical boundary in the workflow, not only its event sequence.

For example:

Text
plan.initialretrieval.service-docsclock.request-startidempotency.deploy-changetool.get-deployment:checkout-api

Stable keys make a replay easier to compare across code changes than “event 17.”

Wrap time instead of calling it everywhere

If application code directly calls Date.now() in twenty places, deterministic replay becomes annoying.

Inject a clock:

TypeScript
interface Clock {  now(): Date;}​class SystemClock implements Clock {  now(): Date {    return new Date();  }}​class ReplayClock implements Clock {  constructor(private readonly values: Date[]) {}​  now(): Date {    const next = this.values.shift();    if (!next) throw new Error("Replay clock exhausted");    return next;  }}

For most workflows, I do not need every nanosecond. Record the time at meaningful boundaries: run start, deadline checks, TTL decisions, scheduled operations, approval expiry.

The same principle applies to randomness.

Wrap random IDs too

TypeScript
interface IdGenerator {  nextId(purpose: string): string;}​class ReplayIdGenerator implements IdGenerator {  constructor(private readonly values: Map<string, string[]>) {}​  nextId(purpose: string): string {    const queue = this.values.get(purpose);    const value = queue?.shift();    if (!value) throw new Error(`No replay ID recorded for ${purpose}`);    return value;  }}

This matters for more than pretty trace matching. If an idempotency key or operation ID changes during replay, later tool lookups can take a different branch.

A value that influences behavior belongs behind a recordable interface.

Record normalized tool results at the adapter boundary

I do not replay by calling the production CRM or cloud API again.

The original tool adapter records the normalized observation that entered agent state:

TypeScript
type ToolRecord = {  logicalCallId: string;  toolName: string;  args: unknown;  observation:    | { ok: true; value: unknown }    | { ok: false; kind: string; message: string };};

Replay uses a fake executor:

TypeScript
class ReplayToolExecutor {  constructor(private readonly records: Map<string, ToolRecord>) {}​  async call(logicalCallId: string, toolName: string, args: unknown) {    const record = this.records.get(logicalCallId);    if (!record) {      throw new Error(`Missing replay tool record: ${logicalCallId}`);    }​    if (record.toolName !== toolName) {      throw new Error(        `Replay diverged: expected ${record.toolName}, got ${toolName}`,      );    }​    assertEquivalentArgs(record.args, args);    return record.observation;  }}

If a code change causes the agent to call a different tool, replay should say the execution diverged. Silently returning some vaguely related fixture hides exactly the behavior we are trying to inspect.

Model calls can be replayed at two levels

There are two different debugging questions.

Application replay: “Given the exact model output from the failing run, does our application take the same path?”

For this, return the recorded model response and do not call the provider.

Model re-evaluation: “With the same prompt/context, does today's model still make the bad decision?”

For this, reconstruct the recorded model request and call the provider deliberately as a new experiment.

Do not confuse the two.

Application replay should be safe, fast, and independent of provider variability. Re-evaluation is useful for model/prompt analysis but cannot promise the same output.

TypeScript
interface ModelClient {  complete(request: ModelRequest): Promise<ModelResponse>;}​class ReplayModelClient implements ModelClient {  constructor(private readonly responses: ModelResponse[]) {}​  async complete(): Promise<ModelResponse> {    const response = this.responses.shift();    if (!response) throw new Error("Replay model responses exhausted");    return response;  }}

Store the request hash even when replaying the response

If code changes the prompt, tool definitions, or context but replay still returns the old response, the run may look reproducible while the recorded model output no longer corresponds to the request.

Compare hashes:

TypeScript
function assertReplayRequest(  recordedHash: string,  currentRequest: ModelRequest,): void {  const currentHash = hashCanonicalModelRequest(currentRequest);​  if (currentHash !== recordedHash) {    throw new Error("Replay diverged before model boundary");  }}

Sometimes I deliberately allow the request to differ so I can test new application code against old outputs. That mode should be explicit.

A strict replay is valuable precisely because it tells you the first point where current execution no longer matches the original.

Retrieval is an external boundary too

Vector indexes change. Documents are added. embeddings are regenerated. Ranker models are upgraded.

For a failing RAG run I record:

TypeScript
type RetrievalRecord = {  query: string;  indexVersion: string;  results: Array<{    chunkId: string;    documentVersion: string;    score: number;  }>;};

Replay can load the recorded chunk versions from an immutable artifact store rather than run a fresh search against today's index.

That lets me ask whether the original answer was bad because retrieval returned weak evidence or because generation misused good evidence.

Without recorded retrieval, those causes blur together after the corpus changes.

Python boundary recorder

Python
from dataclasses import dataclass, fieldfrom typing import Any​@dataclass(frozen=True)class BoundaryRecord:    kind: str    key: str    request: Any    response: Any​@dataclassclass Recorder:    records: list[BoundaryRecord] = field(default_factory=list)​    def add(        self,        *,        kind: str,        key: str,        request: Any,        response: Any,    ) -> None:        self.records.append(            BoundaryRecord(kind, key, request, response)        )​class ReplayTape:    def __init__(self, records: list[BoundaryRecord]) -> None:        self._records = {(item.kind, item.key): item for item in records}​    def get(self, kind: str, key: str) -> BoundaryRecord:        try:            return self._records[(kind, key)]        except KeyError as exc:            raise RuntimeError(                f"Missing replay boundary {kind}:{key}"            ) from exc

For repeated calls with the same logical key, use a sequence per key rather than this one-record map. The representation should match the workflow.

Never replay real side effects by default

A replay environment should fail closed for writes.

TypeScript
type ReplayToolPolicy = {  allowReadFromRecordedTape: true;  allowExternalWrites: false;};

If the original run sent an email, replay returns the recorded email-tool observation. It does not send another email.

If a developer explicitly wants to test the write integration, use a sandbox/test account and a separate mode with clear destination guards.

“Replay production incident” should not become “repeat production incident.”

Record side-effect identity, not secrets

A tool event may need an external operation ID for reconciliation. It probably does not need the API token used to call the service.

Replay artifacts should be sanitized and access-controlled because they can contain user input, retrieved documents, tool results, and model outputs.

I generally avoid storing:

  • raw authorization headers;
  • API keys;
  • reusable cookies/tokens;
  • unrelated personal data that was present in a larger response but never entered agent state.

Record the normalized decision boundary, not every packet on the wire.

Compare replayed state after every transition

The best replay debugger does more than tell me the final answer differs.

I checkpoint meaningful state hashes:

TypeScript
type StateCheckpoint = {  step: string;  stateHash: string;};

During replay:

TypeScript
function assertState(  checkpoint: StateCheckpoint,  currentState: AgentState,): void {  const hash = hashAgentState(currentState);  if (hash !== checkpoint.stateHash) {    throw new Error(`State diverged after ${checkpoint.step}`);  }}

Now a developer can see that the new code diverged immediately after tool-result normalization rather than spending time comparing final prose.

For state containing timestamps or unordered maps, normalize those fields before hashing.

Replay is useful for refactoring too

A tape from a set of representative production runs can be used to test changes in deterministic orchestration code without re-spending model/tool calls.

For example, changing:

  • context compaction logic;
  • no-progress detection;
  • authorization plumbing;
  • event rendering;
  • trace enrichment;
  • output policy.

Strict replay will surface places where the new implementation changes a boundary request. You can then decide whether the change is expected.

This is similar to contract/snapshot testing at integration boundaries, with the important caveat that stored tapes need versioning and privacy controls.

Do not build one enormous opaque recording

I prefer many typed boundary events to a single blob containing the entire agent runtime.

Typed events are easier to migrate, inspect, redact, and partially replay. A developer can replace only the model client with a live provider while keeping tools recorded, or replay tools while testing a new prompt.

That composability is the real value.

What replay cannot prove

A replay can reproduce the application's behavior under recorded observations.

It cannot prove today's external systems would return the same data. It cannot make a stochastic provider reproduce a hidden internal reasoning path. It cannot validate that a bug caused by a race between two real distributed services will always happen in the same order unless that ordering was captured at the relevant boundary.

Replay is a debugging instrument, not a time machine.

For concurrency bugs, additional deterministic schedulers or lower-level integration tests may be needed.

Add the failing run to regression tests

Once the bug is understood, I usually distill the replay into the smallest durable regression case.

The full production tape is valuable for investigation. A compact synthetic fixture is often better for long-term CI because it is less sensitive, faster, and easier to maintain.

The workflow becomes:

  1. reproduce from recorded boundaries;
  2. find first divergence/failure;
  3. fix;
  4. validate against original replay;
  5. add a sanitized focused regression case.

That turns one strange agent incident into a testable engineering lesson.

When replay infrastructure is overkill

A simple one-shot assistant can often be debugged from request/response logs and version metadata.

Replay becomes valuable when runs are multi-step, expensive, mutate state, depend on changing retrieval/tool data, or cross enough nondeterministic boundaries that manual reproduction regularly fails.

The mental model is familiar from distributed systems and event-driven applications: if a value from the outside world affected a decision, decide whether you need to record it.

Agents are difficult to debug when every rerun observes a different world. A replayable architecture narrows that world to a recorded set of boundaries, making the deterministic application code between them inspectable again.

KEEP READING

Related engineering notes