Delve · Field guide

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.

Delve Editorial · AI Agents · 9 min

#observability #tracing #evaluation #reliability #llm-as-judge

The 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.

01 · The mechanism

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.

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.

02 · The instrumentation

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.

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

03 · The diagnosis

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.

04 · The regression guard

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.

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

05 · The live loop

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.

What changes when the failing artifact is a trajectory

The same incident taxonomy, but almost every debugging primitive has to be re-earned.

SignalDeterministic serviceLLM agentWhat you do instead
Failure surfaceException with stack traceWell-formed wrong answerDiff the trajectory, not the output
ReproductionRerun the requestRerun gives a different pathReplay context at temp zero, pin seed
Regression testAssert on return valueReturn value hides the routeAssert on intermediate steps
Root-cause unitFunction or dependencyLayer: retrieval, tool, loop, modelClassify at first diverging span
AlertingError rate and latencyCost and loop depth move firstAlert on displacement versus baseline

Common misconceptions

  • A passing test suite means the agent works. 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.
  • Rerunning the request will reproduce the failure. 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.
  • The model is too weak; upgrade and the bug goes away. 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.

Run the loop on your next incident

Five moves, in order, from one bad session to a permanent guard.

Pull one bad trace

Open a single failing session, not a dashboard. Walk spans chronologically and mark the first step whose output would not appear in a correct run. Ignore everything downstream until you have that step pinned.

Classify before you fix

Label the diverging step as retrieval miss, tool contract error, orchestration fault, or capability limit. Write the label down; it determines whether the fix is an index change, a schema change, a loop guard, or an escalation rule.

Replay with one variable

Replay the captured context at temperature zero with a fixed seed. If it passes, treat the defect as sampling-sensitive and add a constraint. If it still fails, swap exactly one component — retrieval, schema, model — and replay again.

Minimize and pin

Strip history and tools until the failure disappears, keep the smallest failing case, and add it to the golden dataset with step-level assertions on arguments, ordering, and termination.

Instrument the canary

Alert on cost per completed task against a rolling baseline and on identical consecutive tool calls. Put prompt and model-version changes behind a canary so displacement is attributable.

What would change my mind: Sustained evidence that trace-level instrumentation rarely pays off — for example, that most production agent regressions are caught faster by end-to-end output scoring plus cost alerts than by trajectory capture and replay — would demote instrumentation from the first move to a fallback.

Recall check

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?

  1. The final answer text, grouped by failure category
  2. The full trajectory for a failing request, including retrieved chunks and tool calls
  3. The model version and temperature settings alone
  4. The aggregate error rate broken down by user segment

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?

  1. The bug is fixed and can be closed
  2. The model version was silently updated upstream
  3. The failure is sampling-sensitive, so the durable fix is a constraint rather than a prompt tweak
  4. The trace was captured incorrectly

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?

  1. They are graded by a stronger judge model
  2. They fail at the step where behavior changed instead of after downstream steps mask or amplify it
  3. They require no golden dataset
  4. They eliminate the need for production monitoring

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.

Open questions

  • 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.

Sources

Browse all public guides