Building Robust State Handlers to Prevent AI Agent Crashes Mid-Task

Learn how to build fault-tolerant AI agent execution with Python using state management, SQLite checkpointing, retry strategies, and crash recovery. Includes a practical implementation and a real process-crash test.

Kumar NihalNovember 19, 20269 min read
On this page

Building Robust State Handlers to Prevent AI Agent Crashes Mid-Task

An AI agent can complete four steps of a task and fail on the fifth. An API request times out, a tool stops responding, the process crashes, or the execution environment runs out of resources.

What happens next?

In a basic implementation, the agent may lose its progress and start from the beginning. That means repeated API calls, duplicated operations, wasted tokens, and frustrated users.

This is one of the challenges of building reliable AI agents: an agent should not have to forget everything just because its execution was interrupted.

A robust state handler helps an agent track its progress, preserve completed work, handle failures, and recover from interruptions.

In this guide, we'll build a practical Python implementation using state management, SQLite checkpoints, retry strategies, and recovery logic. We'll also simulate an actual process crash to see what happens when an agent needs to resume its work.

1. Why Do AI Agents Fail Mid-Task?#

AI agents often execute multiple operations in sequence. For example, an agent handling a research task might:

  1. Collect information from external sources.
  2. Analyze the collected information.
  3. Generate a report.
  4. Save the report.
  5. Notify the user.

If the process crashes during analysis, a basic implementation may lose track of what has already been completed.

Common causes include:

  • API timeouts: An external service takes too long to respond.
  • Tool failures: A connected tool returns an error or becomes unavailable.
  • Process crashes: The application terminates unexpectedly.
  • Context exhaustion: The agent reaches its available context limit.
  • Network interruptions: A request fails because of temporary connectivity issues.

Not every failure requires the entire task to restart. Some failures can be retried, while others require restoring the last saved execution state.

That's where state management becomes important.

2. What Is AI Agent State Management?#

AI agent state management is the process of tracking and maintaining an agent's execution information throughout a task.

Instead of treating an agent as a function that runs from beginning to end, we maintain a record of its current progress.

For our implementation, the state contains:

State fieldPurpose
task_idIdentifies the execution task
statusTracks whether the task is pending, running, completed, failed, or interrupted
current_stepTracks the current execution position
completed_stepsStores successfully completed steps
pending_stepsStores steps that still need execution
contextHolds task-related information
retry_countTracks retry attempts
checkpoint_versionTracks saved state versions

This information allows the system to understand where an agent stopped and what it needs to do next.

The important distinction: execution state is not the same as an LLM's conversation history. A conversation may provide context, but execution state tells the system which operations have actually been completed.

Implementing the Agent State#

We use Pydantic to define and validate the state structure.

[state.py]

python

from datetime import datetime, timezone
from enum import Enum
from typing import Any
from uuid import uuid4

from pydantic import BaseModel, Field, ConfigDict


class TaskStatus(str, Enum):
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    INTERRUPTED = "interrupted"


class AgentState(BaseModel):
    model_config = ConfigDict(validate_assignment=True)

    task_id: str = Field(default_factory=lambda: str(uuid4()))
    status: TaskStatus = TaskStatus.PENDING

    current_step: int = 0
    completed_steps: list[str] = Field(default_factory=list)
    pending_steps: list[str] = Field(default_factory=list)

    context: dict[str, Any] = Field(default_factory=dict)
    error: str | None = None

    retry_count: int = 0
    checkpoint_version: int = 0

    created_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc)
    )
    updated_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc)
    )

    def update_timestamp(self) -> None:
        self.updated_at = datetime.now(timezone.utc)

    def mark_running(self) -> None:
        self.status = TaskStatus.RUNNING
        self.error = None
        self.update_timestamp()

    def mark_completed(self) -> None:
        self.status = TaskStatus.COMPLETED
        self.error = None
        self.update_timestamp()

    def mark_failed(self, error: str) -> None:
        self.status = TaskStatus.FAILED
        self.error = error
        self.update_timestamp()

    def mark_interrupted(self, reason: str) -> None:
        self.status = TaskStatus.INTERRUPTED
        self.error = reason
        self.update_timestamp()

    def complete_step(self, step_name: str) -> None:
        if step_name not in self.completed_steps:
            self.completed_steps.append(step_name)

        if step_name in self.pending_steps:
            self.pending_steps.remove(step_name)

        self.current_step += 1
        self.update_timestamp()

Python implementation of the AI agent state model.

3. Build a State Handler to Control Execution#

Storing state is only part of the solution. We also need a component that controls how the state changes.

For example, a completed task should not accidentally return to a running state. Similarly, an interrupted task should be allowed to resume.

Our state handler manages these transitions:

  • PENDING → RUNNING
  • RUNNING → COMPLETED
  • RUNNING → FAILED
  • RUNNING → INTERRUPTED
  • INTERRUPTED → RUNNING
  • FAILED → RUNNING

A completed task cannot transition back into execution.

Keeping these transitions explicit prevents inconsistent state changes and makes the execution flow easier to understand.

Implementing the State Handler#

The handler manages task status, completed steps, pending steps, and state transitions.

[ handler.py]

python

from threading import RLock

from state import AgentState, TaskStatus


class StateTransitionError(Exception):
    """Raised when an invalid state transition is attempted."""


class AgentStateHandler:
    ALLOWED_TRANSITIONS = {
        TaskStatus.PENDING: {
            TaskStatus.RUNNING,
            TaskStatus.INTERRUPTED,
            TaskStatus.FAILED,
        },
        TaskStatus.RUNNING: {
            TaskStatus.COMPLETED,
            TaskStatus.FAILED,
            TaskStatus.INTERRUPTED,
        },
        TaskStatus.INTERRUPTED: {
            TaskStatus.RUNNING,
            TaskStatus.FAILED,
        },
        TaskStatus.FAILED: {
            TaskStatus.RUNNING,
        },
        TaskStatus.COMPLETED: set(),
    }

    def __init__(self, state: AgentState | None = None):
        self.state = state or AgentState()
        self._lock = RLock()

    def _transition(self, new_status: TaskStatus) -> None:
        current_status = self.state.status

        if new_status not in self.ALLOWED_TRANSITIONS[current_status]:
            raise StateTransitionError(
                f"Invalid transition: {current_status.value} "
                f"-> {new_status.value}"
            )

        if new_status == TaskStatus.RUNNING:
            self.state.mark_running()
        elif new_status == TaskStatus.COMPLETED:
            self.state.mark_completed()
        elif new_status == TaskStatus.FAILED:
            self.state.mark_failed(self.state.error or "Task failed")
        elif new_status == TaskStatus.INTERRUPTED:
            self.state.mark_interrupted(
                self.state.error or "Task interrupted"
            )

    def start(self) -> AgentState:
        with self._lock:
            self._transition(TaskStatus.RUNNING)
            return self.state

    def complete(self) -> AgentState:
        with self._lock:
            if self.state.pending_steps:
                raise StateTransitionError(
                    "Cannot complete task while pending steps remain"
                )

            self._transition(TaskStatus.COMPLETED)
            return self.state

    def fail(self, error: str) -> AgentState:
        with self._lock:
            self.state.error = error
            self._transition(TaskStatus.FAILED)
            return self.state

    def interrupt(self, reason: str) -> AgentState:
        with self._lock:
            self.state.error = reason
            self._transition(TaskStatus.INTERRUPTED)
            return self.state

    def resume(self) -> AgentState:
        with self._lock:
            self._transition(TaskStatus.RUNNING)
            return self.state

    def set_steps(self, steps: list[str]) -> AgentState:
        with self._lock:
            if self.state.status != TaskStatus.PENDING:
                raise StateTransitionError(
                    "Steps can only be configured before execution"
                )

            if len(steps) != len(set(steps)):
                raise ValueError("Duplicate step names are not allowed")

            self.state.pending_steps = [
                step for step in steps
                if step not in self.state.completed_steps
            ]

            self.state.update_timestamp()
            return self.state

    def complete_step(self, step_name: str) -> AgentState:
        with self._lock:
            if self.state.status != TaskStatus.RUNNING:
                raise StateTransitionError(
                    "Steps can only be completed while running"
                )

            if step_name in self.state.completed_steps:
                return self.state

            if step_name not in self.state.pending_steps:
                raise ValueError(
                    f"Unknown or already processed step: {step_name}"
                )

            self.state.complete_step(step_name)
            return self.state

    def get_state(self) -> AgentState:
        with self._lock:
            return self.state.model_copy(deep=True)

Python state handler for managing AI agent execution transitions.

4. Why State Persistence and Checkpointing Matter#

An in-memory state handler cannot protect an agent from a complete process crash.

When the application terminates, its in-memory data disappears.

To recover from that situation, we need persistent storage.

For this implementation, we use SQLite through aiosqlite. The checkpoint store saves the agent's state as JSON, along with its task ID, checkpoint version, and update timestamp.

The execution flow looks like this:

  1. The agent starts a task.
  2. It completes an execution step.
  3. The updated state is saved as a checkpoint.
  4. The next step begins.
  5. If the process crashes, the last saved checkpoint remains available.
  6. The recovery component loads that checkpoint.

This approach reduces the amount of work that needs to be repeated after an interruption.

Implementing SQLite Checkpoint Storage#

[checkpoint.py]

python

import asyncio
from datetime import datetime, timezone

import aiosqlite

from state import AgentState


class CheckpointError(Exception):
    """Raised when checkpoint operations fail."""


class SQLiteCheckpointStore:

    def __init__(self, db_path: str = "agent_checkpoints.db"):
        self.db_path = db_path
        self._lock = asyncio.Lock()

    async def initialize(self) -> None:
        try:
            async with aiosqlite.connect(self.db_path) as db:
                await db.execute("""
                    CREATE TABLE IF NOT EXISTS checkpoints (
                        task_id TEXT PRIMARY KEY,
                        state_json TEXT NOT NULL,
                        version INTEGER NOT NULL,
                        updated_at TEXT NOT NULL
                    )
                """)
                await db.commit()

        except Exception as exc:
            raise CheckpointError(
                f"Database initialization failed: {exc}"
            ) from exc

    async def save(self, state: AgentState) -> AgentState:
        async with self._lock:
            snapshot = state.model_copy(deep=True)
            snapshot.checkpoint_version += 1
            snapshot.updated_at = datetime.now(timezone.utc)

            try:
                async with aiosqlite.connect(self.db_path) as db:
                    await db.execute("""
                        INSERT INTO checkpoints (
                            task_id, state_json, version, updated_at
                        )
                        VALUES (?, ?, ?, ?)
                        ON CONFLICT(task_id) DO UPDATE SET
                            state_json = excluded.state_json,
                            version = excluded.version,
                            updated_at = excluded.updated_at
                    """, (
                        snapshot.task_id,
                        snapshot.model_dump_json(),
                        snapshot.checkpoint_version,
                        snapshot.updated_at.isoformat(),
                    ))

                    await db.commit()

                state.checkpoint_version = snapshot.checkpoint_version
                state.updated_at = snapshot.updated_at

                return state

            except Exception as exc:
                raise CheckpointError(
                    f"Checkpoint save failed: {exc}"
                ) from exc

    async def load(self, task_id: str) -> AgentState | None:
        async with self._lock:
            try:
                async with aiosqlite.connect(self.db_path) as db:
                    async with db.execute("""
                        SELECT state_json
                        FROM checkpoints
                        WHERE task_id = ?
                    """, (task_id,)) as cursor:

                        row = await cursor.fetchone()

                if row is None:
                    return None

                return AgentState.model_validate_json(row[0])

            except Exception as exc:
                raise CheckpointError(
                    f"Checkpoint load failed: {exc}"
                ) from exc

    async def delete(self, task_id: str) -> bool:
        async with self._lock:
            try:
                async with aiosqlite.connect(self.db_path) as db:
                    cursor = await db.execute("""
                        DELETE FROM checkpoints
                        WHERE task_id = ?
                    """, (task_id,))

                    await db.commit()
                    return cursor.rowcount > 0

            except Exception as exc:
                raise CheckpointError(
                    f"Checkpoint deletion failed: {exc}"
                ) from exc

SQLite-based asynchronous checkpoint storage for AI agent state persistence.

One important design decision is when to save a checkpoint. In our implementation, the state is persisted after each successfully completed step.

This provides a clear recovery boundary, although it does not make external operations transactional.

5. Implement Retry Strategies for Temporary Failures#

Not every failure requires task recovery.

Some failures are temporary. An API may return a timeout, or a network connection may fail briefly.

Instead of immediately marking the task as failed, we can retry operations that are safe to retry.

Our implementation uses:

  • A configurable maximum number of attempts.
  • Exponential backoff.
  • A maximum waiting period.
  • A defined set of retryable exceptions.

For example, if an operation fails because of a temporary connection error, the system can wait and try again.

However, retries must be used carefully.

Consider an agent that sends an email or processes a payment. If the external operation succeeds but the response is lost, blindly retrying could perform the same action twice.

For operations with external side effects, use idempotency keys, deduplication, or an appropriate verification mechanism.

Retries improve resilience, but they do not automatically make operations safe to repeat.

Implementing the Retry Handler#

[retry.py]

python

import asyncio
import logging
from dataclasses import dataclass
from typing import Awaitable, Callable, TypeVar

from tenacity import (
    AsyncRetrying,
    retry_if_exception_type,
    stop_after_attempt,
    wait_exponential,
)

T = TypeVar("T")

logger = logging.getLogger(__name__)


class RetryExhaustedError(Exception):
    """Raised when all retry attempts fail."""

    def __init__(self, attempts: int, last_error: Exception):
        self.attempts = attempts
        self.last_error = last_error

        super().__init__(
            f"Operation failed after {attempts} attempts: {last_error}"
        )


@dataclass
class RetryConfig:
    max_attempts: int = 3
    initial_wait: float = 1.0
    max_wait: float = 10.0
    multiplier: float = 2.0

    def __post_init__(self):
        if self.max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")

        if self.initial_wait < 0 or self.max_wait < 0:
            raise ValueError("Wait durations cannot be negative")

        if self.multiplier < 1:
            raise ValueError("multiplier must be at least 1")


class RetryHandler:

    def __init__(
        self,
        config: RetryConfig | None = None,
        retryable_exceptions: tuple[type[Exception], ...] = (
            ConnectionError,
            TimeoutError,
        ),
    ):
        self.config = config or RetryConfig()
        self.retryable_exceptions = retryable_exceptions

    async def execute(
        self,
        operation: Callable[[], Awaitable[T]],
    ) -> T:

        attempts = 0

        try:
            async for attempt in AsyncRetrying(
                stop=stop_after_attempt(self.config.max_attempts),
                wait=wait_exponential(
                    multiplier=self.config.initial_wait,
                    min=self.config.initial_wait,
                    max=self.config.max_wait,
                    exp_base=self.config.multiplier,
                ),
                retry=retry_if_exception_type(
                    self.retryable_exceptions
                ),
                reraise=True,
            ):
                with attempt:
                    attempts += 1

                    logger.info(
                        "Executing operation, attempt %s/%s",
                        attempts,
                        self.config.max_attempts,
                    )

                    return await operation()

        except self.retryable_exceptions as exc:
            logger.error(
                "Operation failed after %s attempts: %s",
                attempts,
                exc,
            )
            raise RetryExhaustedError(attempts, exc) from exc

        raise RuntimeError("Retry execution ended unexpectedly")

Python retry handler using exponential backoff and configurable retry limits.

6. Recover an Agent After an Interruption#

Now we have state management, persistence, and retry handling. The next component is recovery.

The recovery manager loads the most recent checkpoint and determines how execution should continue.

For example:

  • A completed task does not need recovery.
  • A pending task can start normally.
  • An interrupted task can resume.
  • A task that was marked as running before an unexpected process termination must first be marked as interrupted.

That last case is particularly important.

A process may terminate while its saved state still says RUNNING. When the application starts again, the recovery manager must recognize that the previous execution did not finish normally.

It can then restore the state and allow the execution engine to resume the remaining work.

Implementing the Recovery Manager#

[recovery.py]

python

from state import AgentState, TaskStatus
from handler import AgentStateHandler
from checkpoint import SQLiteCheckpointStore


class RecoveryError(Exception):
    """Raised when task recovery cannot be completed."""


class AgentRecoveryManager:

    def __init__(self, store: SQLiteCheckpointStore):
        self.store = store

    async def recover(self, task_id: str) -> AgentStateHandler:
        try:
            await self.store.initialize()

            state = await self.store.load(task_id)

            if state is None:
                raise RecoveryError(
                    f"No checkpoint found for task: {task_id}"
                )

            if state.status == TaskStatus.COMPLETED:
                raise RecoveryError(
                    "Completed tasks cannot be resumed"
                )

            handler = AgentStateHandler(state)

            
            if state.status == TaskStatus.RUNNING:
                handler.interrupt(
                    "Previous process terminated unexpectedly"
                )

            elif state.status == TaskStatus.PENDING:
                pass

            elif state.status in (
                TaskStatus.INTERRUPTED,
                TaskStatus.FAILED,
            ):
                pass

            else:
                raise RecoveryError(
                    f"Unsupported task status: {state.status}"
                )

            await self.store.save(handler.state)

            return handler


        except RecoveryError:
            raise

        except Exception as exc:
            raise RecoveryError(
                f"Task recovery failed: {exc}"
            ) from exc

Recovery manager that restores an agent from its latest saved checkpoint.

7. Connect Everything with an Agent Executor#

Individual components are useful, but they need to work together.

The agent executor coordinates the complete execution lifecycle:

  1. Initialize persistent storage.
  2. Load or initialize the agent state.
  3. Identify pending steps.
  4. Execute the next step.
  5. Apply retry handling when appropriate.
  6. Mark the step as completed.
  7. Persist the updated checkpoint.
  8. Continue until the task is completed or interrupted.

If an execution step fails permanently, the executor records the failure instead of silently losing the task's progress.

This creates a simple but useful execution architecture:

State Manager → Execution Controller → Retry Handler → Checkpoint Store → Recovery Manager

The components have separate responsibilities, making the system easier to test and extend.

Implementing the Agent Executor#

[agent.py]

python

import asyncio
import logging
from collections.abc import Awaitable, Callable

from state import AgentState, TaskStatus
from handler import AgentStateHandler
from checkpoint import SQLiteCheckpointStore
from retry import RetryHandler, RetryExhaustedError


logger = logging.getLogger(__name__)

StepFunction = Callable[[], Awaitable[object]]


class AgentExecutionError(Exception):
    """Raised when agent execution fails."""


class AgentExecutor:

    def __init__(
        self,
        store: SQLiteCheckpointStore,
        steps: dict[str, StepFunction],
        state: AgentState | None = None,
        retry_handler: RetryHandler | None = None,
    ):
        if len(steps) != len(set(steps)):
            raise ValueError("Duplicate step names are not allowed")

        self.store = store
        self.steps = steps
        self.handler = AgentStateHandler(state)
        self.retry_handler = retry_handler or RetryHandler()

    async def run(self) -> AgentState:
        await self.store.initialize()

        state = self.handler.state

        if state.status == TaskStatus.COMPLETED:
            return self.handler.get_state()

        if state.status == TaskStatus.RUNNING:
            raise AgentExecutionError(
                "Task is already marked as running. "
                "Recover it before starting another execution."
            )

        if state.status in (
            TaskStatus.FAILED,
            TaskStatus.INTERRUPTED,
        ):
            self.handler.resume()

        elif state.status == TaskStatus.PENDING:
            self.handler.start()

        else:
            raise AgentExecutionError(
                f"Unsupported status: {state.status}"
            )

        await self.store.save(state)

        try:
            while state.pending_steps:
                step_name = state.pending_steps[0]

                operation = self.steps.get(step_name)

                if operation is None:
                    raise AgentExecutionError(
                        f"No implementation found for step: {step_name}"
                    )

                logger.info("Executing step: %s", step_name)

                await self.retry_handler.execute(operation)

                self.handler.complete_step(step_name)

                # Persist progress before moving to the next step.
                await self.store.save(state)

                logger.info("Completed step: %s", step_name)

            self.handler.complete()
            await self.store.save(state)

            return self.handler.get_state()

        except asyncio.CancelledError:
            self.handler.interrupt(
                "Execution cancelled"
            )

            await asyncio.shield(self.store.save(state))
            raise

        except Exception as exc:
            if state.status == TaskStatus.RUNNING:
                self.handler.fail(str(exc))

            try:
                await self.store.save(state)
            except Exception:
                logger.exception(
                    "Failed to persist agent failure state"
                )

            raise AgentExecutionError(
                f"Agent execution failed: {exc}"
            ) from exc

Python agent executor coordinating task execution, retries, and checkpoint persistence.

8. Test What Happens When the Process Actually Crashes#

A recovery mechanism should not be considered reliable just because a normal execution test passes.

We need to test what happens when the process terminates unexpectedly.

For this implementation, we created a test that simulates a real process crash using Python's os._exit().

The agent executes three steps:

  1. Research
  2. Analysis
  3. Report

The process is deliberately terminated during the analysis step, after its action has happened but before the completion checkpoint is saved.

A second process then loads the saved checkpoint and resumes execution.

What Happened?#

The execution history looked like this:

StepFirst executionRecovery execution
ResearchCompletedSkipped
AnalysisAction executed, checkpoint not savedExecuted again
ReportNot executedCompleted

The test produced these results:

  • Process crashed unexpectedly.
  • Agent resumed after process crash.
  • Previously completed step was preserved.
  • Remaining steps executed.
  • Task completed successfully.
  • Execution history verified.

The key finding: the research step was not repeated because its completion had already been checkpointed. The analysis step ran again because the process crashed before its completion was persisted.

This is an important limitation to understand.

Checkpointing does not guarantee exactly-once execution.

If an external operation succeeds but the application crashes before saving its completion, the operation may be repeated during recovery. This is why systems handling payments, emails, deployments, or other external side effects need additional idempotency and deduplication mechanisms.

Reproducing the Crash Recovery Test#

[test_fault_tolerance.py]

python

import asyncio
import os
import subprocess
import sys
import tempfile

from pathlib import Path

from state import AgentState, TaskStatus
from agent import AgentExecutor
from checkpoint import SQLiteCheckpointStore
from recovery import AgentRecoveryManager


TASK_ID = "crash-recovery-final-test"


def make_step(name, trace_file, crash=False):
    async def execute():
        with open(trace_file, "a", encoding="utf-8") as file:
            file.write(name + "\n")

        if crash:
            os._exit(23)

    return execute


async def crash_worker(db_path, trace_file):
    store = SQLiteCheckpointStore(db_path)

    steps = {
        "research": make_step("research", trace_file),
        "analysis": make_step("analysis", trace_file, crash=True),
        "report": make_step("report", trace_file),
    }

    state = AgentState(
        task_id=TASK_ID,
        pending_steps=list(steps),
    )

    executor = AgentExecutor(store, steps, state=state)
    await executor.run()


async def resume_worker(db_path, trace_file):
    store = SQLiteCheckpointStore(db_path)

    recovery = AgentRecoveryManager(store)
    handler = await recovery.recover(TASK_ID)

    steps = {
        "research": make_step("research", trace_file),
        "analysis": make_step("analysis", trace_file),
        "report": make_step("report", trace_file),
    }

    executor = AgentExecutor(
        store=store,
        steps=steps,
        state=handler.state,
    )

    result = await executor.run()

    assert result.status == TaskStatus.COMPLETED
    assert result.completed_steps == [
        "research", "analysis", "report"
    ]

    print("PASS: Agent resumed after process crash")
    print("PASS: Previously completed step preserved")
    print("PASS: Remaining steps executed")
    print("PASS: Task completed successfully")


def main():
    if len(sys.argv) > 1:
        mode = sys.argv[1]
        db_path = sys.argv[2]
        trace_file = sys.argv[3]

        if mode == "crash":
            asyncio.run(crash_worker(db_path, trace_file))
        elif mode == "resume":
            asyncio.run(resume_worker(db_path, trace_file))

        return

    with tempfile.TemporaryDirectory() as directory:
        db_path = str(Path(directory) / "crash_test.db")
        trace_file = str(Path(directory) / "execution.log")

        crash = subprocess.run([
            sys.executable,
            str(Path(__file__).resolve()),
            "crash",
            db_path,
            trace_file,
        ])

        assert crash.returncode == 23, (
            f"Expected simulated crash, got {crash.returncode}"
        )

        print("PASS: Process crashed unexpectedly")

        subprocess.run([
            sys.executable,
            str(Path(__file__).resolve()),
            "resume",
            db_path,
            trace_file,
        ], check=True)

        with open(trace_file, encoding="utf-8") as file:
            execution = file.read().splitlines()

        assert execution == [
            "research",
            "analysis",
            "analysis",
            "report",
        ], execution

        print("PASS: Execution history verified")
        print("\nAll crash recovery tests passed!")


if __name__ == "__main__":
    main()

Python subprocess test simulating unexpected process termination and agent recovery.

9. Engineering Lessons and Limitations#

Building a fault-tolerant execution flow requires more than saving a JSON file.

A few practical lessons from this implementation:

  • Keep execution state separate from conversation context. The system should know what has actually completed.
  • Persist progress regularly. Saving after each completed step creates clear recovery points.
  • Use retries selectively. Not every exception is temporary, and not every operation is safe to repeat.
  • Validate state transitions. Explicit rules help prevent inconsistent execution states.
  • Test actual interruptions. Normal success tests cannot demonstrate crash recovery.
  • Understand checkpoint boundaries. A crash between an external side effect and its checkpoint can cause repeated execution.

This implementation is intentionally a focused prototype, not a complete production-grade agent orchestration platform.

It uses a sequential execution model and SQLite-based checkpoints. It does not implement distributed worker coordination, cross-process execution locks, transactional external side effects, or exactly-once guarantees.

Those requirements need additional architecture depending on the application and its workload.

The goal here is to demonstrate the core mechanics of state handling and recovery without turning a focused engineering example into an entire orchestration product.

Frequently Asked Questions (FAQ)#

1. What is state management in AI agents?#

State management is the process of tracking an AI agent's execution progress, including its current status, completed steps, pending tasks, and relevant context. It helps agents maintain execution continuity when failures or interruptions occur.

2. How can AI agents recover from unexpected crashes?#

AI agents can recover using persistent state storage and checkpointing. The system loads the latest saved state, identifies completed and pending steps, and resumes execution from the appropriate recovery point.

3. What is checkpointing in AI agent systems?#

Checkpointing is the process of periodically saving an agent's execution state to persistent storage. If an application crashes, the system can restore the last saved checkpoint instead of restarting the entire task.

4. What is the difference between retry and recovery in AI agents?#

Retry handles temporary failures by attempting the same operation again. Recovery restores the agent's execution state after an interruption or failure so it can continue unfinished work.

5. Does checkpointing guarantee exactly-once execution?#

No. If an external operation succeeds but the process crashes before its completion is saved, that operation may execute again during recovery. Idempotency keys and deduplication mechanisms help prevent duplicate side effects.

6. Which database can be used for AI agent state persistence?#

SQLite, PostgreSQL, and other persistent databases can store agent execution state. The right choice depends on the application's workload, concurrency requirements, and deployment architecture.

Conclusion#

AI agent failures are inevitable in systems that depend on APIs, tools, external services, and long-running execution.

The real engineering challenge is not simply preventing every failure. It is making sure that a failure does not unnecessarily destroy the progress already made.

By combining structured state management, checkpoint persistence, retry strategies, and recovery logic, we can build AI agents that handle interruptions more intelligently.

Our Python implementation demonstrates this with a real process-crash test: previously checkpointed work was preserved, while an interrupted step was executed again.

That distinction matters when designing reliable AI agent systems. Building AI agents that need reliable execution, recovery, or automation infrastructure? Let's discuss your engineering requirements.

Share
Kumar Nihal

Written by

Kumar Nihal

AI-first software engineer and founder of Causly. I build software, SaaS and AI systems, and write about it here. More about me

Get new posts by email

High-signal notes on AI, automation and building systems. No spam.

Keep reading

Insight

Why I Built PCSKit: Solving Context Loss in AI Coding Sessions

AI coding agents are productive, but their work can lose continuity when a context window fills up, a session gets interrupted, or developers switch between tools. I built PCSKit to solve this problem with local-first project continuity, evidence-based handoffs, and verifiable development history—so the next AI agent can continue from the actual project state instead of relying on an unreliable summary.

Nov 24, 2026