Markov chains for agent loops
Absorbing Markov chains, \(N = (I-Q)^{-1}\)
Takeaway
An agent whose drafts pass its own check % of the time averages 6.3 steps per task, yet 1 in 18 tasks needs 15 steps or more.
Change the blue number. Every figure on this page updates with it.
Why care
Agent loops have no fixed length, and the average run hides the runs that cost you.
Plan, act, check, and go round again until the check passes or the agent gives up. Teams size step budgets, timeouts and cost estimates from the average run, then find that a minority of tasks loops many times longer and drives most of the spend and the slow responses. An absorbing Markov chain turns the loop diagram you already have into exact answers: how often a task finishes, how many steps it takes on average, and the whole distribution of run lengths, including the tail.
The intuition
Think of a board game. Each square is a stage of the agent's work, and dice decide which square comes next. Two squares, Done and Give up, end the game: once you land there you never leave. Every other square can send you round the loop again.
Two things follow. Finishing is almost guaranteed if the give-up arrows are rare, but the number of trips round the loop is random, and its spread is set mostly by the weakest arrow back. A verifier that passes 45% of drafts sends more than half of all tasks round again, and some of them round again after that.
The math
Write the transition probabilities as a matrix and put the absorbing states (Done, Give up) last. The top-left block \(Q\) holds moves between working states; \(R\) holds moves into absorbing states:
- \(Q\)
- probabilities of moving between working states (Plan, Act, Verify)
- \(R\)
- probabilities of moving from a working state to Done or Give up
- \(N\)
- fundamental matrix: \(N_{ij}\) is the expected number of visits to state \(j\) starting from \(i\)
- \(\mathbf{t}\)
- expected steps until the run ends, from each starting state
- \(B\)
- probability of ending in Done or in Give up, from each starting state
For the loop on this page, with tool success \(a\), give-up rate after a failure \(g\), verify pass rate \(v\), and share of failed checks that replan rather than revise \(m\):
Three results to use:
- Success odds: the first row of \(B\). For this loop it has a closed form, \(P(\text{done}) = \dfrac{s\,v}{1-(1-v)(1-g)\,s}\) with \(s = \dfrac{a}{a+g-ag}\).
- Expected steps: the first entry of \(\mathbf{t}\), and its variance \((2N-I)\mathbf{t} - \mathbf{t}\circ\mathbf{t}\).
- The tail: the probability a run is still going after \(n\) steps is \(\mathbf{e}_1^\top Q^{\,n}\mathbf{1}\). It shrinks geometrically, at the rate of \(Q\)'s largest eigenvalue, so long runs are rare but never impossible. Budgets belong at a high percentile, not the mean.
Where each of these comes from is worked through in Derivations at the end of the page.
Interactive calculator
Set the probabilities on each arrow and a step budget. The diagram redraws with your numbers, and the histogram shows how many steps tasks take, exactly, from the chain.
Arrow thickness follows the probability. Expected visits per task:
Worked example: a research agent
A research agent answers analysts' questions: it plans, runs searches and tool calls, drafts an answer, and a verifier checks the draft against its sources. The team counted transitions in 2,000 production traces:
| Arrow | Measured |
|---|---|
| Tool step succeeds, \(a\) | 85% |
| Verifier passes the draft, \(v\) | 45% |
| Failed checks that replan rather than revise, \(m\) | 50% |
| Gives up after a failure, \(g\) | 2% |
From those four numbers the chain gives: 96.9% of tasks finish eventually, the average run is 6.3 steps and the median 5, but the 95th percentile is 15 steps and the 99th is 22. The orchestrator had a 15-step budget, so 4.4% of tasks, roughly one in 23, were being cut off while still working.
Four options, compared
| Change | Avg steps | 95th pct | Done in 15 steps |
|---|---|---|---|
| As built | 6.3 | 15 | 92.6% |
| Better tools: \(a\) from 85% to 95% | 6.0 | 14 | 93.8% |
| Bigger budget: 25 steps | 6.3 | 15 | 96.4%* |
| Better first drafts: \(v\) from 45% to 70% | 4.3 | 9 | 98.4% |
* Within the 25-step budget, at the price of paying for every long run.
The tool fix, which the team had prioritized, barely moved anything: a tool failure costs one retry step, while a failed check sends the task all the way round. Raising the verify pass rate, by giving the drafting step the verifier's rubric up front, cut the average by a third and the 95th percentile from 15 steps to 9. That is the arrow worth working on, and the chain shows it before anyone writes code.
Assumptions and where it breaks
- The chain has no memory. Each move depends only on the current state, not on how many times the task has looped. Real agents carry context, so a second failed check may be more or less likely than the first. Fix it by splitting states, such as Verify-1 and Verify-2; the math is unchanged, the matrix just grows.
- Replanning looks free here. In this model replanning and revising lead to equally good drafts, so \(m\) changes the step count but not the odds of finishing. In practice they differ; give each path its own pass rate when you have the data.
- Rare arrows are noisy. A 2% give-up rate estimated from 200 traces could easily be 1% or 4%. Put confidence intervals on each measured arrow (M06) before trusting the tail.
- Steps are not equal. A planning call may cost ten times a tool call. Replace the step count with a cost per state: expected cost is \(N\mathbf{c}\) instead of \(N\mathbf{1}\).
- The agent may choose its moves. When transitions are decisions the agent optimizes rather than chances, the model becomes a Markov decision process (M14).
How to apply it
- Draw the loop from your traces. List the states your orchestrator actually moves through, including the ways a run ends.
- Count transitions. From 500 or more traces, divide each state's outgoing moves by its visits to get the arrow probabilities.
- Compute the distribution, not just the mean. Get the average, median, 95th and 99th percentile steps from the chain.
- Set budgets and timeouts from the tail. Size them at the 95th or 99th percentile, and decide what happens at the cap: hand off to a human, return a partial answer, or fail fast.
- Improve the arrow with the most leverage. Move each slider a little and see which shifts the tail most. Usually it is the check that sends work all the way round.
How to explain it to a stakeholder
"Our agent is a board game with a loop in it. Most games end in five moves, but one in twenty goes round to fifteen or more. We budget for the long games, and we make the loop less likely to send work back."
Related models and patterns
For coding agents
A machine-readable summary and a reference implementation. The same spec is embedded in this page as <script type="application/json" id="model-spec">, and the whole series is listed in models.json.
id: markov-agent-loops
number: M03
name: Absorbing Markov chain for agent loops
family: reliability
answers: "How many steps will a looping agent take, how often does it finish, and how long is the tail?"
formula:
fundamental_matrix: "N = inv(I - Q)"
expected_steps: "t = N @ 1"
absorption_probabilities: "B = N @ R"
step_variance: "(2N - I) @ t - t*t"
still_running_after_n: "e_start @ Q**n @ 1"
inputs:
states: {type: list, meaning: working states first, absorbing states last}
P: {type: matrix, meaning: one-step transition probabilities from traces, rows sum to 1}
budget: {type: int, meaning: step cap applied by the orchestrator}
assumptions:
- next state depends only on the current state (memoryless)
- transition probabilities are stable over time
- every step has equal cost (replace 1 with a cost vector otherwise)
use_when:
- setting step budgets, timeouts and cost estimates for looping agents
- finding which transition most affects run length
related_patterns: [react, plan-and-execute, evaluator-optimizer, bounded-autonomy, budget-aware-planning]import numpy as np
def loop_matrix(a, v, m, g):
"""States: 0 Plan, 1 Act, 2 Verify, 3 Done, 4 Give up."""
P = np.zeros((5, 5))
P[0, 1] = 1
P[1, 2], P[1, 1], P[1, 4] = a, (1 - a) * (1 - g), (1 - a) * g
P[2, 3], P[2, 4] = v, (1 - v) * g
P[2, 0], P[2, 1] = (1 - v) * (1 - g) * m, (1 - v) * (1 - g) * (1 - m)
P[3, 3] = P[4, 4] = 1
return P
def analyze(P, n_transient=3, start=0, budget=None, horizon=500):
Q, R = P[:n_transient, :n_transient], P[:n_transient, n_transient:]
N = np.linalg.inv(np.eye(n_transient) - Q)
t = N.sum(axis=1)
var = (2 * N - np.eye(n_transient)) @ t - t * t
B = N @ R
x = np.eye(len(P))[start]
ended = [] # P(run has ended by step n)
for _ in range(horizon):
x = x @ P
ended.append(x[n_transient:].sum())
ended = np.array(ended)
pct = lambda q: int(np.argmax(ended >= q * ended[-1])) + 1
out = dict(p_done=B[start, 0], p_give_up=B[start, 1],
mean_steps=t[start], sd_steps=var[start] ** 0.5,
p50=pct(0.5), p95=pct(0.95), p99=pct(0.99))
if budget:
out["cut_off_at_budget"] = 1 - ended[budget - 1]
return out
if __name__ == "__main__":
print(analyze(loop_matrix(a=0.85, v=0.45, m=0.5, g=0.02), budget=15))
# p_done 0.969, mean_steps 6.27, p50 5, p95 15, p99 22, cut_off 0.044Derivations
For the math-curious: where each result in The math comes from. Nothing above depends on reading this.
Why the working block shrinks to zero
Multiplying the block matrix by itself keeps its shape: \(P^n = \begin{pmatrix} Q^n & \ast \\ 0 & I\end{pmatrix}\). The entry \((Q^n)_{ij}\) is the probability of being in working state \(j\) after \(n\) steps, starting from \(i\). As long as every working state can reach an absorbing one, each row of \(Q\) sums to less than 1 somewhere along every path, so \(Q^n \to 0\): every run ends eventually.
The fundamental matrix counts visits
Let \(X^{(n)}_{ij}\) be 1 if a run started in \(i\) is in state \(j\) at step \(n\). Its expectation is \((Q^n)_{ij}\). Summing over all steps gives the expected number of visits:
$$N = \sum_{n=0}^{\infty} Q^n = I + Q + Q^2 + \cdots$$This is the matrix version of the geometric series \(1 + x + x^2 + \cdots = 1/(1-x)\). Multiply both sides by \(I - Q\): everything telescopes to \(I\), so \(N = (I-Q)^{-1}\). The sum converges because \(Q^n \to 0\).
Expected steps and the odds of each ending
Each visit to a working state costs one step, so the expected number of steps is the total expected visits: \(\mathbf{t} = N\mathbf{1}\).
To end in absorbing state \(k\), a run spends some time among working states and then takes one step from some \(j\) into \(k\). The expected number of such jumps is \(\sum_j N_{ij}R_{jk}\), and since it happens at most once it is also a probability: \(B = NR\).
The variance comes from the same first-step argument applied to \(T^2\), giving \(\operatorname{Var}(T) = (2N-I)\mathbf{t} - \mathbf{t}\circ\mathbf{t}\), where \(\circ\) squares each entry.
A closed form for this loop
Let \(D_P, D_A, D_V\) be the probability of finishing from Plan, Act and Verify. Condition on the first move from each state:
$$D_P = D_A, \quad D_A = (1-a)(1-g)\,D_A + a\,D_V, \quad D_V = v + (1-v)(1-g)\big(m\,D_P + (1-m)\,D_A\big).$$The second equation gives \(D_A = s\,D_V\) with \(s = a/(a+g-ag)\). Since \(D_P = D_A\), the replan and revise terms merge and \(m\) drops out: \(D_V = v + (1-v)(1-g)\,s\,D_V\). Solving,
$$P(\text{done}) = D_P = \frac{s\,v}{1-(1-v)(1-g)\,s}.$$With the worked example's numbers, \(s = 0.85/0.853 = 0.9965\) and \(P(\text{done}) = 0.9965 \times 0.45 / 0.4629 = 0.969\).
Why the tail decays geometrically
The chance a run is still going after \(n\) steps is \(\Pr(T > n) = \mathbf{e}_1^\top Q^n \mathbf{1}\). Writing \(Q\) in terms of its eigenvalues, the largest one, \(\lambda_{\max} < 1\), dominates for large \(n\), so \(\Pr(T>n) \approx c\,\lambda_{\max}^{\,n}\). Each extra step multiplies the surviving share by roughly \(\lambda_{\max}\). When the verify pass rate is low, \(\lambda_{\max}\) is close to 1 and the tail is long, which is why budgets set from the mean cut off so many runs.
References
- Grinstead, C. M. and Snell, J. L. Introduction to Probability, chapter 11, "Markov Chains". American Mathematical Society; free PDF. The clearest treatment of absorbing chains and the fundamental matrix.
- Kemeny, J. G. and Snell, J. L. (1960). Finite Markov Chains. Van Nostrand. The original source of the fundamental-matrix results.
- Yao, S. et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models. The reason-act-observe loop that most agent loops descend from.