Blog · · 10 min read

AI agent infinite loop: detect and recover workflows that stop making progress

AI agent infinite loop: detect and recover workflows that stop making progress

An AI agent infinite loop is easy to stop after 100 turns. The harder failure is a run that stays alive but stops making progress. It may repeat two different tools, wait on another agent that is waiting back, spin behind a permission request, or lose its worker after a write whose result is unknown. A process heartbeat still looks healthy, and a generic timeout cannot tell whether killing the run is safe.

Use a liveness contract for those cases. Define semantic progress, record wait dependencies, detect stalls and cycles, fence recovery, reconcile side effects, and verify one authoritative outcome without killing legitimate slow work.

Why a live run can still be stuck

Most agent runtimes expose execution limits. LangGraph documents a recursion-limit error when a graph reaches its maximum steps before a stop condition, often because of a cycle. The same documentation warns that a legitimate complex graph may need a higher limit. A step ceiling is necessary, but it does not establish whether useful work happened during those steps.

Termination conditions have the same boundary. AutoGen supports limits based on messages, tokens, timeout, handoff, external signals, and custom conditions. Those controls answer when a team should stop. They do not automatically prove that a live run is advancing toward a product outcome.

Static structure is one source of trouble. A July 2026 paper on infinite agentic loops analyzes framework-induced feedback paths and reports 68 manually confirmed failures across 47 projects. Runtime state adds cases that code structure alone cannot resolve: delayed callbacks, stale approvals, retries after uncertain effects, and dependencies created from current data.

Track four facts separately:

  1. The worker process is reachable.
  2. The workflow scheduler is dispatching steps.
  3. The run is changing meaningful product or workflow state.
  4. The run can still reach a valid terminal outcome.

The first two are health signals. The last two are progress signals. Alerting only on health misses active loops and circular waits.

Classify the stall before recovering it

Do not call every long run deadlocked. Give the detector a small taxonomy with mutually exclusive operational actions.

ClassObservable conditionTypical action
Healthy workA bounded operation is running and its deadline has not expiredContinue and expose progress
Expected waitThe run names an external dependency, owner, and expiryPark without consuming execution budget
LivelockSteps continue but semantic state and action fingerprints repeatStop dispatch, preserve evidence, and replan or escalate
Circular waitA cycle exists in the current wait-for graphBreak the cycle by policy and cancel one dependency
Lost workerNo worker lease exists for runnable workFence the old owner and resume from a safe checkpoint
Unknown effectA tool attempt ended without a trustworthy resultReconcile product state before any retry

Classifying the stall avoids killing a healthy export, migration, or human approval because it crossed an arbitrary wall-clock threshold. It also prevents a timed-out write from being retried after it completed.

Two issue reports illustrate different stalls. One VS Code user reported automatic handoffs looping between agents. Another author reported a background subagent freezing the controller and leaving the chat spinning, with an ineffective stop action and suspected permission-request identifier mismatch. These are author reports, not universal product behavior, but they expose different runtime states behind the same user symptom: the work never finishes.

Define semantic progress for each workflow

A model token, log line, tool invocation, or repeated status poll is activity. None should renew the progress lease by itself.

Define progress as a durable transition that reduces remaining work, resolves a dependency, or produces new authoritative evidence. Suitable events include:

  • a planned unit moves from pending to completed
  • a product write returns a verified receipt
  • an approval changes from pending to approved or rejected
  • a child run reaches a terminal outcome
  • a callback is authenticated and reconciled
  • a failed branch is replaced with a materially different plan
  • the run records a final verified, failed, or cancelled outcome

Do not count cosmetic plan rewrites, repeated reads of the same version, identical tool calls, growing reasoning text, or a status poll that still returns pending.

Store a monotonically increasing progress_epoch with the run. Each accepted progress event advances it in the same transaction as the state change. The detector compares epochs, not prose.

{
  "run_id": "run_2048",
  "state": "waiting",
  "progress_epoch": 17,
  "progress_kind": "child_completed",
  "progress_at": "2026-09-10T10:04:11Z",
  "owner_lease": 42,
  "waiting_on": [
    {
      "kind": "agent_run",
      "target": "run_2049",
      "reason": "pricing_check",
      "expires_at": "2026-09-10T10:09:11Z"
    }
  ],
  "last_effect": {
    "action_id": "refund_8821",
    "status": "verified"
  }
}

This schema is an implementation recommendation. Adapt the state and evidence fields to the records your product already owns. Keep identifiers bounded and do not put prompts or private user data into alert labels.

Record waits as data, not log messages

A run that enters waiting must say what it waits for. Persist a wait edge from the blocked participant to a concrete target, with the reason, creation time, expiry, and resolution policy.

Targets can include another run, a user approval, a tool callback, a queue item, a product lock, or a scheduled time. A vague waiting_for_dependency state is not enough. The detector needs an addressable target to decide whether the wait is valid and whether the target is also blocked.

For agent-to-agent dependencies, maintain a current wait-for graph. On each edge change, find strongly connected components among nonterminal participants. A component containing more than one participant is a circular wait. A self-edge is a cycle too. Confirm that every edge is current before acting, because a stale edge can make a resolved dependency look deadlocked.

A simplified detector can run as follows:

for run in nonterminal_runs:
    if run.state == RUNNABLE and owner_lease_expired(run):
        classify(run, LOST_WORKER)
    elif run.state == WAITING and wait_expired(run):
        classify(run, EXPIRED_WAIT)
    elif run.steps_advance and progress_epoch_is_unchanged(run):
        if repeated_action_fingerprint(run):
            classify(run, LIVELOCK)

for component in strongly_connected_components(current_wait_edges):
    if component.has_cycle and all_edges_unresolved(component):
        classify(component, CIRCULAR_WAIT)

Run this logic against durable workflow state. Trace analysis can explain what happened, but a delayed or sampled trace should not become the authority for cancellation.

Use progress leases without confusing them with worker leases

A worker lease prevents two executors from owning the same runnable work. A progress lease asks a different question: how long may the run remain in its present progress epoch before the control plane evaluates it?

Keep both values:

  • owner_lease changes when execution ownership changes and acts as a fencing token.
  • progress_deadline changes only after accepted semantic progress or an explicit expected-wait transition.

A long tool can extend its expected operation deadline through an authenticated callback or heartbeat, but that does not increment progress_epoch. The extension proves that the dependency is alive, not that the requested product outcome advanced. Cap extensions and record the tool operation identifier so a noisy client cannot keep a dead run open forever.

Choose deadlines by operation class rather than one global timeout. A database read and a human approval have different expected durations. An approval wait may last days but should consume no model-turn budget while parked. A background export may emit percentage checkpoints. A payment callback may have a short normal delay followed by reconciliation rather than immediate retry.

Detect livelock with action fingerprints

Repeated identical tool calls are the obvious loop. FutureAGI's loop-engineering guide recommends explicit terminal states, step caps, typed results, trace inspection, and action fingerprints. Extend the fingerprint beyond the tool name.

Include the normalized operation, authoritative input version, target resource, expected postcondition, and relevant plan node. Remove timestamps, generated request IDs, and other noise before comparison. Otherwise every repeated attempt looks unique.

Track both exact repetitions and short cycles. An agent can alternate search_account and refresh_context forever without repeating one adjacent action. Compare a bounded sequence of fingerprints and check whether progress_epoch changed across the sequence.

Use the detector as a trigger for a controlled decision, not as proof that the model is faulty. Product state might genuinely require repeated polling. Mark that operation as an expected wait with a poll interval, maximum duration, and completion predicate. Unclassified polling remains runnable work and should spend its execution budget.

Recover according to side-effect evidence

Detection stops new dispatch. Recovery begins only after the control plane fences the previous executor with a higher ownership token. Every subsequent state write and tool result must carry that token. A late callback from the old owner can be recorded but cannot move the run forward.

Then inspect the last attempted effect:

Effect evidenceRecovery decision
No external effect startedResume or replan from the checkpoint
Effect failed before acceptanceRetry within the shared action budget
Effect completed with a verified receiptRecord completion and continue without retry
Effect status is unknown but queryableRead authoritative product state and reconcile
Effect status is unknown and not queryableEscalate or compensate by explicit product policy
Circular wait with no committed effectsCancel the lowest-priority dependency and replan
Livelock after verified effectsStop and require a plan that accounts for completed work

Never let the model decide whether its own side effect happened. Read the target product, payment rail, job store, or other authority. Reuse stable action identifiers so reconciliation can connect an uncertain attempt to the resulting record.

Recovery should end in one typed result: resumed, replanned, cancelled, compensated, failed, or needs_human. Attach the detected stall class, evidence snapshot, fencing token, decision owner, and final product postcondition.

Alert with the evidence needed to act

A stuck run alert without context creates manual archaeology. Include:

  • workflow and release version
  • stall class and detection rule
  • current progress epoch and age
  • current owner lease and fencing token
  • bounded action-fingerprint sequence
  • unresolved wait targets and expiries
  • last attempted effect and evidence state
  • proposed automated recovery and why it is permitted
  • user-visible state and next update deadline

Page only when an operator can change the outcome. An expected approval wait should create a product reminder or expiry event, not an SRE page. A repeated low-risk read may be automatically replanned. An unknown financial effect should stop and escalate immediately.

Keep aggregate metrics for time without progress, stalls by class, false-positive recovery blocks, repeated-action depth, circular-wait size, recovery latency, and outcomes after recovery. Do not use model self-reports as the success metric. Join the recovered run to its authoritative product postcondition.

Test liveness before production finds the edge cases

Build deterministic fixtures around the state machine rather than waiting for stochastic prompts to reproduce every failure.

  1. Run a healthy slow tool past the ordinary step interval and prove it is not killed.
  2. Park a valid human approval, expire it, and prove the configured rejection or escalation occurs.
  3. Repeat one tool fingerprint without changing progress and prove the livelock threshold fires.
  4. Alternate two fingerprints without progress and prove the short-cycle detector fires.
  5. Create two child runs that wait on each other and prove the wait-for graph detects one cycle.
  6. Remove a worker after checkpoint commit and prove a new owner fences the old token.
  7. Delay a callback from the fenced worker and prove it cannot mutate current state.
  8. Time out after a completed write and prove reconciliation prevents a duplicate effect.
  9. Make effect status unknowable and prove automation stops instead of guessing.
  10. Recover a run and prove exactly one terminal product outcome is recorded.

Also inject stale wait edges, delayed detector scans, duplicate detector decisions, and control-plane restarts. The detector itself is a distributed component and must be idempotent. Two detectors can identify the same stall, but only one fencing transaction may acquire recovery ownership.

Measure false positives by replaying healthy long-running traces through the classifier. If operation deadlines are too tight, fix the operation class or heartbeat contract. Do not broadly raise every timeout, because that makes real stalls slower to contain.

Put the liveness contract into one release

Start with observe-only classification. Persist progress epochs and wait edges, compute stall classes, and compare the decisions with operator review. Fix missing progress events and invalid expected waits before enabling automated recovery.

Next, automate only lost-worker recovery where no external effect started and livelock cancellation for read-only workflows. Add write-capable recovery after stable action IDs, effect receipts, authoritative reconciliation, and fencing tests pass. Keep unknown effects on the human path until the product has a safe deterministic policy.

Version the liveness policy with the agent release. A release receipt should name progress-event rules, operation deadlines, repetition thresholds, cycle policy, fencing behavior, recovery permissions, test results, rollback triggers, and owner. Roll back automation if false-positive stops rise, fenced executors still write, or recovered runs produce duplicate outcomes.

Choose one long-running product workflow. List the durable events that count as semantic progress, then add explicit wait edges for every parked dependency. Run the ten fixtures above before allowing the control plane to recover a write-capable run.

Be first in line.

Join the waitlist and we'll email you the moment it's ready. No sales call.

Try the demo →
or talk to us