Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Long-horizon
agents.
A ten-step task the agent nails every time. A hundred-step version of the same task, and it almost never finishes. Nothing got harder — the steps are identical. What changed is that reliability compounds: a small per-step failure rate, multiplied over a long chain, becomes near-certain failure. The fix isn't a smarter model; it's an engineered one — checkpoint the work, and retry the segment that broke instead of the whole run.
The wall: reliability compounds
If each step of a task succeeds with probability p, and the task needs k steps to all go right in a row, the chance of finishing clean is pk. That exponent is brutal. It's the same passk curve that agent evaluation measures — and it means length, not difficulty, is the enemy.
A 95%-reliable step sounds great until you chain a hundred of them and land under 1%. The math of long horizons is unforgiving to any single-shot run.
The full treatment of measuring this — pass@k versus passk, and how reliability scores over many attempts — lives in the agent-evals handbook. This handbook picks up where measurement ends: given that pk collapses, how do you build an agent that survives it?
Checkpointing: don't restart from zero
The first move is to stop treating the task as one indivisible chain. Checkpointing saves the agent's state at intervals — completed subtasks, intermediate artifacts, verified progress — so a failure at step 87 doesn't throw away steps 1 through 86. Without checkpoints, one stumble anywhere means starting over; with them, a stumble costs only the work since the last save.
■■■■✗ → restart ALL
success p^k
■■│■■✗ → retry last segment
failure is local
A good checkpoint is resumable state: enough that the agent can pick up exactly where it left off, not a vague summary that forces guesswork. The art is choosing what to persist — the durable artifacts and decisions, not the entire scratchpad — so resume is faithful and cheap.
Resume + retry: break the exponent
Checkpoints unlock the real win: retry the failed segment, not the whole task. Split the k steps into segments of length c. A segment succeeds with probability pc, and if you can retry a failed segment up to r times, its effective success rises to 1−(1−pc)r. The whole task is then those segments in series:
Same model, same per-step p. At p=0.95, k=100: the naive run finishes 0.6% of the time; checkpoint every 10 steps with 3 retries per segment and it finishes ~51%. The exponent that was killing you now works segment-by-segment, where retries can beat it.
You can't make pk survivable by nudging p — you'd need near-perfection. You make it survivable by shortening the chain that has to hold: small segments, cheap resume, and retries where a failure is local and recoverable. Reliability engineering, not model improvement.
Two dials fall out of the formula. Shorter segments (frequent checkpoints) make each segment more likely to pass on the first try; more retries per segment raise each segment's effective reliability. Both cost overhead, so you tune them against the horizon. The runnable model below lets you turn each dial.
The catch: real failures are silent and correlated
The retry math above makes two quiet assumptions: every failure is noticed, and every retry is an independent draw. Long-running agents break both. A step can fail while reporting success, with a test it skipped, a file it thinks it wrote, or "done" on a feature that doesn't work, and every later step builds on the mistake. A retry only fires on a failure somebody detected. And when the cause is the model's own misunderstanding, the retry tends to make the same mistake, because nothing about the second attempt is different.
Illustrative, at p = 0.95 and k = 100. If 10% of failures are silent, the ceiling is about 61%; at 20% it's 37%; at 50% it's 8%. No number of retries moves it. Only detection does.
So the cheapest reliability work on a long-horizon agent is usually verification, not retries: a check after each step that can tell "claimed done" from "done". Anthropic's write-up on harnesses for long-running agents names exactly these failure modes in its coding agents: trying to one-shot the whole app and running out of context mid-implementation, a later session seeing progress and declaring the project finished, and marking features complete without end-to-end testing. Its fix for the last one was to have the agent use browser automation and "do all testing as a human user would." Correlated failures need a different kind of retry, one that changes something (the prompt, the context, the approach, or the model), so the next attempt isn't the same attempt again.
State outside the context window: compaction, progress files, git
A checkpoint is only as good as what it saves, and for an LLM agent the hard part is that the working state lives in the context window, which fills up and degrades. Anthropic's post on context engineering (September 2025) calls the degradation context rot and describes three ways to work past it:
| Technique | What it does |
|---|---|
| Compaction | Summarize a conversation nearing the context limit and continue in a fresh window. Claude Code keeps "architectural decisions, unresolved bugs, and implementation details," drops redundant tool output, and carries over the five most recently accessed files. |
| Structured notes | The agent writes notes outside the context window (a to-do list, a NOTES.md) and reads them back later. |
| Sub-agents | Focused tasks run in clean context windows and return only a condensed summary to the lead agent. |
The harness post (November 2025) turns this into a checkpoint protocol for work that spans many context windows. An initializer session writes an init.sh that starts the dev server, a claude-progress.txt log, and a JSON feature list in which every feature (over 200 in their example) starts out marked failing. Then it makes an initial git commit. Every later coding session starts the same way: read the progress file and the git log, run init.sh and a basic end-to-end test to catch damage from the last session, pick the highest-priority failing feature, and finish by committing and updating the progress file, leaving the environment clean.
Map that onto this handbook's model and each file has a job. The git commit is the checkpoint, the progress file is the resumable state, and the feature list with its passes field is the verifier that keeps "done" honest. Even the file format is a reliability decision: the authors chose JSON because the model was less likely to inappropriately rewrite it than a Markdown file.
Durable execution: replay without repeating side effects
Progress files are checkpoints the agent keeps for itself. A durable execution engine keeps them for the program running the agent, so a crashed process can resume instead of restarting. In Temporal, a workflow's steps are recorded in an Event History. After a crash, a worker replays that history to rebuild state and carries on from the last recorded event. In the docs' words, "completed Activities will not re-execute as part of a Workflow Replay." LangGraph's checkpointers do the analogous job for agent graphs: they "persist a thread's graph state as checkpoints," keyed by a thread_id, to support human-in-the-loop pauses, time travel and fault tolerance.
The gap that bites is between doing a side effect and recording it. Temporal notes that an Activity isn't written to history until it returns or errors, and that "Temporal recommends that Activities be idempotent" because retried Activities "may be executed more than once." For an agent that sends email, files tickets or moves money, a crash after the action but before the record means the retry does it twice, unless the action carries a key that is the same on every attempt:
key = f"{run_id}:{step}" # identical on every retry of this step
if ledger.seen(key): return ledger.result(key)
result = billing.charge(invoice, idempotency_key=key)
ledger.record(key, result)
return result
A sketch. The downstream API must honor the key too, because the crash can land between charge() and record(). Practice it in the Idempotency Key Handler challenge.
The time horizon — and how engineering extends it
The field now tracks an agent's time horizon, defined by METR in "Measuring AI Ability to Complete Long Tasks" (March 2025) as the time humans typically take to complete the tasks a model finishes with 50% success. At publication, frontier models such as Claude 3.7 Sonnet sat around 50 minutes, and the frontier horizon had doubled roughly every seven months since 2019. By METR's Frontier Risk Report of May 2026, the public frontier's 50% horizon was about 12 hours, with a wide interval of 5 to 61 hours. METR's Time Horizon 1.1 suite can't reliably measure past 16 hours, so the yardstick itself is running out.
The same report puts the 80% horizon at about 1.5 hours. That gap is this handbook's opening math in the wild: ask for more reliability and the task length a model can carry shrinks by roughly a factor of eight. A team that needs a long-running agent to succeed four times in five is working with a much shorter horizon than the headline number.
The lesson of this handbook is that the horizon isn't only a property of the model. Raw per-step reliability sets a baseline; checkpointing, retries and verification extend it. An agent that saves progress, verifies each step and retries locally has a longer usable horizon than its bare p would predict. So when METR's curve doubles, part of that is better models, and part is better harnesses doing exactly what's above.
Why it matters
The agents that will run for hours — refactoring a codebase, conducting deep research, driving a multi-stage workflow — don't win by having a magically reliable model. They win on reliability engineering: checkpoint often, make state resumable, verify between steps, retry the smallest failing unit. It's the same discipline distributed systems learned decades ago (idempotency, retries, checkpoints), now applied to an agent's step chain.
For a builder the takeaway is liberating: you don't have to wait for a perfect model to ship a long-running agent. You have to engineer around imperfect steps. Measure the decay with agent-evals, guard each step with the patterns in agent patterns, and structure the whole loop with a harness that checkpoints and resumes. The horizon you can reach is mostly up to you.
The measurement half: Agent Evals. The per-step guardrails: Agent Patterns. The loop that runs it: Harness Engineering. What survives a full window: Context Engineering.
Break the p^k collapse with checkpoints
Long-horizon reliability is one formula and its rescue. A single-shot run of k steps succeeds with probability pk — which collapses as the horizon grows. Checkpoint into segments of c steps and retry a failed segment up to r times, and each segment's success climbs to 1−(1−pc)r, with the whole task their product over k/c segments. Watch a 0.6% success become 51% at the same per-step reliability, and turn the segment-length and retry dials.
Worked example: tuning segment length and retries on a 100-step task
Take the page’s task: p = 0.95 per step, k = 100 steps. Each plan splits it into segments of c steps and allows up to r attempts per segment. Success is the page’s formula. The last column is the work that counts: steps executed per finished task, if a run that gives up is restarted from scratch. A failed attempt stops at its first bad step, so it is cheaper than a full segment.
| Plan | One segment, first try (p^c) | Segment with retries | Task finishes | Steps run per finished task |
|---|---|---|---|---|
| No checkpoint (c = 100, r = 1) | 0.59% | 0.59% | 0.59% | 3,358 |
| Checkpoint every 10, no retries (r = 1) | 59.87% | 59.87% | 0.59% | 3,358 |
| c = 20, r = 2 | 35.85% | 58.85% | 7.06% | 674 |
| c = 5, r = 2 | 77.38% | 94.88% | 34.97% | 202 |
| c = 10, r = 3 (the page’s case) | 59.87% | 93.54% | 51.28% | 184 |
| c = 5, r = 3 | 77.38% | 98.84% | 79.22% | 131 |
| c = 10, r = 5 | 59.87% | 98.96% | 90.07% | 141 |
| c = 1, r = 3 | 95.00% | 99.99% | 98.76% | 106 |
Row 2 is the surprise: checkpoints with no retries change nothing. Ten segments that must each pass once are the same 100 steps that must each pass once, 0.95^100 either way. A checkpoint only pays when something resumes from it. Rows 4 and 6 have the same segment length, so the third attempt alone lifts success from 35% to 79%, because the segment rate is raised to the 20th power. The last column is why reliability engineering is also cost engineering. A bare run burns about 3,358 steps per success; checkpointing every 5 steps with 3 attempts burns 131, only 31% over the 100-step minimum. Row 8 looks best, but it hides the price of saving state after every step, which the next table covers.
Cost and trade-offs: what each reliability dial costs
Here Time is the overhead the dial adds to a run, and Space is the state it has to keep.
| Case | Time | Space | Why |
|---|---|---|---|
| Checkpoint every step | A save (and often a verify) per step; when steps are cheap, this can cost more than the steps | Full resumable state at every step | Highest success, but only worth it when a step is expensive, as with a long tool call or a model call. |
| Checkpoint every 5 to 10 steps | One save per segment | One snapshot per segment; keep the last good one | The usual sweet spot. Pair it with 3 or more attempts, or the checkpoint is wasted (row 2 above). |
| More attempts per segment | Worst case r × k steps: 300 for r = 3, k = 100 | A counter per segment | Cheap on average (131 to 141 steps per success above), expensive in the worst case. Cap it with a total budget. |
| Verify after each step | One check per step: a test, a diff, a schema validation | Nothing extra | The only dial that raises the silent-failure ceiling. Retries cannot fix what nobody detected. |
| Change something on retry | A new prompt, more context or a different model; the retry costs more | A note of what the last attempt tried | Breaks correlated failures. Repeating the same attempt mostly repeats the same mistake. |
| Durable execution engine | Replay of the event history on recovery | An event history per run, kept by the engine | Resumes the program after a crash. It does not make side effects idempotent; you still need the key. |
| Compaction | One summarizing call near the context limit | Smaller context; detail is lost | Keeps a long run going, but anything the summary drops is gone. Durable facts belong in files, not the transcript. |
The dials interact. Short segments make each retry cheap, retries make short segments worth saving, and verification decides whether either of them fires at all. Spend on verification first, retries second, and checkpoint frequency last.
Common mistakes
- Checkpointing before verifying
Save state after a step that silently failed, and every retry resumes from the poisoned checkpoint. The segment “passes” on its next attempt and builds on the bad state. Verify, then save. A checkpoint should mean “known good”, not “happened”.
- A segment boundary inside a transaction
If a segment ends after half a database migration, or after writing three of five related files, resume starts from a state that never should have existed. Draw boundaries where the world is consistent, so that a resumed run and a fresh run see the same thing.
- Retries per segment, no total budget
Three attempts per segment sounds bounded, but on a 100-step task the worst case is 300 steps, and with five attempts it is 500. Add a run-level cap on steps, tokens or wall-clock time, and escalate to a human when it trips.
- Letting the agent edit its own verifier
If the agent can rewrite the test, the feature list or the passes field, “make it pass” has a cheap answer. Keep the verifier outside the agent’s write access, or fail the step when the number of checks goes down. The page’s harness example points the same way: it kept the feature list in JSON because the model was less likely to rewrite it.
- Changing the code under a paused run
A durable run that resumes on new code replays its old history against new logic. Temporal requires workflow code to be deterministic for exactly this reason, and has versioning for changing it while runs are in flight. Agent harnesses have the same problem with prompts and tools: record which version a run started on, and resume it on that version.
Where this shows up in production and interviews
- Codebase-wide migrations
The natural segment is one file or one module. Each segment ends with tests and a commit, so the commit is the checkpoint and
gitis the resume log. A failing file is retried, and after a few attempts it is parked for a human while the rest of the migration carries on. - Retry policies are the r dial
In Temporal an Activity gets a retry policy by default, with exponential backoff and no limit on attempts. That is fine for a flaky network call. For an agent step that can fail silently or in the same way twice, set a maximum and route the final failure somewhere a person will see it.
- Deep research agents
Segments are sub-questions. The checkpoint is a notes file of sources already read and claims already checked, so a crash, or a full context window, costs one sub-question rather than the whole report. Verification is checking each claim against its source before it is written down.
- The interview version
“Design an agent that runs a four-hour task.” Start with p^k, using the page’s 0.6% figure, then propose segments, a retry budget and per-step verification, and quote the table above: 0.6% to 79% at the same model quality. Close with idempotency keys for side effects and a run-level cap. That shows you treat it as a reliability problem, not a prompting problem.
Check yourself
Per-step reliability is 0.99 and the task is 200 steps. What is the chance a single run finishes?
0.99^200 ≈ 13.4%. A step that fails 1 time in 100 still sinks most 200-step runs, because the exponent is the task length.
You add a checkpoint every 10 steps but keep r = 1. What happens to the success rate?
Nothing, it stays at 0.95^100 ≈ 0.59%. Ten segments that must each pass on the first try are the same 100 steps in series. Checkpoints only help when a failed segment is retried from them.
Only 5% of failures are silent, with p = 0.95 and k = 100. What is the ceiling with unlimited retries?
From the page’s formula: (1 − 0.05 × 0.05)^100 = 0.9975^100 ≈ 77.9%. Even a small share of undetected failures caps the run well below 100%, and only better detection moves that cap.
A step charges a card with idempotency key = a fresh random UUID. It crashes after the charge, before recording it. What happens on retry?
The customer is charged twice. The retry generates a new UUID, so the billing API sees a new request. The key has to be derived from something that is the same on every attempt, such as the page’s run_id:step.
Quick answers
Why do long agent tasks fail?
Reliability compounds: a k-step task succeeds with probability p^k. At 95% per step, a 100-step task lands under 1%. The steps aren't hard — the length is, because one failure anywhere derails the whole run.
How does checkpointing help?
It saves progress so a failure doesn't restart from zero. Combined with resume, you break the p^k chain into segments and retry only the failed one — a c-step segment retried r times succeeds 1−(1−p^c)^r.
What is an agent's time horizon?
The task length it can complete at a given success rate (e.g. 50%). It's been doubling on a regular cadence. Reliability engineering — checkpoints, retries, verification — extends the usable horizon beyond raw per-step reliability.
How is this different from agent evals?
Agent-evals measures the decay (pass@k vs pass^k). This handbook engineers around it: checkpointing, resumable state, segment retries, and verification between steps. And self-improving agents asks the next question: can the agent shorten its own failures over time?
How do long-running agents keep state across context windows?
They keep it outside the context window. In Anthropic's harness for long-running coding agents, an initializer session writes an init.sh script, a progress file and a JSON feature list with every feature marked failing, then makes a git commit. Each later session reads the progress file and git log, runs a basic end-to-end test, works on one feature, commits, and updates the progress file. Compaction then summarizes a conversation near the context limit so work can continue in a fresh window.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Agentic AI Interview HandbookTwenty topics every senior AI engineer should be able to reason about live — from eval pipelines to reliability patterns for generative systems.Read →
- The Agent Evaluations HandbookA self-contained handbook on evaluating AI agents — theory, interactive widgets, and practical guidance. Trajectory evals, tool-use scoring, LLM-as-judge, observability, and reliability for PMs, engineers, and founders.Read →
- The Agent Patterns HandbookThe design patterns behind every LLM agent — the ReAct Thought–Action–Observation loop, tool/function calling, plan-and-execute, reflection, memory, multi-agent orchestration, and the failure modes (loops, hallucinated tools, recovery, human-in-the-loop) that break agents in production.Read →
- The Model Context Protocol (MCP) HandbookThe open standard connecting AI agents to the outside world — why M×N bespoke integrations collapse to M+N, the host/client/server roles over JSON-RPC, the three primitives (tools, resources, prompts), the connect→discover→call session lifecycle, when MCP earns its keep, and the security sharp edges (a server's output is untrusted input).Read →
- The Loop Engineering HandbookStop prompting your agents — design the system that prompts them for you. The inner vs outer loop, the four loop types (heartbeat, cron, hook, goal), the six building blocks (automations, worktrees, skills, MCP connectors, subagents, external memory), stopping conditions and the verification split, state across runs, cost engineering, and the six failure modes that burn tokens at 3am.Read →
- The Context Engineering HandbookThe discipline that replaced prompt-tweaking: curating everything the model sees under a finite attention budget. The anatomy of a production context window, the three taxes on an overstuffed one (context rot, cost, behavioral drift), the four operations (write, select, compress, isolate), agent-specific patterns like compaction and just-in-time retrieval, six production habits, and where it sits in the prompt → context → loop → harness stack.Read →