Engineering 10 min read Published November 23, 2026

How to Debug AI Agents with Execution Traces

Master non-deterministic AI agent debugging. Learn how to record turn-level execution traces, capture tool diffs, and create deterministic replay fixtures.

Sarah Chen
Sarah Chen
Lead Systems Architect & AI Reliability Engineer
Share
Architecture diagram showing AI agent execution trace serialization, tool call diff recording, and deterministic replay engine

CadreGPT turn-level execution trace architecture converting stochastic multi-agent failures into deterministic, offline replay fixtures.

The "It Failed Once in 300 Runs" Crisis

Every engineering team that moves from single-prompt prototypes to multi-agent production systems eventually encounters the same operational nightmare:

An autonomous reconciliation agent ran 299 times without incident. On run 300, it hallucinated an invalid currency exchange rate parameter, attempted to mutate an immutable ledger entry, crashed, and left three downstream worker tasks permanently stranded in an unhandled state.

When the on-call engineer inspects the log aggregator, they find standard unstructured logs:

text
2026-11-23T04:12:01.104Z [INFO] Agent started workflow task_9821
2026-11-23T04:12:03.450Z [INFO] Model generated tool call: reconcile_ledger
2026-11-23T04:12:04.891Z [ERROR] Uncaught ValidationError: Field "currency_rate" must be positive number. Received: "EUR/USD 1.082"
2026-11-23T04:12:04.892Z [ERROR] Workflow aborted.

The engineer copies the initial task input, pastes it into a local test script, runs it five times, and every single run succeeds. The test passes. The error disappears.

Why? Because traditional software debugging assumes deterministic execution paths. When function foo(x) fails in traditional software, running foo(x) with identical inputs in a local debugger executes the exact same bytecode.

In autonomous AI agents, running the same initial input does not execute the same code. Three independent layers of non-determinism compound across every turn of the execution loop:

typescript
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                        Compound Non-Determinism in AI Agents                           │
├────────────────────────┬───────────────────────────────┬───────────────────────────────┤
│ Layer                  │ Mechanism                     │ Failure Vector                │
├────────────────────────┼───────────────────────────────┼───────────────────────────────┤
│ 1. Model Sampling      │ Temperature, top-p, seed drift│ Stochastic token selection    │
│ 2. Tool Environment    │ Dynamic third-party APIs      │ Payload schema variations     │
│ 3. Context Mutations   │ Sliding window / RAG injection│ Turn-by-turn prompt inflation │
└────────────────────────┴───────────────────────────────┴───────────────────────────────┘

If your platform relies on unstructured string logs, you cannot debug autonomous agents. You are attempting to debug a distributed state machine by reading an echo of what it thought it did.

To solve this, enterprise platforms must transition to turn-level execution traces.


Anatomy of an Execution Trace

An execution trace is not a log file. An execution trace is a complete, hermetically sealed recording of state transitions across every turn of an agent's lifecycle.

To reproduce an intermittent failure offline, the trace must record five discrete artifacts for each turn:

  1. Exact Prompt Snapshot: The fully hydrated context window at turn start, including system directives, injected RAG context, and prior turn histories.
  2. Model Sampling Metadata: Model identifier, temperature, top-p, active seed, and exact token counts (prompt, completion, cached).
  3. Raw Model Output: Unparsed completion text and structured tool-call declarations before validation.
  4. Tool Execution I/O Diff: Exact input arguments dispatched to the tool, HTTP status codes, response headers, execution duration, and serialized return payloads.
  5. State Transition Assertion: The before-and-after finite state machine (FSM) status (as discussed in our guide on Finite State Machines vs. Unbounded Loops).

The Type-Safe Trace Schema

Here is the exact TypeScript data contract CadreGPT uses to record immutable execution traces:

typescript
// src/types/execution-trace.ts

export type AgentTurnStatus = 'SUCCESS' | 'TOOL_ERROR' | 'SCHEMA_VIOLATION' | 'BUDGET_EXCEEDED';

export interface ToolCallTrace {
  toolCallId: string;
  toolName: string;
  inputArguments: Record<string, unknown>;
  outputPayload: Record<string, unknown> | string;
  isError: boolean;
  executionDurationMs: number;
  idempotencyKey?: string;
}

export interface AgentTurnTrace {
  turnIndex: number;
  timestamp: string;
  modelIdentifier: string;
  samplingParameters: {
    temperature: number;
    topP: number;
    seed?: number;
    maxTokens: number;
  };
  tokenUsage: {
    promptTokens: number;
    completionTokens: number;
    totalCostUsd: number;
  };
  contextWindowSnapshot: {
    systemPromptHash: string;
    messageCount: number;
    injectedKnowledgeIds: string[];
  };
  rawModelOutput: string;
  toolCalls: ToolCallTrace[];
  resultingState: string;
  turnStatus: AgentTurnStatus;
  stateDiff: {
    variablesBefore: Record<string, unknown>;
    variablesAfter: Record<string, unknown>;
  };
}

export interface WorkflowExecutionTrace {
  workflowId: string;
  runId: string;
  initiatorId: string;
  startTime: string;
  endTime?: string;
  finalStatus: 'COMPLETED' | 'FAILED' | 'HALTED_BY_GATE';
  turns: AgentTurnTrace[];
}

With this structure stored in your database or object vault, a failure on turn 17 is no longer a mystery. You have the exact input the model received on turn 17, the exact string it returned, and the exact response the database returned when invoked.


The Information-Gain Walkthrough: Turning Flakes into Replay Tests

Let us walk through a real-world incident from production telemetry and examine how to convert it into a zero-cost deterministic regression test.

Step 1: Isolating the Non-Deterministic Drift

In our reconciliation workflow, the agent is tasked with parsing a customer webhook payload and recording an invoice.

On 99.7% of executions, the external billing API returns numbers formatted as raw floats:

json
{ "total": 1450.50, "currency": "USD" }

However, when an upstream partner system experiences high gateway load, its legacy fallback proxy formats totals as formatted strings with comma separators:

json
{ "total": "1,450.50", "currency": "USD" }

The LLM, seeing "1,450.50" in its context window, attempts to parse the value using a regex tool call:

json
{ "action": "parse_amount", "value": "1,450.50" }

Stochastically—dependent on token sampling—the model occasionally emits an unescaped comma in its JSON payload or casts the value into an array, triggering an uncaught schema validation error in your backend tool adapter.

Step 2: Extracting the Offending Turn

Instead of attempting to re-trigger the external API error, we download the serialized trace for the failed run from the CadreGPT Task Telemetry Inspector:

json
{
  "workflowId": "wf_rec_0991",
  "runId": "run_err_4410",
  "turns": [
    {
      "turnIndex": 3,
      "modelIdentifier": "gemini-2.0-flash",
      "toolCalls": [
        {
          "toolName": "fetch_billing_record",
          "inputArguments": { "invoiceId": "INV-2026-881" },
          "outputPayload": { "total": "1,450.50", "currency": "USD" },
          "isError": false,
          "executionDurationMs": 142
        }
      ],
      "turnStatus": "SCHEMA_VIOLATION",
      "resultingState": "ERROR_HANDLER"
    }
  ]
}

Step 3: The Deterministic Replay Test Engine

Now we construct an offline replay harness. The replay harness intercepts all external network calls and feeds the recorded outputPayload directly into the agent runtime.

No LLM API calls are made. No live databases are touched. Execution takes 38 milliseconds:

typescript
// tests/replays/reconcile-ledger.replay.test.ts
import { describe, it, expect } from 'vitest';
import { AgentReplayHarness } from '@/lib/ai-gateway/replay-harness';
import failedTrace from './fixtures/run_err_4410.trace.json';

describe('Replay Regression: Run ERR-4410 String Amount Parsing', () => {
  it('correctly normalizes string formatted numbers without throwing schema validation error', async () => {
    // 1. Initialize replay harness with frozen trace data
    const harness = new AgentReplayHarness({
      traceFixture: failedTrace,
      targetTurnIndex: 3,
      freezeTime: new Date(failedTrace.turns[3].timestamp),
    });

    // 2. Mock external tool outputs with the exact payload that triggered the incident
    harness.mockToolCall('fetch_billing_record', () => {
      return { total: "1,450.50", currency: "USD" };
    });

    // 3. Execute the agent turn against our updated tool schema adapter
    const result = await harness.executeTurnStep();

    // 4. Assert determinism: turn must succeed without entering ERROR_HANDLER
    expect(result.turnStatus).toBe('SUCCESS');
    expect(result.extractedAmount).toBe(1450.50);
    expect(result.resultingState).not.toBe('ERROR_HANDLER');
  });
});

Notice what we just accomplished:

  1. Flakiness is eliminated: The bug that happened once in 300 runs now reproduces on demand in 38 milliseconds.
  2. Zero marginal cost: The regression suite runs in local CI pipelines without consuming OpenAI, Claude, or Gemini API credits.
  3. Permanent verification: Future prompt changes or model version upgrades can never re-introduce this failure mode without failing the CI build.

Capturing Tool Diffs and Preventing State Corruption

Recording model outputs is only half the battle. When an agent mutates external databases, third-party CRMs, or cloud infrastructure, operations teams need to verify state delta safety.

If an agent updates a customer's credit balance from $500 to $200, the trace must record the before-and-after diff:

typescript
┌────────────────────────────────────────────────────────────────────────┐
│                        State Delta Verification                        │
├────────────────────────────────────────────────────────────────────────┤
│ Before Mutation:                                                       │
│ { "customerId": "cust_402", "balance": 500.00, "status": "ACTIVE" }    │
│                                                                        │
│ Invoked Tool: debit_account(amount: 300.00)                            │
│                                                                        │
│ After Mutation:                                                        │
│ { "customerId": "cust_402", "balance": 200.00, "status": "ACTIVE" }    │
└────────────────────────────────────────────────────────────────────────┘

By coupling state diffs with two-phase credit metering and financial invariance, if the post-mutation assertion fails (for instance, if the balance somehow dropped below zero), the runtime immediately issues a compensating rollback transaction and halts execution at a Human-in-the-Loop approval gate.


Architectural Performance: Zero-Overhead Trace Ingestion

A common objection from engineering leadership is that recording full context snapshots on every turn degrades throughput and inflates storage costs.

Under naive implementations—such as synchronously writing multi-megabyte JSON payloads to a primary PostgreSQL database inside the inference loop—this objection is valid.

CadreGPT avoids inference degradation through a three-tier storage topology:

typescript
┌───────────────────────────────────────────────────────────────────────────────────────┐
│                      CadreGPT Trace Storage Pipeline                                  │
├────────────────────┬──────────────────────────────────┬───────────────────────────────┤
│ Tier               │ Storage Medium                   │ Lifecycle & Latency           │
├────────────────────┼──────────────────────────────────┼───────────────────────────────┤
│ Tier 1: In-Memory  │ Process Ring Buffer              │ Immediate (<0.2ms)            │
│ Tier 2: Real-Time  │ Redis Stream (Pub/Sub SSE Bridge)│ 15-day hot retention (<1.2ms) │
│ Tier 3: Cold Vault │ Cloudflare R2 / AWS S3 (Zstandard│ Permanent compressed audit    │
└────────────────────┴──────────────────────────────────┴───────────────────────────────┘
  1. Non-blocking Ingestion: The agent worker emits trace events to an in-memory ring buffer. Worker execution never blocks waiting for I/O disk writes.
  2. Real-Time Streaming: The ring buffer flushes asynchronously to Redis Streams, which powers both the real-time Server-Sent Events dashboard and immediate incident inspection.
  3. Cold Archival with Zstandard: Completed traces are compressed with Zstandard (achieving >85% compression ratios on JSON text) and uploaded in micro-batches to S3 or Cloudflare R2. 100,000 full execution turns occupy less than 1.4 GB of cold object storage.

PII Sanitization & Security Boundary

Enterprise compliance frameworks (SOC 2 Type II, HIPAA, GDPR) prohibit storing unredacted authentication keys, bearer tokens, and customer PII in telemetry logs.

CadreGPT enforces deterministic sanitization at the gateway layer before trace events touch Redis or disk storage:

typescript
// src/lib/telemetry/trace-sanitizer.ts
import crypto from 'node:crypto';

const SENSITIVE_KEY_REGEX = /bearer|token|secret|password|authorization|api[_-]?key/i;

export function sanitizeTracePayload<T>(payload: T): T {
  if (typeof payload !== 'object' || payload === null) {
    return payload;
  }

  if (Array.isArray(payload)) {
    return payload.map(sanitizeTracePayload) as unknown as T;
  }

  const sanitized: Record<string, unknown> = {};

  for (const [key, value] of Object.entries(payload)) {
    if (SENSITIVE_KEY_REGEX.test(key) && typeof value === 'string') {
      // Replace raw secret with deterministic HMAC hash for audit tracking
      sanitized[key] = `[REDACTED_HMAC:${crypto.createHash('sha256').update(value).digest('hex').slice(0, 12)}]`;
    } else if (typeof value === 'object' && value !== null) {
      sanitized[key] = sanitizeTracePayload(value);
    } else {
      sanitized[key] = value;
    }
  }

  return sanitized as T;
}

Engineers can still correlate whether two failing turns used the same authorization token by comparing the HMAC fingerprint, but the raw secret is never stored in the trace archive.


Summary Checklist: Production Agent Debugging Readiness

Before deploying autonomous agents to customer-facing or financially mutating workflows, verify that your observability stack passes these five criteria:

  • [ ] Turn-level immutability: Are context snapshots, model sampling parameters, and raw responses captured at every discrete turn?
  • [ ] Tool call parameter recording: Are exact JSON arguments, return values, and network durations stored per invocation?
  • [ ] Offline replay capability: Can an engineer download a trace file and execute the failing turn locally without invoking live LLM APIs?
  • [ ] State delta tracking: Are external database changes recorded as before-and-after diffs with automated rollback assertions?
  • [ ] Boundary sanitization: Are secrets and PII redacted into deterministic HMAC hashes prior to telemetry serialization?

If your current framework lacks these capabilities, you are flying blind in production.

To see turn-level execution traces and interactive replay tooling in action, inspect live execution telemetry in CadreGPT or explore how our Visual Workflow Canvas builds deterministic agent topologies.

Sarah Chen

Sarah Chen

Verified Enterprise Author

Lead Systems Architect & AI Reliability Engineer

Distributed systems architect focused on formal verification, state-machine orchestration, and deterministic replay debugging for autonomous AI workforces.

Frequently Asked Questions

To reproduce intermittent agent failures, record a complete turn-level execution trace containing the system prompt, conversation history, model sampling parameters (seed, temperature), and the exact JSON payloads of all tool calls. Replaying this trace against a mock execution harness allows developers to step through the failure offline without paying model invocation costs or triggering production API side effects.
Related Topics:#Debugging#Execution Traces#Observability#AI Agents#Tool Calling#Reliability Engineering

Recommended Architectural Deep Dives

Engineering

Real-Time SSE Telemetry & Thought Streaming: Architecting Observability for Autonomous Workforces

Architect sub-15ms agent telemetry, thought streaming, and execution diffs using Redis Pub/Sub and Server-Sent Events instead of HTTP polling.

9 min readRead Deep Dive
Engineering

Financial Invariance in Autonomous AI: Architecting Two-Phase Token & Credit Metering

How CadreGPT eliminates runaway AI compute bills using two-phase credit reservations, SERIALIZABLE isolation, and real-time token telemetry.

7 min readRead Deep Dive