Fix Loops, Memory, Handoff, RAG and SQL Errors

Five stubborn symptoms, one method: find what the agent saw at the moment it went wrong.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library, including SQLite. The tables, steps and numbers are invented.

Beginner Recognize the symptom

Symptom map

You seeLook first atSection
Same call again and againTool results and stop rulesLoops
Asks for something already givenWhat was sent in the latest requestForgetting
Uses an outdated factSource and age of the factStale context
Confident answer from the wrong pageRetrieved passages and filtersRetrieval
Plausible but wrong numberThe query and metric definitionSQL
Work lost between agentsThe handoff message and ownershipDelegation

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

CauseClueFix
No stop conditionKeeps "improving" a finished resultDefine done and verify it in code
Unhelpful errorRepeats the same failing callSay what to change and when not to retry
Empty result treated as try againSlight rewordings of one searchMark empty as a valid outcome; cap searches
Result not visibleRe-reads the same itemKeep results in state; check truncation
Impossible goalCycles among alternativesAllow an honest "cannot complete"
Agents bouncing workHandoffs back and forthNamed 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

LayerRuleWhen it fires
Goal checkCode confirms the outcome existsEnd successfully
Repeat guardSame call, or same result, several timesTell the model; then stop
Progress guardNo new facts or state change in several stepsAsk for help or hand over
BudgetMaximum steps, time and spendStop with a summary of partial work
External stopUser cancel or operator switchStop 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".

Intermediate State and memory

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

ProblemRemedy
Cached data outlives the sourceExpiry times and invalidation on change
Old and new memories both presentReplace or mark superseded; keep timestamps
Document versions mixed in the indexVersion and effective-date metadata; remove retired content
User statement conflicts with a recordState which source is authoritative; ask when unsure
Agents hold different copies of stateOne shared record with version checks on writes
Wrong date assumedSupply 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 breaksCheckFix
IngestionIs the document indexed and readable?Repair parsing; reprocess failures
ChunkingIs the answer split from its heading or table?Structure-aware chunks with titles
QueryDoes the search text lack names or context?Rewrite with conversation context
MatchingExact codes or terms missed?Combine keyword and vector search
RankingRight passage present but low?Rerank; adjust how many are kept
FiltersWrong product, region, date or permission?Fix metadata and apply filters before ranking
Index driftEmbedding model or settings changed?Rebuild consistently and version the index
GenerationRight 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).

Expert Queries and teams

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.

FaultExampleDefense
Join fan-outTotals repeated per child rowAggregate before joining; test row counts and keys
Wrong definitionRevenue includes refunds or taxGoverned metrics in a semantic layer
Wrong time windowTime zone or fiscal calendar ignoredState both explicitly; show the dates used
Missing filterTest or deleted records countedViews that already apply the rules
NullsRows silently excluded from a conditionHandle them deliberately and report counts
Wrong tableStale copy or similar nameCurate 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

Illustrative case: the wrong returns policy

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

Capturetrace
Rebuildcontext
Isolateone part
Fixand test

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

MeasurePrevents or reveals
Step, time and spend limitsEndless loops
Typed state with versionsForgotten facts and lost updates
Source and date on every factStale and conflicting context
Retrieval test set in the pipelineSilent index regressions
Trusted figures for common questionsWrong queries
Handoff schema with required statusLost and falsely successful work

Common mistakes

MistakeBetter approach
Raising the step limit to cure a loopFind why progress stops
Putting the whole history in every requestKeep structured state and select context
Blaming the model for retrieval errorsInspect retrieved passages first
Trusting a query because it ranCheck keys, definitions and trusted totals
Adding another agent to superviseClarify ownership and the handoff contract first
Deleting a bad memory onlyAlso 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

Next steps