Fix Loops, Memory, Handoff, RAG and SQL Errors
Five stubborn symptoms, one method: find what the agent saw at the moment it went wrong.
Read the trace and ask what information the agent had at the failing step. Loops need progress checks and hard limits. Forgetting needs explicit state. Wrong documents need retrieval tested on its own. Bad SQL needs definitions and result checks. Failed delegation needs clear handoff contracts.
What you will learn: diagnostic steps and fixes for loops, lost or stale context, memory conflicts, poor retrieval, incorrect queries and multi-agent handoffs.
Prerequisites: Debugging Agents, RAG and Handoffs and What Is Context Engineering? Stack and Token Budgets.
The example runs in November 2026 with Python 3.13 and only the standard library, including SQLite. The tables, steps and numbers are invented.
Symptom map
| You see | Look first at | Section |
|---|---|---|
| Same call again and again | Tool results and stop rules | Loops |
| Asks for something already given | What was sent in the latest request | Forgetting |
| Uses an outdated fact | Source and age of the fact | Stale context |
| Confident answer from the wrong page | Retrieved passages and filters | Retrieval |
| Plausible but wrong number | The query and metric definition | SQL |
| Work lost between agents | The handoff message and ownership | Delegation |
In each case, resist editing the prompt first. Reconstruct the exact context at the failing step. If the needed information was absent, wrong or buried, wording changes will not help much.
Agent loops
| Cause | Clue | Fix |
|---|---|---|
| No stop condition | Keeps "improving" a finished result | Define done and verify it in code |
| Unhelpful error | Repeats the same failing call | Say what to change and when not to retry |
| Empty result treated as try again | Slight rewordings of one search | Mark empty as a valid outcome; cap searches |
| Result not visible | Re-reads the same item | Keep results in state; check truncation |
| Impossible goal | Cycles among alternatives | Allow an honest "cannot complete" |
| Agents bouncing work | Handoffs back and forth | Named owner and a handoff limit |
Detect loops by progress, not only by identical calls: a changed query that returns the same material is still going nowhere. Loops, Performance, Incidents and Maturity shows a run guard with step and spend limits.
Two checks you can run
The first check spots a repeated result under different inputs. The second compares an agent's query with a trusted figure and finds rows counted twice.
"""Two quick checks: is the agent looping, and did its SQL double count?"""
import json
import sqlite3
def find_loop(steps, window=6, limit=3):
"""Flag a tool that keeps returning the same result, even with new arguments."""
seen = {}
for number, (tool, args, result) in enumerate(steps, 1):
key = json.dumps([tool, result], sort_keys=True)
recent = [n for n in seen.get(key, []) if number - n < window] + [number]
seen[key] = recent
if len(recent) >= limit:
return f"loop: {tool} gave the same result at steps {recent}"
return "no loop found"
STEPS = [
("search", {"q": "invoice 77"}, "no results"),
("search", {"q": "invoice #77"}, "no results"),
("list_folders", {}, ["2026"]),
("search", {"q": "inv-77"}, "no results"),
("search", {"q": "77 invoice"}, "no results"),
]
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders(id INTEGER, total INTEGER);
CREATE TABLE items(order_id INTEGER, name TEXT);
INSERT INTO orders VALUES (1, 100), (2, 50);
INSERT INTO items VALUES (1, 'pen'), (1, 'pad'), (1, 'ink'), (2, 'pen');
""")
agent_sql = "SELECT SUM(o.total) FROM orders o JOIN items i ON i.order_id = o.id"
trusted_sql = "SELECT SUM(total) FROM orders"
duplicated = ("SELECT o.id, COUNT(*) FROM orders o JOIN items i ON i.order_id = o.id "
"GROUP BY o.id HAVING COUNT(*) > 1")
if __name__ == "__main__":
print(find_loop(STEPS))
print()
print("agent query total: ", db.execute(agent_sql).fetchone()[0])
print("trusted total: ", db.execute(trusted_sql).fetchone()[0])
print("orders repeated by the join (id, copies):", db.execute(duplicated).fetchall())
Output:
loop: search gave the same result at steps [1, 2, 4]
agent query total: 350
trusted total: 150
orders repeated by the join (id, copies): [(1, 3)]
The searches differ in wording yet keep returning nothing, so a guard that compared only arguments would miss them. Keying on the tool and its result catches this, at the cost of possible false alarms for tools that normally reply with the same short status, which need their own rule. The query runs without any error and returns more than twice the trusted number, because joining orders to their items repeats an order once for each item.
Design stop rules in layers
| Layer | Rule | When it fires |
|---|---|---|
| Goal check | Code confirms the outcome exists | End successfully |
| Repeat guard | Same call, or same result, several times | Tell the model; then stop |
| Progress guard | No new facts or state change in several steps | Ask for help or hand over |
| Budget | Maximum steps, time and spend | Stop with a summary of partial work |
| External stop | User cancel or operator switch | Stop safely and report effects |
Legitimate polling can look like a loop, so mark waiting tools and give them delays and deadlines of their own. When a guard fires, keep what was learned: a clear account of the attempts is far more useful to a person than "maximum steps exceeded".
The agent forgets context
A model call knows only what is in that request, apart from what it learned in training. "Forgetting" means your system did not include something, included it where it was lost among other material or replaced it with a poor summary.
- Inspect the final assembled request, not the chat window.
- Check trimming: which messages are dropped when the window fills?
- Check summaries: did they keep decisions, constraints, identifiers and failures?
- Keep structured state for facts that must survive, such as the order number and what is already done.
- Check scoping: is the session or user identifier consistent across requests and servers?
- Confirm writes: was the memory ever saved?
See Context Assembly, Retrieval, Compression and Caching and Stateful and Long-Running Agent Architecture.
Stale context and conflicts
| Problem | Remedy |
|---|---|
| Cached data outlives the source | Expiry times and invalidation on change |
| Old and new memories both present | Replace or mark superseded; keep timestamps |
| Document versions mixed in the index | Version and effective-date metadata; remove retired content |
| User statement conflicts with a record | State which source is authoritative; ask when unsure |
| Agents hold different copies of state | One shared record with version checks on writes |
| Wrong date assumed | Supply the current date and time zone |
Decide precedence before conflicts happen, for example: live system of record, then approved policy, then recent user statement, then older memory. Carry source and age with each fact so the rule can be applied (Memory Write, Recall and Forgetting Policies). If a wrong memory may have influenced actions, find every run that read it.
State that survives
Keep facts that must not be lost in a small structured record that your code maintains and places in each request.
{
"goal": "move order 1 delivery to Friday",
"order_id": 1,
"constraints": ["no extra charge"],
"done": ["checked shipments"],
"failed": ["carrier slot lookup timed out once"],
"waiting_for": null,
"version": 4
}
Update it from verified tool results, not from the model's description of them. The version number lets a store reject a write based on an old copy, which turns a silent overwrite into a visible conflict that can be retried.
Retrieval returns wrong documents
Split the question: was the right passage retrieved, and was it used correctly? Look at the returned passages for a failing query before touching the answer prompt.
| Where it breaks | Check | Fix |
|---|---|---|
| Ingestion | Is the document indexed and readable? | Repair parsing; reprocess failures |
| Chunking | Is the answer split from its heading or table? | Structure-aware chunks with titles |
| Query | Does the search text lack names or context? | Rewrite with conversation context |
| Matching | Exact codes or terms missed? | Combine keyword and vector search |
| Ranking | Right passage present but low? | Rerank; adjust how many are kept |
| Filters | Wrong product, region, date or permission? | Fix metadata and apply filters before ranking |
| Index drift | Embedding model or settings changed? | Rebuild consistently and version the index |
| Generation | Right passage, wrong answer? | Require citations; remove conflicting text |
Build a small set of questions with the passage each should find, and measure that before and after changes (RAG Evaluation, Grounding and Debugging, Embeddings, Vector and Hybrid Search, Reranking).
SQL agents return wrong results
A query error is the easy case. The costly one is a query that runs and answers a different question.
| Fault | Example | Defense |
|---|---|---|
| Join fan-out | Totals repeated per child row | Aggregate before joining; test row counts and keys |
| Wrong definition | Revenue includes refunds or tax | Governed metrics in a semantic layer |
| Wrong time window | Time zone or fiscal calendar ignored | State both explicitly; show the dates used |
| Missing filter | Test or deleted records counted | Views that already apply the rules |
| Nulls | Rows silently excluded from a condition | Handle them deliberately and report counts |
| Wrong table | Stale copy or similar name | Curate the schema offered; describe columns |
Keep access read-only and scoped to the user, limit time and rows, show the query and assumptions with the answer, and test against figures your data owners have approved (Safe SQL, Permissions and Evaluation, Semantic Layers and Business Metrics for AI).
Multi-agent delegation and handoff failures
- Missing context: the receiver gets a task name but not the goal, constraints or what was tried. Send a structured brief.
- Unclear ownership: two agents act, or none does. Assign one owner per task at each moment.
- Wrong specialist: overlapping role descriptions confuse routing. Sharpen them and test routing as a classification problem.
- Silent failure: a worker's error is summarized as success. Return explicit status and evidence.
- Lost result: the reply arrives after a timeout. Use task identifiers and reconcile late results.
- Scope growth: delegated agents gain more access than the requester. Pass down only what the task needs.
{
"task_id": "t-318",
"goal": "confirm delivery date for order 1",
"known": {"shipments": 2},
"constraints": ["read only", "reply within 60 seconds"],
"return": ["status", "date", "evidence", "open_questions"]
}
First ask whether the handoff is needed at all. A single agent with good tools has fewer places to lose information (Single-Agent vs Multi-Agent Systems, Handoffs, Routing, Shared State and Communication).
A worked diagnosis
Report: a customer was told returns are allowed for 60 days; the policy says 30.
Trace: retrieval returned two passages, one from a retired holiday policy, ranked first.
Cause: the retired document stayed in the index and had no end date.
Immediate fix: remove it and find other answers that cited it.
Lasting fix: require effective and end dates, filter on them before ranking and fail ingestion when they are missing.
Test: the question joins the retrieval set, with a check that retired content never appears.
No prompt change would have been reliable here: the model was given conflicting evidence and picked one. The repair belongs in the data and the filter.
A shared method
Isolate by replacing one part at a time with a known good value: supply the correct passage by hand, a verified tool result or a hand-written plan. If the run then succeeds, you have found the weak part. Add the failure to the regression set and watch a metric that would show its return.
Know when to ask for help
Several of these failures end better when the agent stops and says what it lacks. Define the situations in which it must ask the user or hand over: a required identifier is missing, two authoritative sources disagree, retrieval finds nothing relevant, a query result fails a sanity check or a delegated task returns no evidence. Test these paths like any other feature. A clear question such as "I found two delivery dates for this order; which shipment do you mean?" resolves in seconds what a loop or a guess would turn into a support case.
Make the handover useful by including the goal, the facts already verified, the actions already taken and the specific decision needed, so the person does not have to start again (Progress, Approval, Undo and Handoff UX).
Prevention measures
| Measure | Prevents or reveals |
|---|---|
| Step, time and spend limits | Endless loops |
| Typed state with versions | Forgotten facts and lost updates |
| Source and date on every fact | Stale and conflicting context |
| Retrieval test set in the pipeline | Silent index regressions |
| Trusted figures for common questions | Wrong queries |
| Handoff schema with required status | Lost and falsely successful work |
Common mistakes
| Mistake | Better approach |
|---|---|
| Raising the step limit to cure a loop | Find why progress stops |
| Putting the whole history in every request | Keep structured state and select context |
| Blaming the model for retrieval errors | Inspect retrieved passages first |
| Trusting a query because it ran | Check keys, definitions and trusted totals |
| Adding another agent to supervise | Clarify ownership and the handoff contract first |
| Deleting a bad memory only | Also trace which runs used it |
Troubleshooting checklist
- The failing step and its full context are reconstructed.
- Loops are detected by lack of progress and capped.
- Required facts live in explicit state.
- Facts carry source, date and precedence.
- Retrieval is measured separately from answering.
- Queries are checked against approved figures.
- Handoffs have an owner, a schema and a status.
- Each fixed failure has a regression case.
Frequently asked questions
Will a larger context window stop forgetting?
It can reduce trimming, but selection, state and summaries still decide whether the right facts are used well.
Why does retrieval work in tests but not for users?
Real questions use other words, depend on earlier turns or hit permission filters, so sample them into your test set.
Can the agent check its own SQL?
A second pass may catch some mistakes, but verified definitions, key checks and trusted totals give firmer evidence.
How many handoffs are too many?
Set a limit from your real workflows and investigate any run that reaches it or returns to a previous owner.
References and further reading
- Anthropic: effective context engineering for AI agents: managing what the model sees.
- Anthropic: how a multi-agent research system was built: delegation lessons.
- Why Do Multi-Agent LLM Systems Fail?: a taxonomy of failures.
- SQLite SELECT documentation: how joins and aggregates are evaluated.
Next steps
Fix Latency, Cost, Deployment and Score Regressions
Fix slow, costly and regressed agents.
Parallelism, Deadlocks and Conflict Resolution
Handle disagreeing agents.
RAG Security, Freshness and Cost
Keep an index healthy.