Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Step Limits Stop Long Runs; Progress Detection Stops Stuck Runs

A hard step ceiling is necessary but crude. A stronger agent runtime fingerprints repeated actions, tracks state changes, and stops cycles that spend tools and tokens without producing new information or advancing the task.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#agent-loops#no-progress-detection#reliability#tool-calling#typescript#python
On this page

A six-step agent that loops for six steps is still broken.

Hard step limits are important because every autonomous loop needs a final boundary. But they only answer one question: when do we stop regardless of what happened?

They do not answer a more useful question: is the agent still making progress?

I have seen this failure pattern in many forms. A tool returns “record not found,” the model changes one word and calls it again. A coding agent edits a file, runs the same failing test, rewrites the edit back to its previous state, and repeats. A research agent searches three versions of the same query without adding any new evidence.

The run is active. Tokens are being generated. Tools are returning results. Nothing is moving forward.

I prefer a runtime that keeps the hard step ceiling but also tracks a small set of progress signals. Repeated action fingerprints, unchanged resource state, identical error classes, and no growth in useful evidence can trigger a controlled stop before the maximum is exhausted.

The example here is a developer agent fixing a failing API test.

Define progress in application terms

“Different model output” is not progress.

For a coding task, progress may include:

  • a new relevant file discovered;
  • a patch changed the repository state;
  • the failing-test set became smaller or meaningfully different;
  • a new error signature appeared;
  • an explicit blocker was identified;
  • the workflow advanced to a different state.

For a research agent, the signals would be different: new source IDs, new claims supported, or a question resolved.

I make the runtime generic but let the workflow emit domain-specific progress markers.

TypeScript
type ProgressMarker = {  kind: string;  key: string;  value: string;};​type StepRecord = {  step: number;  actionFingerprint: string;  observationFingerprint: string;  progressMarkers: ProgressMarker[];  createdAt: string;};

A marker might be:

Text
kind=test-suitekey=failing-test-countvalue=3

or:

Text
kind=repositorykey=head-shavalue=4d91c2a

The runtime does not need to understand Git to see whether the marker changed.

Fingerprint normalized actions

Exact string equality is too weak.

These tool calls are logically the same:

JSON
{"tool":"read_file","args":{"path":"src/auth.ts","start":1,"end":200}}

and:

JSON
{"args":{"end":200,"start":1,"path":"src/auth.ts"},"tool":"read_file"}

Canonicalize the action before hashing it.

TypeScript
import { createHash } from "node:crypto";​function stableValue(value: unknown): unknown {  if (Array.isArray(value)) {    return value.map(stableValue);  }​  if (value && typeof value === "object") {    return Object.fromEntries(      Object.entries(value as Record<string, unknown>)        .sort(([a], [b]) => a.localeCompare(b))        .map(([key, child]) => [key, stableValue(child)]),    );  }​  return value;}​function fingerprint(value: unknown): string {  return createHash("sha256")    .update(JSON.stringify(stableValue(value)))    .digest("hex");}

For some tools, arguments need semantic normalization too. A search query with an extra period may be effectively the same query. I would implement that at the tool adapter, not inside one universal fingerprint function.

Do not flag one repeated read as a loop

Repetition can be legitimate.

A coding agent may re-read a file after editing it. A deployment agent may poll status until a rollout completes. A retry-safe API call may repeat after a transient 503.

The detector needs context.

I look for patterns such as:

  • the same action fingerprint repeated several times with the same observation;
  • action A → action B → action A → action B with unchanged resource versions;
  • the same error category after argument changes that are not materially different;
  • several steps with no new progress markers at all.

This produces a score rather than a single brittle rule.

TypeScript
type StallAssessment = {  stalled: boolean;  reason?: string;  repeatedActionCount: number;  stepsWithoutProgress: number;};​function assessStall(history: StepRecord[]): StallAssessment {  const recent = history.slice(-6);  if (recent.length < 3) {    return { stalled: false, repeatedActionCount: 0, stepsWithoutProgress: 0 };  }​  const last = recent.at(-1)!;  const repeatedActionCount = recent.filter(    (step) =>      step.actionFingerprint === last.actionFingerprint &&      step.observationFingerprint === last.observationFingerprint,  ).length;​  let stepsWithoutProgress = 0;  for (let index = recent.length - 1; index >= 0; index -= 1) {    if (recent[index].progressMarkers.length > 0) break;    stepsWithoutProgress += 1;  }​  if (repeatedActionCount >= 3) {    return {      stalled: true,      reason: "same action produced the same observation repeatedly",      repeatedActionCount,      stepsWithoutProgress,    };  }​  if (stepsWithoutProgress >= 4) {    return {      stalled: true,      reason: "multiple steps completed without a progress marker",      repeatedActionCount,      stepsWithoutProgress,    };  }​  return { stalled: false, repeatedActionCount, stepsWithoutProgress };}

The numbers are examples. They should come from traces and evaluations for the workflow.

Progress markers should represent change, not activity

A naive implementation emits tool-called=true every step and therefore always appears to make progress.

Markers should be generated only when state changes in a way that matters.

For tests:

TypeScript
function testProgressMarkers(  before: Set<string>,  after: Set<string>,): ProgressMarker[] {  if (setsEqual(before, after)) return [];​  return [    {      kind: "tests",      key: "failing-tests",      value: [...after].sort().join(","),    },  ];}

A run that changes one failing test into a different failing test has made *some* state change, but whether that counts as useful progress depends on the workflow. I often store the marker and let a higher-level policy assess whether the change improved or merely oscillated.

Detect short cycles explicitly

The simplest loop is AAAA. Real agents often oscillate ABAB.

TypeScript
function hasRepeatedCycle(  fingerprints: string[],  cycleLength: number,  repetitions: number,): boolean {  const needed = cycleLength * repetitions;  if (fingerprints.length < needed) return false;​  const tail = fingerprints.slice(-needed);  const cycle = tail.slice(0, cycleLength);​  for (let offset = cycleLength; offset < tail.length; offset += cycleLength) {    for (let i = 0; i < cycleLength; i += 1) {      if (tail[offset + i] !== cycle[i]) return false;    }  }​  return true;}

For a coding agent, the fingerprint can include tool name plus repository head SHA. That prevents edit → test → edit → test from being treated as a loop when each edit genuinely advances repository state.

If the head SHA toggles between two values, however, that is a strong oscillation signal.

Python version

Python
from dataclasses import dataclassfrom hashlib import sha256import json​@dataclass(frozen=True)class StepRecord:    step: int    action_fingerprint: str    observation_fingerprint: str    progress_markers: tuple[str, ...]​​def stable_value(value):    if isinstance(value, list):        return [stable_value(item) for item in value]    if isinstance(value, dict):        return {            key: stable_value(value[key])            for key in sorted(value)        }    return value​​def fingerprint(value: object) -> str:    payload = json.dumps(        stable_value(value),        separators=(",", ":"),        sort_keys=True,    ).encode("utf-8")    return sha256(payload).hexdigest()​​def repeated_same_result(history: list[StepRecord], threshold: int = 3) -> bool:    if not history:        return False​    last = history[-1]    matches = sum(        1        for item in history[-6:]        if item.action_fingerprint == last.action_fingerprint        and item.observation_fingerprint == last.observation_fingerprint    )    return matches >= threshold

The important part is not the hash function. It is the normalized unit of comparison and the workflow's definition of progress.

Give the agent one recovery attempt before stopping

A stall detector does not have to terminate immediately.

I like a small escalation ladder:

  1. first stall signal: inject a structured “no progress” observation and require a different strategy;
  2. second stall signal: disable the repeated action or request a narrower plan;
  3. continued stall: stop with a useful blocker or hand off to a human.
TypeScript
type StallNotice = {  reason: string;  disallowedActionFingerprint?: string;  requiredResponse: "replan" | "stop-and-report";};

The agent should not receive vague text such as “try harder.” It should know what pattern was detected and that repeating it is no longer allowed.

The hard step ceiling stays

Progress detection can itself be wrong.

A planner may continually generate “new” searches that evade duplicate fingerprints while still wasting time. A tool may return random IDs that make identical results hash differently. A workflow may emit noisy progress markers.

So I keep absolute bounds:

TypeScript
type RunLimits = {  maxSteps: number;  maxToolCalls: number;  maxElapsedMs: number;  maxCostUsd?: number;};

No-progress detection is an early-stop optimization and quality control. The hard limits are the final safety net.

Polling tools need a different policy

Status polling intentionally repeats the same action.

For those tools, I include state in the observation fingerprint and an explicit poll budget:

TypeScript
type PollPolicy = {  maxPolls: number;  minimumIntervalMs: number;  terminalStates: string[];};

If deployment status remains pending three times, that may be expected. If it remains pending for fifty polls despite a ten-poll budget, the workflow should pause or report that the operation is still running.

Do not globally suppress repeated calls and accidentally break legitimate waiting behavior.

Repeated failures should collapse to one error class

Raw error messages often contain request IDs or timestamps:

Text
Timeout contacting CRM request=9f3...Timeout contacting CRM request=a71...

Exact hashes differ, but the failure is the same.

Normalize errors before fingerprinting:

TypeScript
type NormalizedFailure = {  kind: "timeout" | "rate-limit" | "forbidden" | "invalid-input" | "dependency-error";  dependency: string;  operation: string;};

The loop detector should see “CRM/search timeout” three times, not three unique paragraphs.

This also improves observability aggregation.

Tool-result freshness affects loop detection

A repeated read with the same result may mean the resource is genuinely unchanged. A repeated read from a stale cache may mean the tool is broken.

I therefore include resource version/freshness metadata in observations when possible.

If the agent keeps reading ticket:T-91@version7 after another process updated it to version 8, the problem is not model looping—it is stale context or a caching bug.

Progress detection works best when the underlying tools expose enough state to tell those cases apart.

Test with adversarial trajectories

Single-turn evaluations do not exercise loops.

I build traces where the agent is tempted to repeat itself:

  • search returns no results for three similar queries;
  • an edit fixes one test but breaks another, then the model tries to revert;
  • a rate-limited tool returns the same retryable error repeatedly;
  • two tools contradict each other and the planner alternates between them;
  • a resource does not change despite a polling loop.

The test asserts not only final quality but also resource usage: number of steps, tool calls, repeated fingerprints, and whether the runtime stopped with the correct reason.

A useful system should fail *boundedly*.

Do not overfit the detector to one model

Model behavior changes. One model may repeat exact calls. Another may paraphrase arguments each time. A future model may use more tool calls per plan but make better progress.

That is why I prefer state-based signals—resource versions, test outcomes, evidence sets, workflow transitions—over trying to classify the model's prose for “stuckness.”

The closer the signal is to the task, the less it depends on one model's style.

When a step limit is enough

If an agent has a maximum of four cheap, read-only tool calls, a sophisticated cycle detector is probably unnecessary.

No-progress detection becomes useful when runs are long enough that wasting ten steps matters, tools can be expensive, or side effects make repeated attempts risky.

The principle is straightforward: activity is not progress.

An agent runtime should know when it has learned something new, changed relevant state, or advanced the workflow. If none of those things have happened for several steps, continuing until the hard ceiling is not autonomy. It is just a more expensive loop.

KEEP READING

Related engineering notes