Why free-form agent loops collapse in production
Across Hacker News and engineering postmortems, the consensus in 2026 is clear: giving an LLM an open-ended while-loop and 25 tools works in a 3-step demo and fails silently in production. Every unconstrained step multiplies model variance, context drift, and prompt-injection surface area.
Instead of asking the model to invent the next control-flow step from scratch, treat the LLM as a bounded decision engine inside a deterministic state machine. Control flow lives in compiled code; language intelligence lives at well-typed transition edges.
- Explicit states (e.g., ClassifyIntent -> FetchContext -> DraftAction -> AwaitApproval -> Execute) prevent circular retries.
- Per-state tool allowlists ensure a drafting state can never invoke destructive billing or deletion tools.
- Hard transition budgets (max retries per edge, max tokens per run) cap worst-case latency and API spend.
Free-form ReAct loops vs. constrained FSM + Rust guards
| Dimension | Free-Form ReAct Loop | Constrained FSM + Rust Guards |
|---|---|---|
| Control flow | Implicit in LLM prompt history | Explicit typed state graph in code |
| Tool permissions | All tools exposed on every turn | Scoped allowlist per active state |
| Prompt injection blast radius | Arbitrary tool execution | Blocked by deterministic guard predicates |
| Failure recovery | Restart entire run from step 0 | Resume from last persisted state checkpoint |
| Auditability | Unstructured text traces | Typed state-transition ledger (SOC2 ready) |
Typed state transitions and guard predicates in Rust
A lightweight state machine does not require a heavy orchestration framework. Encoding states, allowed transitions, and budget guards as an enum in Rust (or a discriminated union in TypeScript) makes invalid transitions unrepresentable at compile time and takes under 2 milliseconds per check.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AgentState { Classify, Retrieve, Draft, AwaitHuman, Execute, Failed }
pub struct GuardCtx { pub tokens_used: u32, pub max_tokens: u32, pub human_approved: bool }
pub fn can_transition(from: AgentState, to: AgentState, ctx: &GuardCtx) -> Result<(), &'static str> {
if ctx.tokens_used > ctx.max_tokens {
return Err("token_budget_exceeded");
}
match (from, to) {
(AgentState::Classify, AgentState::Retrieve) => Ok(()),
(AgentState::Retrieve, AgentState::Draft) => Ok(()),
(AgentState::Draft, AgentState::AwaitHuman) => Ok(()),
(AgentState::AwaitHuman, AgentState::Execute) if ctx.human_approved => Ok(()),
(_, AgentState::Failed) => Ok(()),
_ => Err("illegal_state_transition"),
}
}Checkpointing, replay, and human-in-the-loop gates
Because every state transition is deterministic and small, you can persist `(run_id, state, payload_hash, tokens_used)` to Postgres after each edge. If an upstream LLM provider times out during `Draft`, your worker resumes from `Retrieve` without re-running expensive embeddings or duplicating side effects.
- Attach an idempotency key (`run_id:state:attempt`) to every external API or webhook call.
- Require `human_approved == true` before any state that mutates billing, sends customer emails, or writes to production databases.
- Emit structured OpenTelemetry spans per transition so you can measure exact p95 latency and failure rates by state.