Loops, Performance, Incidents and Maturity
Catch runs that go nowhere, respond calmly when something breaks and improve your ability to see.
Enforce limits on steps, time, cost and repetition in code and watch for lack of progress. Profile the critical path before optimizing. In an incident, contain first, then investigate, and write a blameless review with owned actions. Grow observability in stages, judged by the questions you can answer.
What you will learn: detecting loops, stalls and cost runaway, profiling agent performance, incident roles and root cause analysis, and a maturity model.
Prerequisites: What to Measure: Metrics, Dashboards and SLOs and Debugging Agents, RAG and Handoffs.
The example runs in November 2026 with Python 3.13 and only the standard library, on invented runs. The limits and maturity levels are teaching choices, not an industry standard.
Loops, stalls and runaway cost
| Problem | What it looks like | Signal |
|---|---|---|
| Exact loop | The same call with the same arguments | Repeat count |
| Near loop | Small variations that learn nothing | No new facts or state change |
| Cycle | A, B, A, B across tools or agents | Repeating sequence, transfer count |
| Stall | Waiting with no timeout | Age of the current step |
| Fan-out burst | Many sub-agents or parallel calls | Active children, depth |
| Context growth | Each step costs more than the last | Input tokens per step |
| Retry storm | Several layers retry the same failure | Attempts per logical call |
Each step may look fine, so ordinary error alerts stay quiet. You need checks on the run as a whole.
Limits that must live in code
- Maximum steps, elapsed time, tokens and money per run.
- Maximum repeats of one call and transfers between agents.
- Maximum depth and number of child runs, with the parent's budget shared among them.
- Timeouts on every model and tool call.
- Daily and per-user caps that apply across runs.
When a limit trips, end in a defined way: save state, say what was and was not done, and hand off to a person where needed. A silent kill can leave half-finished changes (Agent Decisions: Confidence, Stopping, Loops and Budgets).
A run guard and a critical path
The first part of this program stops runs for four different reasons. The second finds which spans determine the total time of a slow run.
"""Stop runaway runs and find where the time went."""
import json
from collections import Counter
class RunGuard:
def __init__(self, max_steps=12, max_repeats=3, max_cost=0.50, max_stall=4):
self.max_steps, self.max_repeats = max_steps, max_repeats
self.max_cost, self.max_stall = max_cost, max_stall
self.steps, self.cost, self.stall = 0, 0.0, 0
self.calls, self.facts = Counter(), set()
def after_step(self, tool, args, cost, new_facts):
"""Return None to continue, or the reason to stop."""
self.steps += 1
self.cost += cost
key = (tool, json.dumps(args, sort_keys=True))
self.calls[key] += 1
fresh = set(new_facts) - self.facts
self.facts |= fresh
self.stall = 0 if fresh else self.stall + 1
if self.cost > self.max_cost:
return "cost limit"
if self.calls[key] >= self.max_repeats:
return f"same call {self.calls[key]} times"
if self.stall >= self.max_stall:
return f"no new information in {self.stall} steps"
if self.steps >= self.max_steps:
return "step limit"
return None
def run(name, steps):
guard = RunGuard()
for tool, args, cost, facts in steps:
reason = guard.after_step(tool, args, cost, facts)
if reason:
print(f"{name}: stopped after step {guard.steps}: {reason} "
f"(cost {guard.cost:.2f})")
return
print(f"{name}: finished in {guard.steps} steps (cost {guard.cost:.2f})")
run("healthy", [("search", {"q": "a"}, .05, ["a1"]), ("read", {"id": 1}, .04, ["a2"])])
run("looping", [("search", {"q": "refund"}, .03, ["x"])] * 6)
run("wandering", [("search", {"q": f"try {i}"}, .02, ["same"]) for i in range(9)])
run("expensive", [("read", {"id": i}, .22, [f"f{i}"]) for i in range(5)])
# Spans of one slow run: id, parent, name, start ms, end ms
SPANS = [(1, None, "run", 0, 4200), (2, 1, "plan", 0, 900), (3, 1, "search", 900, 1500),
(4, 1, "crm.read", 900, 3100), (5, 1, "answer", 3100, 4200)]
def critical_path(spans, root=1):
"""Walk back from the end, taking the child that finished last each time."""
children = [s for s in spans if s[1] == root]
path, edge = [], next(s for s in spans if s[0] == root)[4]
for child in sorted(children, key=lambda s: s[4], reverse=True):
if child[4] <= edge:
path.append(child)
edge = child[3]
return path[::-1]
print("Critical path:")
for _, _, name, start, end in critical_path(SPANS):
print(f" {name:9} {end - start:>5} ms")
Output:
healthy: finished in 2 steps (cost 0.09)
looping: stopped after step 3: same call 3 times (cost 0.09)
wandering: stopped after step 5: no new information in 4 steps (cost 0.10)
expensive: stopped after step 3: cost limit (cost 0.66)
Critical path:
plan 900 ms
crm.read 2200 ms
answer 1100 ms
The looping run stops at the third identical call. The wandering run changes its search words every time but learns nothing, so the progress check stops it. The expensive run ends at 0.66 although the limit is 0.50: this guard checks after spending. To hold a limit strictly, reserve an estimated cost before each call and settle the difference afterward.
In the slow run, the 600-millisecond search ran in parallel with a 2,200-millisecond record lookup. Making search faster would change nothing. The critical path points to the lookup first.
"New facts" is a simple stand-in. A coding agent might use failing tests going down; a research agent, new relevant sources; a support agent, a state change in the ticket.
Alert on patterns
| Alert | Urgency | First action |
|---|---|---|
| Spend rate far above normal | Page | Apply the cap; find the version or tenant |
| Writes or messages above normal | Page | Pause the tool; check for duplicates |
| Rise in limit stops | Same day | Read samples; look for a changed dependency |
| Queue age growing | Same day | Check stuck steps and capacity |
| Tokens per task creeping up | Weekly review | Inspect context growth |
Performance profiling
- Measure percentiles for the whole run and for each span type, split by task kind and version.
- Break down time: queueing, model time to first output, generation, retrieval, tools, retries and waiting for people.
- Find the critical path in several slow runs.
- Count steps. Removing one unnecessary model call often beats speeding it up.
- Change one thing, then compare latency, quality and cost together.
| Finding | Options |
|---|---|
| Long sequential tool calls | Run independent calls in parallel |
| Large repeated prompts | Trim context; use prompt caching where available |
| Slow generation | Shorter outputs, a smaller model for simple steps, streaming |
| Slow dependency | Cache safe reads, set timeouts, fix the service |
| Queueing | Capacity, priorities and admission control |
| Waiting for approval | Better routing and clearer requests, not weaker checks |
See Latency, Load Testing and Capacity Planning for capacity and Reducing Tokens, Tool Calls and Spend for spend.
A worked latency budget
Suppose users should usually have an answer within 8 seconds. Divide that time before building, then compare with measurements.
| Stage | Budget | If it overruns |
|---|---|---|
| Intake and policy checks | 0.3 s | Cache policy data safely |
| Planning model call | 1.5 s | Shorter context or a faster model |
| Parallel lookups | 2.0 s | Timeouts and partial results |
| Answer generation | 3.0 s | Limit length and stream output |
| Margin | 1.2 s | Room for one retry |
Percentiles of separate stages do not simply add up to the percentile of the whole, so always measure end to end too. Count time spent waiting for a person separately, and tell the user when work will continue in the background.
Incident management
An agent incident is any event where agent behavior causes or threatens harm or serious disruption: wrong actions, data exposure, unsafe output, a runaway bill or a large quality drop. Security attacks need the additional steps in Red Teaming and Incident Response.
| Role | Does |
|---|---|
| Incident lead | Decides and coordinates; does not do all the fixing |
| Technical responders | Contain, investigate and repair |
| Communications | Updates users, staff and partners with verified facts |
| Scribe | Keeps a timeline of observations and decisions |
| Legal and privacy | Assess notification duties and deadlines early |
Containment choices, mildest first
- Raise approval requirements.
- Disable one tool or switch it to read-only.
- Roll back the prompt, model, index or release.
- Route to a simpler workflow or to people.
- Stop the agent, drain queues and revoke its credentials.
Choose according to harm, not convenience, and verify that actions have actually ceased, including queued and scheduled work.
Severity by effect
| Level | Example | Response |
|---|---|---|
| 1 | Ongoing unauthorized actions or exposure of sensitive data | Immediate, leadership informed |
| 2 | Many wrong results with a workaround | Urgent, same day |
| 3 | Limited defect, no lasting harm | Planned fix |
Some laws set reporting deadlines. For high-risk AI systems under the EU AI Act, providers report serious incidents under Article 73 within limits as short as days, and deployers must inform them, once the high-risk rules apply to the system (from December 2027 or August 2028); privacy law has its own clocks, such as 72 hours for notifying many personal data breaches under the GDPR. Know who decides, before you need to (EU AI Act and US AI Policy).
Preserve evidence
- Place a hold on relevant traces, audit records and logs before automatic expiry removes them.
- Record exact versions of code, prompts, models, indexes, tools and policy.
- Export queued and pending items before draining them.
- Note every manual change made during the response, with time and author.
- Limit access, since incident bundles often hold sensitive data.
Repair what the agent did
Stopping the agent does not undo its work. List affected records and people from the audit trail, decide how to reverse or compensate each action, and have a person verify a sample of the repairs. Do not hand cleanup to the same agent that caused the damage. Tell affected people what happened, what you did and what they should check, using verified facts only.
A short update format
State what is known, what is unknown, who is affected, what has been contained, what happens next and when the next update will come. Regular, honest updates reduce guesswork and duplicate effort.
Root cause analysis
Complex failures rarely have one cause. Look for the conditions that made it possible and the safeguards that did not catch it.
| Question | Example answer |
|---|---|
| What triggered it? | A supplier changed an error format |
| Why did the agent react badly? | The error looked like an empty success, so it retried by another route |
| Why did limits not stop it? | The cap was per run, and new runs kept starting |
| Why was it found late? | No alert on writes per hour |
| What reduced harm? | Approval was required for payments |
Run reviews without blame. People who fear punishment share less, and "someone should have noticed" fixes nothing. Each action needs an owner, a date and a way to verify it, preferably as a test or a control. Replay the incident in isolation after the fix.
Follow up until it holds
Review open actions weekly, and close one only when its check exists and passes. A month later, ask whether the same class of failure could happen in another agent, and share the control that now prevents it. Track repeat incidents: they show where actions treated symptoms instead of causes, and where a shared platform control would help every team that runs agents.
Practice before it is real
- Inject a failing or slow tool in a test environment and watch what the agent does.
- Rehearse the stop and measure the time until the last action.
- Run a tabletop exercise on a runaway cost or wrong mass message.
- Check that on-call staff can open traces and disable tools at night.
Step-by-step fixes for common faults are collected in Incident Runbook and Failure Mode Catalog.
Observability maturity model
| Level | You have | You can answer |
|---|---|---|
| 1. Logs | Text logs per service | Did something fail? |
| 2. Traces | Connected spans with run IDs and versions | What happened in this run? |
| 3. Measures | Outcome, quality, latency and cost metrics with alerts | Is it working, and when did that change? |
| 4. Feedback | Failures become evaluation cases; releases gated on results | Did our change make it better? |
| 5. Managed | Service objectives, tested limits and drills, governed telemetry | What risk are we running, and can we prove control? |
Score each agent, not the company as a whole, using evidence. A high-risk agent should be further along than an internal summarizer. Move one level at a time and pick the next question you most need to answer.
A short self-assessment
- Given a complaint, can you find the run within five minutes?
- Can you tell which version served it?
- Would you learn of a tenfold cost rise within an hour?
- When did the last incident become a test?
- Has anyone checked that old telemetry is deleted?
Common mistakes
| Mistake | Better approach |
|---|---|
| Limits written only in the prompt | Enforce them in the runtime |
| Per-run caps with unlimited runs | Add per-user and daily caps |
| Optimizing the longest span that is not on the critical path | Profile the path first |
| Debugging while harm continues | Contain, preserve evidence, then investigate |
| Reviews that end at "model error" | Find missing safeguards |
| Actions without owners | Assign, date and verify |
Operations checklist
- Runs have step, time, cost, repeat and depth limits.
- Progress is measured in a way that suits the task.
- Alerts cover spend, side effects and stuck work.
- Slow runs are profiled by critical path.
- Roles, severity levels and containment steps are agreed.
- Stop and rollback are rehearsed.
- Reviews produce owned, verified actions.
- Each important agent has a maturity target.
Frequently asked questions
What step limit should an agent have?
Base it on observed successful runs with some margin, and review runs that reach it rather than raising it automatically.
Is a loop always a bug?
No. Polling or refining can be intended, but it should show progress and have a bound.
Who should be on call for an agent?
The team that can change and stop it, with clear escalation to security, privacy and the business owner.
Do small projects need incident process?
Yes in a light form: know how to stop it, who to tell and where to record what happened.
References and further reading
- Google SRE Book: managing incidents: roles and coordination.
- Google SRE Book: postmortem culture: blameless reviews.
- NIST SP 800-61 Rev. 3: incident response recommendations.
- European Commission: AI Act: the legal framework for incident duties.
Next steps
Troubleshooting
Work through specific failures.
High Availability and Disaster Recovery
Keep service up when parts fail.
Agent FinOps, Budgets and Chargeback
Manage spend as a routine.