# Debugging AI Agents in Production: Trace, Bisect, Replay

Agent failures are sampled paths, not broken lines. Capture the trajectory, find the first diverging step, and turn the incident into a permanent test.

> How do you debug an AI agent in production?

## Short answer

Debug an agent by treating the **trajectory** — the full sequence of model calls, tool invocations, and retrieved context — as the failing artifact, not the final answer. Capture that trajectory before you need it, find the first diverging step in one bad trace, classify the fault by layer, then replay it as a permanent test.

The mental model that makes this work: a bug is a low-probability path, not a broken line. Two runs can produce identical final text via different routes, so grading output alone hides the route that will break under shifted traffic. Instrumentation is the whole game — retrofitting spans during an incident is usually impossible because the failing runs already went by unrecorded.

- **Failing artifact**: The trajectory, not the answer
- **First move**: Find first diverging span
- **Best early canary**: Cost per completed task

## Why agent bugs leave no stack trace

An agent's failure is not a line of code that executed; it is a **sampled path** through model calls, tool invocations, and retrieved context that happened to end badly. Change the seed or the input and the same code produces a different path — so "reproduce the bug" means "find the input distribution and context state that make the bad path likely," not "run it again" .

Four properties make these failures invisible to conventional APM. They are **silent**: the agent returns a well-formed, confident, wrong answer instead of raising . They are **cumulative**: a weak retrieval at step 3 becomes a hallucinated tool argument at step 7, so the visible error sits far downstream of the cause. They are **economic**: loops that re-ask the same question burn tokens, which is why session cost versus a rolling average flags runaways earlier than error rate does . And they are **structural**: one trace can span thousands of nested calls across heterogeneous tool schemas, which defeats log grep .

The practical consequence: two runs can produce identical final text via different paths — one by retrieving the right document, one by guessing. Grading only the output cannot tell them apart, and the guessing path is the one that breaks when traffic shifts.

> The failing artifact is the trajectory, not the answer.

> Note: A bug that fails 2% of the time under production input is not rare — it is the same defect as a hard crash, just sampled less often.

## Capture the trajectory before you have a bug

Capture at span level or you capture nothing useful. One request should be one trace; each model call and each tool invocation a nested child span carrying the rendered prompt, the exact retrieved chunks with scores, tool name plus raw arguments and raw response, token counts, latency, and the agent's state at that step. The OpenTelemetry **GenAI semantic conventions** define the attribute names for this, but they remain Development-stability and keep getting reorganised — one instrumentation package pins them as local constants for exactly that reason, and keeps non-spec fields (fallback chains, response cache) in a separate namespace so they stay distinguishable when you scroll a span .

Two operational constraints shape the design. Trace delivery **must not block tool execution**: use a batch exporter that buffers in memory, flushes periodically, and drains on shutdown, so an unreachable backend costs telemetry rather than availability . And watch **cardinality**: tool and agent names are safe as metric labels; session IDs are not, and thousands of daily sessions will crash a metrics server that carries them . Per-session detail belongs in the trace store.

Full capture means storing prompts, PII, and proprietary context — decide redaction and retention at instrumentation time, not during an incident. Sample aggressively for cost, but keep a force-full-capture path for flagged sessions.

> Note: Sampling decisions made for storage cost are effectively sampling decisions about which bugs you will be able to see.

## Bisect one bad trace down to a layer

Start from one bad trace, not from the aggregate dashboard. Walk the spans in order and find the **first diverging step** — the earliest point where the trajectory stops matching what a correct run would have done. Everything after that is usually consequence. Then classify the fault at that step, because the fix differs per class:

- **Retrieval miss**: the needed chunk was never in context, and the model reasoned correctly over insufficient evidence.
- **Tool contract error**: an ambiguous schema, rejected arguments, and a retry loop.
- **Orchestration fault**: premature termination, unbounded retry, or a dead end the agent could not exit.
- **Capability limit**: the context and tool set were adequate and the model still could not perform the step.

Test one variable at a time. Replay the identical context at temperature zero with a pinned seed; if it now succeeds, the fault is sampling-sensitive rather than deterministic, and your fix is a **constraint** (validation, step caps, a stricter schema) rather than a prompt tweak. Then swap exactly one component — retrieval index, tool schema, model version — and re-run.

The most common misdiagnosis is "the model is too weak." Trace tooling packages spin, tool bugs, early abort, and routing errors as separable, nameable classes , and trace-analysis research treats structural diagnosis as distinct from raw capability . A stronger model often just masks a schema defect on every call.

> "The model is too weak" is usually a context or tool-schema defect wearing a disguise.

## Turn a production failure into a permanent test

A production failure is worth exactly one thing: a test that outlives it. Capture the failing input, the retrieved context, and the tool responses, then **minimize** — strip conversation history and available tools until the failure stops reproducing, and keep the smallest version that still fails. That reduced case enters a golden dataset alongside the expected *intermediate* behavior, not just the expected answer.

Grade at two levels. **Step-level assertions** — did the agent look up the order before issuing a refund, were arguments schema-valid, did it terminate within N steps, did it stay under a token budget — are cheap, deterministic, and catch regressions earlier than outcome scoring, because they fail at the step where behavior changed rather than at the end. **Outcome grading** with a rubric judge catches the subtler plausible-but-wrong class. Trace tooling has already moved structural grading and failure classification from manual reading to repeatable operations over a trace set , which is what makes step-level checks affordable at dataset scale.

LLM-as-judge carries its own error. Judges drift with model version, are sensitive to prompt and ordering, and can be confidently wrong — calibrate against a human-labeled slice before letting a judge score block a release, and keep deterministic assertions as the gate.

Compare execution **paths** structurally, not just final text. A fix that reroutes the agent into a lucky answer looks like a pass under output-only grading.

> Note: Step-level checks fire on the step that changed; end-to-end checks fire only after every downstream step has masked or amplified it.

## Monitoring live traffic, and what you can only bound

Production surfaces failures you never had a trace for. Sample live traffic into the same eval harness continuously — a fixed percentage plus every flagged session — and track **trajectory metrics**, not just success: tool error rate by tool, identical consecutive tool calls, loop depth, escalation rate, cost per completed task, and session cost against a rolling average . Cost is the most reliable early canary because loops, routing errors, and unbounded context accumulation all register there before a user complains .

Alert on **displacement**, not just absolute error. A prompt edit, a retrieval index rebuild, or a silent provider model update changes behavior with no change in your code; shading traffic through a canary or shadow deployment converts that into a small attributable delta instead of a broad regression.

The caveat that governs everything above: non-determinism means some failures cannot be reproduced, only **bounded**. You will ship with a nonzero failure rate. The engineering goal is a measured rate with fallbacks — deterministic tool wrappers, step caps, validation before side effects, human escalation on low confidence — not a bug-free agent. Two ongoing costs are easy to underestimate: retaining prompts and tool payloads means retaining PII, and continuous judge scoring means paying a second model on a slice of all traffic forever. Budget both before you widen sampling.

> You are not eliminating failures; you are pricing and bounding them.

## Common misconceptions

- **Myth:** A passing test suite means the agent works. **Reality:** Test suites sample a narrow input distribution. Agents fail on the tail — unusual context lengths, empty retrieval results, tool timeouts — so a green suite and a healthy production error rate are different claims.
- **Myth:** Rerunning the request will reproduce the failure. **Reality:** Sampling means the same input can take a different path. Reproducibility comes from replaying the captured context at low temperature, not from rerunning the live request.
- **Myth:** The model is too weak; upgrade and the bug goes away. **Reality:** A stronger model often masks an ambiguous tool schema or a retrieval gap, converting a visible failure into a quieter one that costs more tokens on every call.

## FAQ

### An agent returns a fluent, correct-looking answer for 98% of requests. For the other 2% it produces a plausible answer from the wrong source document. Which debugging artifact gives you the most leverage?

The failure is a route problem, not a text problem. Only the trajectory shows whether the wrong document was retrieved, whether it ranked below a cutoff, or whether a tool call was skipped.

### You replay a failing input at temperature zero with a pinned seed and it now succeeds. What does that tell you?

A pass on deterministic replay means the defect lives in path probability, not in a single reproducible computation. Validation, step caps, or a stricter schema bound it; a prompt edit does not.

### Why do step-level assertions catch agent regressions earlier than end-to-end answer scoring?

An end-to-end check only fires if the final output degrades — but a wrong tool argument at step 4 can still produce a correct answer at step 9 by luck. Step assertions fire at step 4.

### How much trajectory capture is enough before the storage and PII cost outweighs the debugging benefit?

Every team picks a sampling rate by intuition; there is no published failure-detection curve relating capture rate to mean time to diagnosis.

### How reliable are LLM-as-judge scores as a release gate across model versions?

If judge scores drift when either the judged or the judging model changes, continuous evals produce false regressions and false passes at the same rate.

### Can trajectory-level metrics predict failures before they reach users?

Cost and loop-depth alerts are used as leading indicators, but no source here quantifies their precision or lead time.

---

Delve Editorial · https://delve.prisflow.com/p/agent-observability
