Debugging Agents, RAG and Handoffs
Do not guess from the final answer. Find the first step where reality and expectation parted.
Work from the timeline: find the first step that went wrong, classify it as input, context, retrieval, decision, tool, handoff or control, reproduce it with recorded results and no live side effects, change one thing, then keep the case as a regression test.
What you will learn: a debugging method, reading state and timelines, diagnosing tool, planning, retrieval and handoff failures, and replaying runs safely.
Prerequisites: Agent Tracing and OpenTelemetry and The Agent Loop: Observe, Reason, Plan, Act, Reflect.
The example runs in November 2026 with Python 3.13 and only the standard library. The recorded run is invented, and the "agent" is plain code so that the replay technique is easy to see.
Why agent bugs are different
In ordinary software, the same input usually gives the same result, and a stack trace points at the line. An agent chooses its own path, depends on changing data, and may fail without any error: every call succeeds and the answer is still wrong. The same input may also succeed the next time. So you need records of what happened and a way to test a suspected cause more than once.
Six steps
- State the symptom precisely: what happened, what should have happened and who noticed.
- Gather the trace, agent and model versions, configuration, time and affected records.
- Read forward from the start. The last error is often a result of an earlier mistake.
- Ask at each step: given what it saw then, was this output reasonable?
- Test the explanation by predicting what a change will do before you make it.
If the agent is still causing damage, stop or limit it, preserve the evidence and debug afterward (Loops, Performance, Incidents and Maturity).
State inspection and timelines
A timeline lists steps with their times. State inspection shows what the agent held at each one. Together they answer "what did it know when it decided?"
| Capture per step | Helps you see |
|---|---|
| Assembled context: sources, sizes, truncation | Missing or crowded-out information |
| Memory read and written | Stale or wrong remembered facts |
| Task state and plan | Skipped, repeated or abandoned work |
| Tool choice and arguments | Wrong tool or wrong values |
| Result and validation | Errors treated as success |
| Budget left and stop reason | Why it ended |
Workflow engines and frameworks that save checkpoints let you view state between steps, and some let you resume from one (Graphs, State Machines, Parallelism and Sagas). Capture references and hashes where full content is too sensitive (Safe Logging, Sampling and Retention).
Tool-calling failures
| Symptom | Likely cause | Check |
|---|---|---|
| Wrong tool chosen | Overlapping names or vague descriptions; too many tools | Compare descriptions; test selection cases |
| Invalid arguments | Loose schema, unclear units or formats | Validation errors by field |
| Valid but wrong values | ID copied from the wrong record, invented value | Trace where the value first appeared |
| Timeout, then duplicate action | Retry without idempotency | Query the system of record |
| "Success" with nothing changed | Error hidden in a normal response | Check status mapping and verify effects |
| Result ignored | Too long, badly structured or truncated | Look at what reached the model |
| Permission refused | Missing scope or policy block | Policy decision record |
See Reliable Tool Execution and Error Recovery for designs that prevent many of these and Fix Tool Calling and Invalid JSON Errors for a catalog of fixes.
Walk a tool failure from outside in
- Effect: what does the system of record show?
- Response: what did the tool return, and what did the model receive after processing?
- Execution: did the call reach the service, once or several times?
- Gate: what did validation and policy decide?
- Request: which arguments did the model propose?
- Offer: which tools and descriptions did the model see?
Stop at the first layer that behaved wrongly. If the model chose well from poor descriptions, rewrite the description; if it chose badly from good ones, add selection cases and consider offering fewer tools.
Planning and reasoning failures
| Pattern | What you see | Usual remedy |
|---|---|---|
| Goal drift | Later steps serve a different aim | Restate the goal and constraints in state |
| Missing step | A check never happens | Make it a workflow step in code |
| Premature finish | Claims done without evidence | Require verifiable completion checks |
| No stop | Keeps searching or polishing | Budgets and progress rules |
| Wrong assumption | Acts on something never confirmed | Require a lookup or a question first |
| Ignored error | Continues as if the call worked | Structured errors and control logic |
The model's written reasoning can suggest where to look, but it may not reflect what drove the output. Test by changing what the model saw and watching whether behavior changes over several trials. If a rule must always hold, enforce it in code rather than rewording the prompt again.
RAG failures
Split the pipeline and test each part with the same question.
| Finding | Look at |
|---|---|
| Fact missing or outdated in sources | Content ownership and refresh |
| Present in source, absent in index | Parsing, tables, permissions, failed jobs |
| In index, not retrieved | Query wording, filters, chunking, hybrid search, ranking |
| Retrieved, then dropped | Context limits, deduplication, order |
| Present, answer still wrong | Conflicting passages, instructions, model limits |
| Cited source does not support the claim | Grounding checks and citation handling |
| Wrong user sees a document | Access filters: treat as a security incident |
RAG Evaluation, Grounding and Debugging gives measures for each stage.
Three quick retrieval experiments
| Experiment | If it now works |
|---|---|
| Give the model the correct passage by hand | The fault is before the answer step |
| Search with the document's own wording | Query rewriting or matching needs work |
| Remove filters in an isolated test with permitted data | Metadata or filter logic is wrong |
Never remove access filters against real restricted data to debug. Use a test index with synthetic documents.
Multi-agent handoff failures
| Failure | Sign in the trace | Remedy |
|---|---|---|
| Lost context | Receiver asks again or guesses | A typed handoff message with required fields |
| Wrong receiver | Repeated transfers | Clear routing rules and a fallback owner |
| Ping-pong | Two agents return work to each other | Transfer limit and a final decider |
| Duplicate work | Two branches change one record | Ownership, locks or version checks |
| Silent drop | No completion and no error | Deadlines and acknowledgments |
| Error laundering | A guess becomes a "fact" downstream | Carry sources and status with claims |
First check that the trace is connected. A missing parent link can make a handoff look like two unrelated successes.
Replay a run safely
Replay feeds recorded results back to the agent, so you can test a change without calling live systems. Substitute one step at a time, then find the first place the new run differs.
"""Replay a recorded run against new code and find the first divergence."""
import json
RECORDED = [ # captured from the failing run
{"step": "retrieve", "in": {"q": "return window"},
"out": {"doc": "policy-2024", "days": 14}},
{"step": "order", "in": {"id": "A-7"},
"out": {"delivered_days_ago": 21}},
{"step": "decide", "in": {"days": 14, "age": 21},
"out": {"eligible": False}},
]
class Replay:
"""Serve recorded results; never touch live systems."""
def __init__(self, tape):
self.tape, self.position, self.log = tape, 0, []
def call(self, step, args, live=None):
entry = self.tape[self.position] if self.position < len(self.tape) else None
self.position += 1
if live is not None: # the one step under test runs for real
result = live(**args)
elif entry and entry["step"] == step and entry["in"] == args:
result = entry["out"]
else:
raise LookupError(f"no recording for {step} {json.dumps(args)}")
self.log.append({"step": step, "in": args, "out": result})
return result
def current_policy(q):
return {"doc": "policy-2026", "days": 30}
def agent(io, retriever=None):
policy = io.call("retrieve", {"q": "return window"}, live=retriever)
order = io.call("order", {"id": "A-7"})
age = order["delivered_days_ago"]
return io.call("decide", {"days": policy["days"], "age": age},
live=lambda days, age: {"eligible": age <= days})
def first_difference(before, after):
for number, (a, b) in enumerate(zip(before, after), 1):
for field in ("step", "in", "out"):
if a[field] != b[field]:
return number, a["step"], field, a[field], b[field]
return None
same = Replay(RECORDED)
print("Reproduced:", agent(same), "| diverges:", first_difference(RECORDED, same.log))
fixed = Replay(RECORDED)
print("With current retriever:", agent(fixed, retriever=current_policy))
number, step, field, old, new = first_difference(RECORDED, fixed.log)
print(f"First difference at step {number} ({step}), field '{field}'")
print(" before:", old)
print(" after: ", new)
Output:
Reproduced: {'eligible': False} | diverges: None
With current retriever: {'eligible': True}
First difference at step 1 (retrieve), field 'out'
before: {'doc': 'policy-2024', 'days': 14}
after: {'doc': 'policy-2026', 'days': 30}
The faithful replay reproduces the refusal exactly. Swapping in only the current retriever changes the first step's output from a 14-day policy to a 30-day one, and the decision flips. The cause was stale retrieval, not the decision logic. A real agent also needs recorded or repeated model responses, and the replay should fail loudly, as here, when asked for something it has not recorded.
What replay cannot promise
- Model output may vary between calls even with the same settings, and hosted models can change.
- Once a new run takes a different path, old recordings no longer cover it.
- Time, randomness, concurrency and external state need to be recorded or controlled.
- Sensitive content may have been removed, so you may have to rebuild it synthetically.
Run it in an isolated environment with no production credentials. A replay that resends payments or emails turns a bug hunt into a second incident.
When failures are intermittent
Run the case many times and compare rates before and after a change. Going from 3 failures in 10 to 0 in 10 is encouraging but weak evidence: with a true failure rate of 30 percent, ten clean runs would still happen about 3 times in 100. Use more trials for rare or serious faults, and check that other cases did not get worse (Chaos, Recovery Testing and Release Gates).
Compare good and bad runs
Pick a successful run similar to the failed one and lay them side by side. Compare versions, context sources, tool arguments, results, order of steps and timing. Differences narrow the search quickly. Group many failures by version, tool, language, tenant and hour; a cluster often points at a deployment or a dependency rather than the model.
Write a useful bug record
| Field | Example |
|---|---|
| Symptom | Eligible return refused |
| Run and versions | r-3307, agent 2.4.0, index build 118 |
| First wrong step | Retrieval returned the previous policy |
| Cause | Old document not removed at refresh |
| Fix | Delete superseded versions; filter by effective date |
| Guard | Regression case and freshness alert |
| Others affected | Query of runs that retrieved the old document |
Do not close a record at "the model hallucinated". Ask why the system let an unsupported claim become an answer or an action, and fix that control too.
Build a small debugging kit
- A run viewer that opens a trace from a support reference.
- An export command that writes a run's recorded inputs and results to a protected test file.
- A replay harness with fake tools that refuse any unrecorded call.
- A comparison view for two runs or two versions.
- A repeat runner that reports a failure rate over many trials.
- A fault list of known causes with the quickest check for each.
Each tool shortens the next investigation. Give the export command the same access rules as the logs it reads, and expire the files it creates, because a debugging copy is still a copy of someone's data.
Questions to ask a user who reports a problem
- What were you trying to do?
- What did you expect, and what happened instead?
- When was it, and do you have the reference shown on screen?
- Has it worked before, and what changed on your side?
- Is anything still wrong now, such as a charge or a message already sent?
Know when to stop digging
Set a time box. If the cause is still unclear, reduce the risk with a tighter limit, an approval step or a rollback, record what has been ruled out and ask a second person to review the trace with fresh eyes. An open question with a safeguard around it is better than a confident explanation nobody has tested. Reopen the case when the same symptom returns or a new trace adds evidence.
Common mistakes
| Mistake | Better approach |
|---|---|
| Starting from the final answer | Find the first wrong step |
| Editing the prompt first | Classify the layer before changing anything |
| Changing several things together | One change, then measure |
| Declaring victory after one good run | Repeat and compare rates |
| Replaying against live systems | Isolate and use recordings |
| Fixing one user's case only | Search for others affected |
Debugging checklist
- Symptom, expectation, run ID and versions are written down.
- The trace is complete across agents.
- The first wrong step is identified and classified.
- The case reproduces in isolation, or its failure rate is measured.
- One change is tested at a time.
- Controls that let the fault have effect are reviewed.
- A regression case and a monitor are added.
- Other affected runs and people are found.
Frequently asked questions
What if there is no trace of the failed run?
Reproduce from the user's description, then add the missing instrumentation before closing the case.
Does setting temperature to zero make runs repeatable?
It reduces variation in many systems but does not guarantee identical output, especially across model or infrastructure changes.
Can another model diagnose the trace?
It can suggest suspects, but verify each against records and protect the tool from instructions hidden in the trace.
When should we change the model?
After checking context, tools and controls, and only when evaluation on your cases shows the new model is better.
References and further reading
- Google SRE Book: effective troubleshooting: a hypothesis-driven method.
- OpenTelemetry: traces: reading spans and context.
- LangGraph persistence: an example of saved state and checkpoints.
- Temporal workflows: replay in durable execution.
Next steps
Loops, Performance, Incidents and Maturity
Handle failures at scale.
Context Poisoning, Distraction, Confusion, Clash and Rot
Understand what goes wrong in context.
Continuous Evaluation, Statistics and Scorecards
Turn fixes into lasting checks.