Lesson 7.4: Loops, drift and runaway cost: finding and fixing failures
Learn the three common agent failures, loops, drift and runaway cost, and how to detect them, cap the damage, add checkpoints and debug from traces.
By the end of this lesson you will be able to recognise the three common failures of a working agent, loops, drift and runaway cost, set detection and limits that stop each before it does much harm, add checkpoints that bring a wandering agent back, and read a failed run to find its cause. You will work out that capping each run at five times its normal cost cuts a day's spend from ₹29,850 to ₹15,600 when 1 per cent of runs would otherwise run away to 100 times the cost, and that a 1 per cent chance of drifting off track at each step leaves a 30-step run on track only 74 per cent of the time, rising to 94 per cent with a checkpoint every ten steps that catches 80 per cent of the drift. You should have read Lessons 5.4, 7.1 and 7.2. No code is needed. The mathematics is powers and multiplication.
The last lesson dealt with an attacker who wants to hijack an agent. Most of the trouble an agent causes comes from no attacker at all. A model that is trying to do its job can still get stuck, wander off or spend far more than it should, and because an agent runs for many steps without a person watching, a small fault can grow before anyone notices. This lesson names three families of failure, shows how to catch each early and gives a method for finding the cause when a run goes wrong.
Failure one: loops
A loop is when the agent repeats itself without making progress. It calls the same tool with the same arguments, gets the same result and decides to do it again. Or it alternates between two actions: search, read, search, read. Or it tries a fix, sees the same error, tries a slightly different fix and sees the same error, indefinitely.
Loops arise for several reasons.
The tool fails in a way the model does not understand. A vague error such as "failed" gives the model nothing to change, so it retries. Lesson 2.3 covered writing errors that say what to do differently.
The task cannot be done as stated. The record does not exist, the permission is missing or the goal is contradictory. A model asked to succeed keeps trying instead of saying so.
The stop condition is unclear. The agent does not know when it has finished, so it keeps checking and improving.
A result looks like a partial success. The agent sees progress, such as a changed error message, and persists.
Two agents hand work back and forth, as Lesson 5.3 warned.
Detecting and breaking loops
Four controls work together.
A step cap. A hard limit on steps per run, such as 20. When reached, the run stops and hands back. It is crude and effective.
Repeat detection. Keep a record of the last calls. If the same tool is called with the same arguments three times in a row, or the last six calls cycle through two actions, intervene. Intervening can mean adding a message to the context, "You have tried this three times with the same result. Do not repeat it. Try something different or report that you cannot proceed", and, if that fails, stopping the run.
Progress checks. Every few steps, check that something has changed: a new fact found, a state changed, a sub-goal done. If nothing has changed in five steps, the agent is probably stuck.
A way to give up. Make "I cannot complete this, and here is why" a normal, accepted outcome, with a tool or format for it. An agent with no way to stop except success will keep trying. Say in the instructions that reporting a blocker is better than guessing or retrying forever.
A word on retries. Retrying a failed call is often right: a network blip may clear. But retries need a limit, a delay that grows between tries and a rule that only temporary errors are retried. Retrying a permission error ten times achieves nothing.
Failure two: drift
Drift is when an agent gradually moves away from its goal or its instructions. Each step looks reasonable, and the run ends somewhere it should not be. Examples:
A research agent asked to compare three products starts following an interesting side topic and returns a report on something else.
A coding agent fixing one bug begins refactoring unrelated code.
An agent that began with careful, polite replies becomes terse and skips checks late in a long run.
An agent forgets a constraint stated at the start, such as "do not contact the customer", because it is now buried deep in a long context.
Drift has a few causes. The context grows and early instructions lose weight. Each step is conditioned on the previous steps, including earlier small mistakes, so errors compound. The agent optimises the nearest sub-goal and loses sight of the real one. And long runs give more steps in which to go wrong.
Why long runs drift
A simple model shows the effect. Suppose at each step there is a 1 per cent chance that the agent takes a step that moves it off track and does not recover. After n steps the chance that it is still on track is 0.99ⁿ. At 10 steps that is 90.4 per cent. At 30 steps it is 0.99³⁰ = 73.97 per cent, about 74 per cent. At 60 steps it is 54.7 per cent. A fault rate that sounds small becomes a coin toss over a long run. Real drift is not this tidy, but the shape holds: longer runs are less reliable, and the loss accelerates.
Checkpoints
The remedy is to stop long runs from being one long stretch. A checkpoint is a point at which the agent, or a separate check, compares progress with the goal and corrects course. Four kinds are common.
Restating the goal. Every few steps, insert the original goal and constraints back into the context, so that they are fresh. It costs a few tokens and helps surprisingly.
A plan with progress marks. Have the agent keep a short plan and mark steps done. At each checkpoint it reads the plan and checks the next step still serves the goal, as Lesson 4.1 described.
A separate reviewer. A second call compares the work so far with the goal and the constraints, and says whether it is on track. It has no stake in the path taken, so it sees drift that the agent does not.
A summary and restart. For very long tasks, summarise the state, discard the old context and continue from the summary with the goal restated, as Lesson 4.3 covered. This also keeps the context small.
Return to the model. Say a checkpoint occurs every 10 steps and catches and corrects drift 80 per cent of the time. In a 10-step segment, the chance of no drift is 0.99¹⁰ = 0.904. The chance of drifting is 0.096, and the checkpoint rescues 80 per cent of those, which is 0.077. So a segment ends on track with probability 0.904 + 0.077 = 0.981. Three segments, a 30-step run, give 0.981³ = 0.944, or 94.4 per cent. The checkpoints lift a 30-step run from 74 to 94 per cent. A checkpoint that catches only half the drift would give 0.904 + 0.048 = 0.952 per segment and 0.952³ = 86.3 per cent, still a large gain.
Predict first: a run has 30 steps, and at each step there is a 1 per cent chance of going off track for good. Without any checkpoint, about what share of runs stay on track? Then, if a checkpoint every 10 steps catches 80 per cent of drift, what share stay on track? Decide before reading on.
The answers are about 74 per cent and 94 per cent.
Failure three: runaway cost
A runaway is a run that spends far more than it should, in tokens, tool calls, money or time. It is often a loop or drift that was not stopped. It matters because agent costs are not capped by nature. A person who gets stuck stops for lunch. An agent keeps spending.
Runaway cost has several routes.
A loop that is not stopped by a cap.
A growing context. Each step re-sends history, so the cost of step n grows with n, as Lesson 7.2 of the AI Engineering track explained. A run twice as long can cost four times as much.
An expensive tool called many times, such as a paid search or a large model.
Fan-out. A lead that starts workers that start workers, each of which loops.
Large results. One tool returns a whole file or 10,000 rows into the context, and every later step pays for it.
Retries on a large call.
Capping the damage
Controls are cheap, and should be in place before launch.
Per-run limits on steps, tokens, money and time. When one is reached, stop and hand back.
Per-user and per-day budgets, so that no one user or day can consume everything.
Limits on fan-out: the number of workers, the depth of delegation and the number running at once, as Module 5 covered.
Limits on tool results, such as a maximum number of rows or characters, with a clear note if cut.
Cost tracking in real time, with an alert when a run or a day exceeds a threshold, and a switch to stop everything.
How much does a per-run cap save? Suppose an agent handles 5,000 runs a day at a normal cost of ₹3 a run, which is ₹15,000. Suppose 1 per cent of runs, 50 of them, run away to 100 times the normal cost, ₹300 each. Then:
Without a cap, normal runs cost 4,950 × ₹3 = ₹14,850, and runaways cost 50 × ₹300 = ₹15,000. The total is ₹29,850 a day. Half the bill comes from 1 per cent of runs.
With a cap at five times normal cost, ₹15 per run, the runaways are stopped at ₹15 each. They cost 50 × ₹15 = ₹750. The total is ₹14,850 + ₹750 = ₹15,600 a day.
The cap saves ₹14,250 a day, nearly half the bill, and costs nothing for the 99 per cent of runs that never touch it. The cap must sit above the legitimate high end. If a few real runs truly need ₹20, a ₹15 cap will cut them off, which you detect by checking how many runs hit the cap and why. Set the cap from data, around twice the 95th percentile cost, and review it.
Finding the cause: reading a failed run
When a run fails, loops, drifts or overspends, you need to find out why. Agents leave a trace, the record of every step: the model's output, each tool call with arguments and result, the tokens used and the time. Lesson 8.2 covers traces in detail. Here is a method for reading one.
1. Find the first wrong step. Do not start at the end, where the failure shows. Walk forward until the first step that is wrong, since later steps are often just consequences. A wrong tool choice in step 3 explains the mess in step 9.
2. Ask what the model could see. At that step, what was in the context? Was the needed fact present, absent or buried? Was the tool result clear? Was an instruction missing or in conflict with another? Most errors come from what the model was shown, not from the model being foolish.
3. Classify the cause. A small set of causes covers most failures.
Cause · Sign · FixUnclear instruction · The agent did something reasonable that you did not want · Rewrite the instruction, add an example
Bad tool description or schema · Wrong tool chosen, or wrong arguments · Sharpen the description, add constraints
Unhelpful tool result or error · The agent could not tell what went wrong · Return a clear message and what to do
Missing information · The needed fact was never fetched · Add a tool or a retrieval step
Context overload · The fact was there but buried or old · Summarise, trim results, restate the goal
Task impossible · No path exists · Allow a clean give-up
Model limitation · It reasons wrongly even with clear information · Break the step down, use a stronger model for it, or add a check
Environment fault · A tool or service failed · Add retries and error handling
4. Reproduce it. Replay the run with the same inputs, or the same context at the failing step, and see whether it fails again. Because agents vary, run it several times, as Lesson 7.1 explained, to learn how often it fails.
5. Fix the cause, not the symptom. If a loop was caused by a vague error message, adding a step cap treats the symptom. Do both, but fix the message.
6. Add the case to the test set, with the check that would have caught it, so it never returns unnoticed.
A habit worth building: keep a failure log, a short note on each failure with its cause category and its fix. After a month, count by category. The commonest cause shows where your agent's weak point lies, and often it is the same one or two things.
Alerts and the stop button
Failures that happen in production need fast detection. Useful alerts include: runs over the step or cost cap, the share of runs hitting a cap rising above a threshold, the same tool call repeated many times, a sudden rise in average cost per run, a sudden fall in task success and an unusual tool error rate. Each alert should say who responds and how.
And every agent needs a stop button: a way to halt a run, or all runs, immediately, and to revoke its credentials. Test it. An agent you cannot switch off in a minute is a risk.
Three worked examples
Example 1: a loop from a vague error
A support agent looked up orders. When an order ID had a typo, the tool returned "Error". The agent retried with the same ID, then tried reformatting it, then tried again, using the full 40-step cap on about 3 per cent of requests. The trace showed that the first wrong step was step 2, where the agent read "Error" and had nothing to act on. The team changed the tool to return "No order found with ID 55-21. Order IDs have 6 digits. Ask the customer to confirm the ID." The loops stopped. The step cap was lowered to 15 and repeat detection added. Cost per run fell 9 per cent.
Example 2: drift in a long research run
A research agent compared five companies and ran about 45 steps. Reviewers noticed that in a quarter of the reports, the last two companies were covered more thinly and the user's stated focus, on lending, disappeared. The trace showed that the agent's context was almost full of early search results by step 30, and the original brief was far back. The team added a goal restatement every 10 steps, a running plan with check marks and a summary restart at step 25. In the next evaluation, the share of reports that covered all five companies with the focus kept rose from 74 to 93 per cent.
Example 3: a runaway from fan-out
A lead agent was asked to analyse 200 documents. It started a worker per document, and several workers, finding a document long, started sub-workers of their own. A run cost ₹4,800, against a normal ₹120. The alert on cost per run fired at ₹500, and a person stopped the run at ₹900. The fixes were a limit of 10 workers running at once, a depth limit of one, a cap on tokens per worker and a daily budget that stops new runs when exceeded. The next large job cost ₹140.
A checklist for loops, drift and runaway cost
1. Set run limits for steps, tokens, money and time, based on real data.
2. Add repeat detection and a progress check. Make giving up a normal outcome.
3. Write tool errors that say what is wrong and what to do.
4. For long runs, add checkpoints: restate the goal, keep a plan, use a separate reviewer or summarise and restart.
5. Cap tool results, fan-out and depth.
6. Track cost in real time, with per-run and per-day budgets and alerts.
7. Build a stop button, and test it.
8. Keep traces. When a run fails, find the first wrong step, ask what the model could see, classify the cause and fix it.
9. Keep a failure log and review the counts monthly.
10. Add each failure to the evaluation set.
Common mistakes
No step or cost cap. One bad run can cost a day's budget.
Vague errors. The model has nothing to change, so it repeats.
No way to give up. The agent keeps trying when it should report a blocker.
Retrying everything. Retry temporary faults only, with a limit and a growing delay.
Long runs with no checkpoints. The goal fades and errors compound.
Letting tool results flood the context. Limit and summarise.
Unlimited fan-out. Cap workers and depth.
Starting at the last step of a failed trace. Find the first wrong step.
Blaming the model first. Check what it was shown.
Fixing the symptom only. A cap hides a bad tool message but does not fix it.
Key takeaways
Working agents fail in three common ways: loops, drift and runaway cost.
Stop loops with a step cap, repeat detection, progress checks and a clean way to give up. Write tool errors that say what to do.
Drift grows with run length. A 1 per cent chance of drifting each step leaves a 30-step run on track 74 per cent of the time. Checkpoints every ten steps that catch 80 per cent of drift lift that to 94 per cent.
Cap runaway cost with per-run, per-day and fan-out limits. A cap at five times normal cost cut a day's spend from ₹29,850 to ₹15,600 in the example, where 1 per cent of runs ran away.
To debug, read the trace forward, find the first wrong step, ask what the model could see, classify the cause, reproduce it and fix the cause.
Keep a failure log, alert on caps and cost, build a tested stop button and add every failure to the evaluation set.
Check yourself
1. Name three controls that break a loop.
Any three of: a step cap, repeat detection, progress checks and a clean way to give up.
2. At each step there is a 2 per cent chance of drifting for good. What share of 20-step runs stay on track with no checkpoints?
0.98²⁰ = 0.668, about 66.8 per cent.
3. Name two kinds of checkpoint.
Any two of: restating the goal, keeping a plan with progress marks, a separate reviewer, or summarising and restarting.
4. 2,000 runs a day cost ₹5 each. 2 per cent run away to 50 times the cost. What does a day cost with no cap?
Normal: 1,960 × ₹5 = ₹9,800. Runaway: 40 × ₹250 = ₹10,000. Total ₹19,800.
5. Why start reading a failed trace at the beginning and not the end?
The end shows the symptom. The first wrong step is the cause, and later steps are often consequences of it.
6. Why should the agent have a way to give up?
Without one, it keeps trying when the task cannot be done, which produces loops, wasted cost and guessed answers.
Try this
Set aside seventy-five minutes.
1. For an agent you have, or an imagined one, find the typical number of steps and cost of a run. Set a step cap and a cost cap from them.
2. Write repeat detection: what counts as a repeat and what the agent is told and when the run stops.
3. Rewrite three tool errors so each says what is wrong and what to do next.
4. For a run over 20 steps, design a checkpoint. Use the drift simulator to see what it might add.
5. Use the cost simulator with your own numbers to see how much a cap would save.
6. Take a failed run, real or invented, and write the trace-reading steps: the first wrong step, what the model could see, the cause category and the fix.
7. Write the alerts you would set and who responds, and describe how you would stop the agent in under a minute.
A good result is a reliability plan for one agent: limits, loop and drift controls, cost budgets, alerts, a stop button and a debugging method. That completes Module 7. Your agents can now be evaluated, limited, defended and kept from running away. Module 8 turns to operating them: cost and model choice, tracing, long-running agents and governance.
Tags: Agentic AI Agent failures Runaway cost Debugging Reliability