Beyond Git Worktree

Graceful Shutdown Patterns for Over-Budget AI Agent Sessions

Budget enforcement alone isn't enough; agents need shutdown paths that preserve work.

· 8 min read · Updated
Cover illustration for “Graceful Shutdown Patterns for Over-Budget AI Agent Sessions”
Agent Cost Controls · October 28, 2026 · 8 min read · 1,872 words

To prevent unexpected AI coding agent bills, teams need pre-call budget enforcement as well as spending alerts, the kind of limit that Ellipsis, a cloud agent platform running coding agents on managed infrastructure, applies before a session continues rather than reporting overruns afterward. Graceful shutdown requires a second layer that preserves useful work before execution stops. The control stack combines budget checks, constrained execution, and a shutdown policy that selects downgrade, checkpoint, partial return, summarization, or escalation according to remaining budget and task risk.

Why a hard stop is the wrong default when an agent hits its budget ceiling

Enforcement decides whether another call may execute. The shutdown strategy decides what to do with the work already done. Waxell's 2026 analysis distinguishes alerts, which notify after spending occurs, from enforcement, which blocks the next LLM call. That distinction establishes the spending boundary, but it does not define a usable outcome for the developer.

An abrupt stop can leave no result, explanation, saved state, or next step. Across a large engineering organization, repeated terminations compound into lost context and interrupted work. Designers must therefore decide whether to enforce a limit and what the agent can preserve before the session closes.

How runaway costs actually happen — the cost structure that makes shutdown design non-trivial

Agent cost can grow closer to quadratically than linearly as conversation history accumulates. Each request includes not only new content but also earlier context, so later steps cost more than earlier ones. Counting steps alone is therefore a poor way to predict spending. The spending boundary can arrive while the task remains unfinished and before a useful result is ready.

Waxell's November 2025 incident account describes a LangChain market research pipeline whose Analyzer and Verifier agents kept exchanging requests until the team identified the loop through billing data. The account traces the spending to the lack of per-agent budget caps and pre-call termination. Neither agent needed to fail for spending to continue. Agent-to-agent coordination can sustain locally valid reasoning without reaching a stopping point, leaving shutdown logic to handle whatever partial state exists when enforcement intervenes.

The three enforcement signals that determine which shutdown pattern applies

Cycles' degradation framework defines three signals, namely ALLOW, ALLOW_WITH_CAPS, and DENY. ALLOW permits normal execution, while ALLOW_WITH_CAPS permits work under constraints before the budget is exhausted. DENY blocks further budgeted execution and requires a stop or another permitted response. The middle signal creates room for adaptation. Without it, a binary policy goes straight from running as usual to refusing to run, with little chance to prepare a useful ending.

Framework controls provide pieces of this behavior, but their signals are not interchangeable. LangGraph raises GraphRecursionError, while the OpenAI Agents SDK raises MaxTurnsExceeded and provides error_handlers. These are execution limits. The Claude Agent SDK provides session spending controls through max_budget_usd and structured result messages, while LangChain supplies summarization, fallback, and human-approval middleware. Cycles identifies the remaining gap as a unified application-level degradation policy, which must distinguish warning thresholds from exhausted budgets rather than treat every limit as one generic exception.

Pattern 1 — Model downgrade: staying in the task at lower cost

Model downgrade belongs at ALLOW_WITH_CAPS, when there is still room in the budget. The agent checks whether its preferred model fits the remaining cap, then walks a configured fallback chain until it finds one that does. This is a poor choice when the less capable model gives wrong answers. A risk-sensitive legal review should not silently switch to a smaller model and return a plausible but incorrect conclusion. Downgrade must be an explicit opt-in policy for tasks that tolerate it.

Context size also constrains the fallback path. A cheaper model may have a smaller effective context window, so it may need truncation or summarization before the next call. Skipping that preparation risks failure or degraded output. Conversely, automatic escalation to a larger model can cause a 30x per-token cost jump. Gateway model-tier rules can limit development keys to smaller model classes, so teams should check those controls in their gateway provider's documentation.

Pattern 2 — Checkpoint and suspend: preserving state so work can resume

When downgrade is exhausted or inappropriate, a structured multi-step task can suspend with its intermediate state intact. Anthropic recommends progress files so agents can pick up where they left off. A useful checkpoint records completed steps and outputs, current task state, an accumulated context summary, the suspension trigger, and reconstruction metadata. The checkpoint makes later resumption possible without replaying completed work. It also supplies the foundation for the escalation handoff described below.

The Go runtime pattern illustrates bounded shutdown. On context cancellation, it completes the current step, records partial results, and emits run.cancelled. On SIGTERM, it stops accepting new runs, completes in-flight steps, and exits through a timeout-bounded Shutdown(ctx context.Context) error. A token budget schema tracks cumulative usage across the run and uses BudgetAlertThreshold to create time for checkpointing before the hard limit. Completing a step cannot authorize calls that enforcement has already denied, which makes that warning window essential.

Checkpointing requires durable state worth restoring. A one-shot query or single-step synthesis may offer no meaningful resumption point. In that case, the next question is whether any completed output has independent value.

Pattern 3 — Partial result return: delivering what was completed before the ceiling hit

Partial-result return works for tasks that have no useful way to resume but have finished parts worth returning. A partial result contains finished work from before termination, whereas a corrupted result exposes unfinished or inconsistent work as usable output. Every partial return needs an explicit incomplete label, the completed sub-results, the stopping point, the budget reason, the unfinished scope, and the caller's next step.

A PR review agent that completes three of five files can return findings for those three while identifying the unreviewed files. The OpenAI SDK's error_handlers can produce controlled final output on MaxTurnsExceeded, while the Claude SDK's structured budget-exhaustion results support a partial-result envelope. Neither mechanism establishes output validity by itself. Reasoning-heavy work still needs a quality gate, because a half-completed refactoring suggestion may leave code inconsistent and be worse than no suggestion.

Pattern 4 — Graceful summarization: condensing session state into a handoff artifact

Graceful summarization should begin at ALLOW_WITH_CAPS, before DENY, because producing the summary itself consumes tokens. Waiting for exhaustion defeats the mechanism that was supposed to preserve context. This pattern is useful when neither resumption nor completed sub-results adequately serve the user, but an account of the investigation can help someone take over. The artifact preserves decisions as well as conversation history. It should distinguish completed work, work in progress, work not started, key decisions, live hypotheses, and the recommended next step.

CrewAI illustrates the underlying compression mechanism through proactive summarization near the context-window threshold and reactive summarization on overflow when respect_context_window=True, the default. That mechanism can also condense session history before shutdown. Cycles specifies that a stop message should explain the budget limit, what was saved, what remains unfinished, and what the user can do next. For long-running research, that summary may be the deliverable itself, while also providing a human-readable audit record of intent, progress, and stopping reason.

Pattern 5 — Escalation handoff: routing the suspended session to a human or a higher-authority agent

Some budget events indicate an authorization boundary. A valid task may need a spending extension that a human can approve. Or its next step may involve irreversible actions, cross-system writes, or sensitive data that need review. These are different reasons for the same pause. Neither should be resolved through an automatic downgrade that avoids the decision about scope or risk.

Effective escalation depends on a checkpoint or summary that the recipient can act on. A feature-building agent that exhausts its budget mid-implementation should route to the initiating developer with completed work preserved and remaining work described. Access must end with the suspended session. Its credentials should be revoked, and the session should get fresh credentials when it resumes so that its authority ends with the original window. If there is no useful partial state, resumable checkpoint, or meaningful summary, a clean stop with a clear explanation and next step is the honest response.

How to stop AI coding agents from running up unexpected API bills — the infrastructure layer

Shutdown patterns at the application level need enforcement that the agent cannot skip. An external check must evaluate the budget before the LLM call executes, rather than rely on the agent to consult its own counter. Enforcement placement is a concrete selection criterion. Cycles and Waxell both describe pre-execution enforcement and implement it at the application or SDK layer.

The control stack also needs more than a total spending cap. A monthly cap still permits rapid consumption of the entire allowance, while a circuit breaker detects an anomalous spending rate before that allowance is exhausted. Session isolation addresses a different failure path. An isolated sandbox with session-scoped credentials revoked at completion prevents a terminated session's retry loop from reusing lingering access. These controls complement shutdown policy rather than replace its decision about what to preserve.

Observability makes the resulting behavior distinguishable in practice. Shutdown records must include run_id, session_id, the triggering signal, the applied pattern, what was saved, and what was not. Without those fields, an audit record may show that a run ended but leave it unclear whether the run left anything useful. The structured summary supplies readable context, while the event records which control fired.

How to choose which pattern fires — and how to configure it as code

Teams should centralize shutdown decisions in per-agent configuration. Runtime settings can specify MaxSteps, MaxRuntimeSeconds, PerToolTimeoutSec, and TokenBudget, including MaxTotalTokens and BudgetAlertThreshold. ConversationHistory configuration defines how retained context changes as constraints tighten. Each control addresses a different limit. Together, they make the agent's authorized operating range readable without inspecting its task logic.

The warning policy should trigger downgrade only where the task tolerates reduced capability, then checkpoint at a higher warning level. At DENY, the policy should return valid partial results with clear labels or escalate, based on the kind of task and its risk. Summary preparation belongs before that final boundary. The shutdown path should emit the prepared summary rather than attempt an unauthorized generation call after exhaustion. Where no meaningful summary exists, the clear stop explanation remains the appropriate output.

The context policy's TruncationStrategy can use a sliding window to keep the last N messages within budget, summarize older messages, or drop the oldest messages. The summarize-older option expresses the compression behavior used by graceful summarization, while the shutdown policy determines when to produce the handoff artifact. Irreversible actions need explicit approval routing at the gate. That lets escalation fire because of the action's policy requirements.

Regardless of pattern, shutdown should emit a structured run.cancelled or run.token_budget_exceeded event. Its fields should include run_id, trace_id, signal type, applied pattern, completed steps, and a reference to any checkpoint or summary. This becomes both an operational signal and an audit record. Teams should establish the configuration before scaling beyond prototypes, rather than reconstruct the intended policy from billing data after a runaway session. Teams should treat shutdown policy with the same care as infrastructure configuration, defining it in YAML, reviewing it in pull requests, and keeping it versioned in the repository.

More in Agent Cost Controls