Debugging Agents, RAG and Handoffs

Do not guess from the final answer. Find the first step where reality and expectation parted.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner A method that works

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

Collecttrace, versions, user report
Locatefirst wrong step
Classifywhich layer failed
Replaysafely, repeatedly
Fixone change at a time
Guardtest and monitor
  1. State the symptom precisely: what happened, what should have happened and who noticed.
  2. Gather the trace, agent and model versions, configuration, time and affected records.
  3. Read forward from the start. The last error is often a result of an earlier mistake.
  4. Ask at each step: given what it saw then, was this output reasonable?
  5. Test the explanation by predicting what a change will do before you make it.
Contain first when harm continues

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 stepHelps you see
Assembled context: sources, sizes, truncationMissing or crowded-out information
Memory read and writtenStale or wrong remembered facts
Task state and planSkipped, repeated or abandoned work
Tool choice and argumentsWrong tool or wrong values
Result and validationErrors treated as success
Budget left and stop reasonWhy 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).

Intermediate Failure by layer

Tool-calling failures

SymptomLikely causeCheck
Wrong tool chosenOverlapping names or vague descriptions; too many toolsCompare descriptions; test selection cases
Invalid argumentsLoose schema, unclear units or formatsValidation errors by field
Valid but wrong valuesID copied from the wrong record, invented valueTrace where the value first appeared
Timeout, then duplicate actionRetry without idempotencyQuery the system of record
"Success" with nothing changedError hidden in a normal responseCheck status mapping and verify effects
Result ignoredToo long, badly structured or truncatedLook at what reached the model
Permission refusedMissing scope or policy blockPolicy 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

  1. Effect: what does the system of record show?
  2. Response: what did the tool return, and what did the model receive after processing?
  3. Execution: did the call reach the service, once or several times?
  4. Gate: what did validation and policy decide?
  5. Request: which arguments did the model propose?
  6. 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

PatternWhat you seeUsual remedy
Goal driftLater steps serve a different aimRestate the goal and constraints in state
Missing stepA check never happensMake it a workflow step in code
Premature finishClaims done without evidenceRequire verifiable completion checks
No stopKeeps searching or polishingBudgets and progress rules
Wrong assumptionActs on something never confirmedRequire a lookup or a question first
Ignored errorContinues as if the call workedStructured 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.

Sourcedoes the fact exist?
Indexwas it ingested well?
Retrievewas it found?
Assembledid it reach the model?
Answerwas it used faithfully?
FindingLook at
Fact missing or outdated in sourcesContent ownership and refresh
Present in source, absent in indexParsing, tables, permissions, failed jobs
In index, not retrievedQuery wording, filters, chunking, hybrid search, ranking
Retrieved, then droppedContext limits, deduplication, order
Present, answer still wrongConflicting passages, instructions, model limits
Cited source does not support the claimGrounding checks and citation handling
Wrong user sees a documentAccess filters: treat as a security incident

RAG Evaluation, Grounding and Debugging gives measures for each stage.

Three quick retrieval experiments

ExperimentIf it now works
Give the model the correct passage by handThe fault is before the answer step
Search with the document's own wordingQuery rewriting or matching needs work
Remove filters in an isolated test with permitted dataMetadata 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

FailureSign in the traceRemedy
Lost contextReceiver asks again or guessesA typed handoff message with required fields
Wrong receiverRepeated transfersClear routing rules and a fallback owner
Ping-pongTwo agents return work to each otherTransfer limit and a final decider
Duplicate workTwo branches change one recordOwnership, locks or version checks
Silent dropNo completion and no errorDeadlines and acknowledgments
Error launderingA guess becomes a "fact" downstreamCarry 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.

Expert Replay and reproduction

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.
Replay must not act

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

FieldExample
SymptomEligible return refused
Run and versionsr-3307, agent 2.4.0, index build 118
First wrong stepRetrieval returned the previous policy
CauseOld document not removed at refresh
FixDelete superseded versions; filter by effective date
GuardRegression case and freshness alert
Others affectedQuery 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

  1. What were you trying to do?
  2. What did you expect, and what happened instead?
  3. When was it, and do you have the reference shown on screen?
  4. Has it worked before, and what changed on your side?
  5. 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

MistakeBetter approach
Starting from the final answerFind the first wrong step
Editing the prompt firstClassify the layer before changing anything
Changing several things togetherOne change, then measure
Declaring victory after one good runRepeat and compare rates
Replaying against live systemsIsolate and use recordings
Fixing one user's case onlySearch 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

Next steps