# adityapainuli/stateful-agents architecture

> Architecture diagram of the GitHub repository adityapainuli/stateful-agents, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-23). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/adityapainuli/stateful-agents
- Repository: https://github.com/adityapainuli/stateful-agents

## Overview

1. **Repo shape and primary runtime**  
   The active system is the Python package under `python/stateful_agents/`. It is a small async agent runtime with four main boundaries: the workflow engine, durable state stores, distributed locking, and workflow-specific business logic. The `engine/` directory is an older TypeScript prototype kept as a reference, not the main runtime.

2. **Core execution model**  
   `stateful_agents/engine.py` is the center of the architecture. `AgentEngine.run()` follows a fixed loop: load persisted state, execute the handler for the current step, save the updated state, then advance. The important architectural choice is that progress is checkpointed after every step, so the workflow is resumable without replaying completed work.

3. **Durable state as the workflow boundary**  
   `stateful_agents/state.py` defines the `AgentState` model. It carries the agent identity, current step name, payload, and a fencing token. This state object is the handoff between the workflow logic and the persistence layer; the engine never relies on in-memory progress as the source of truth.

4. **Storage layer and backend swap point**  
   `stateful_agents/stores/` implements a single `StateStore` protocol with four backends: Redis, Postgres, SQLite, and an in-memory baseline. The runtime can therefore be deployed against different durability/performance tradeoffs without changing workflow code. The store is the authoritative persistence boundary for checkpoints.

5. **Crash safety mechanism**  
   The crash-safety guarantee comes from the checkpoint loop, not from replay or orchestration. If a process dies mid-step, the next process start loads the last saved state and resumes at that exact step. The repo’s demo and docs emphasize that a completed step is one whose state has been durably saved; partial step work is not treated as committed.

6. **Distributed coordination and fencing**  
   `stateful_agents/lock.py` provides `DistributedLock`, implemented with Redis primitives: `SET NX PX` for acquisition, a Lua-based release, a heartbeat for renewal, and `INCR` to issue monotonic fencing tokens. This is a separate coordination layer from the state store. Its job is to prevent two workers from acting on the same agent concurrently and to make stale writers detectable.

7. **Stale-write protection at the storage boundary**  
   Every `save()` path rejects writes with an older fencing token than what is already persisted. That means even if an old worker survives a partition or lock expiry, its late write is dropped server-side instead of silently overwriting newer state. The lock prevents most contention; fencing tokens protect against the cases the lock cannot fully prevent.

8. **Workflow composition layer**  
   `stateful_agents/workflows/research.py` is the sample application workflow. It shows how domain logic is plugged into the engine as named steps, with long-running work split into smaller resumable chunks. The workflow is where LLM calls, state transitions, and step-specific payload updates are composed.

9. **External model and I/O boundary**  
   `stateful_agents/llm.py` is the abstraction around model calls, keeping model interaction out of the engine itself. In the architecture diagram, this should be drawn as an external dependency reached from workflow code, not from the persistence or locking layers.

10. **Operational demos and validation paths**  
   `python/demos/run_research.py` exercises the normal workflow path, while `python/demos/crash_and_resume.py` intentionally kills a running process and demonstrates recovery from persisted state. These demos are important because they validate the main architectural promise: restart-safe progress with no replay of completed steps.

11. **Benchmarking and observability of the design**  
   `python/benchmarks/` is a separate harness for latency, throughput, and cold-resume measurement across stores. It is not part of the runtime path, but it helps characterize the architecture’s tradeoffs, especially the cost of per-step checkpointing and the recovery time after process restarts.

12. **Reference implementation in TypeScript**  
   `engine/src/*` mirrors the same conceptual pieces—runner, state store, Redis utilities, and a research workflow—but it is labeled as the original TS prototype. For architecture purposes, treat it as a reference model for the Python implementation rather than a separate deployed subsystem.

13. **What to draw as the key data flow**  
   The main flow is: worker process acquires Redis lock, loads `AgentState` from a chosen store, runs one workflow step, persists the new state with a fencing token, then repeats until done. The important external dependencies are the state backend and Redis for locking/fencing; everything else is internal orchestration around those two boundaries.

Main entry points: [`python/stateful_agents/stores/base.py`](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/base.py) (Store protocol), [`python/stateful_agents/engine.py`](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/engine.py) (Agent engine), [`python/stateful_agents/state.py`](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/state.py) (Agent state), [`engine/src/agent.runner.ts`](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/agent.runner.ts) (TS runner)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_python_runtime["Python runtime"]
  node_agent_engine["Agent engine<br/>async loop<br/>[engine.py]"]
  node_agent_state["Agent state<br/>checkpoint model<br/>[state.py]"]
end

subgraph group_coordination["Coordination"]
  node_distributed_lock{{"Distributed lock<br/>Redis lock<br/>[lock.py]"}}
end

subgraph group_storage["State stores"]
  node_state_store_base["Store protocol<br/>persistence API<br/>[base.py]"]
  node_memory_store[("Memory store<br/>store backend<br/>[memory_store.py]")]
  node_redis_store[("Redis store<br/>store backend<br/>[redis_store.py]")]
  node_postgres_store[("Postgres store<br/>store backend<br/>[postgres_store.py]")]
  node_sqlite_store[("SQLite store<br/>store backend<br/>[sqlite_store.py]")]
end

subgraph group_workflow["Workflow logic"]
  node_workflow_research_py["Research flow<br/>sample workflow<br/>[research.py]"]
  node_llm_py(("LLM boundary<br/>model adapter<br/>[llm.py]"))
end

subgraph group_ops["Ops"]
  node_run_demo["Research demo<br/>demo entrypoint<br/>[run_research.py]"]
  node_crash_demo["Crash demo<br/>fault-injection demo"]
  node_benchmarks["Benchmarks<br/>measurement harness<br/>[run_bench.py]"]
end

subgraph group_reference_ts["TS reference"]
  node_ts_runner["TS runner<br/>prototype runtime<br/>[agent.runner.ts]"]
  node_ts_state_store[("TS store<br/>prototype store<br/>[state.store.ts]")]
  node_ts_llm(("TS LLM<br/>prototype adapter<br/>[llm.ts]"))
  node_ts_redis{{"TS Redis<br/>prototype utils<br/>[redis.ts]"}}
  node_ts_research["TS research<br/>prototype workflow<br/>[research.ts]"]
end

node_agent_engine -->|"loads/saves"| node_agent_state
node_agent_engine -->|"uses"| node_state_store_base
node_agent_engine -->|"coordinates"| node_distributed_lock
node_agent_engine -->|"runs"| node_workflow_research_py
node_workflow_research_py -->|"calls"| node_llm_py
node_distributed_lock -->|"Redis primitives"| node_redis_store
node_state_store_base -->|"backend"| node_memory_store
node_state_store_base -->|"backend"| node_redis_store
node_state_store_base -->|"backend"| node_postgres_store
node_state_store_base -->|"backend"| node_sqlite_store
node_redis_store -->|"persists"| node_agent_state
node_postgres_store -->|"persists"| node_agent_state
node_sqlite_store -->|"persists"| node_agent_state
node_memory_store -->|"persists"| node_agent_state
node_run_demo -->|"exercises"| node_agent_engine
node_crash_demo -->|"exercises"| node_agent_engine
node_benchmarks -->|"measures"| node_state_store_base
node_ts_runner -->|"uses"| node_ts_state_store
node_ts_runner -->|"calls"| node_ts_llm
node_ts_runner -->|"runs"| node_ts_research
node_ts_state_store -->|"backed by"| node_ts_redis

click node_agent_engine "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/engine.py"
click node_agent_state "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/state.py"
click node_workflow_research_py "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/workflows/research.py"
click node_llm_py "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/llm.py"
click node_distributed_lock "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/lock.py"
click node_state_store_base "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/base.py"
click node_memory_store "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/memory_store.py"
click node_redis_store "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/redis_store.py"
click node_postgres_store "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/postgres_store.py"
click node_sqlite_store "https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/sqlite_store.py"
click node_run_demo "https://github.com/adityapainuli/stateful-agents/blob/main/python/demos/run_research.py"
click node_crash_demo "https://github.com/adityapainuli/stateful-agents/blob/main/python/demos/crash_and_resume.py"
click node_benchmarks "https://github.com/adityapainuli/stateful-agents/blob/main/python/benchmarks/run_bench.py"
click node_ts_runner "https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/agent.runner.ts"
click node_ts_state_store "https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/stores/state.store.ts"
click node_ts_llm "https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/llm.ts"
click node_ts_redis "https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/utils/redis.ts"
click node_ts_research "https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/workflows/research.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_agent_engine,node_agent_state toneBlue
class node_distributed_lock toneAmber
class node_state_store_base,node_memory_store,node_redis_store,node_postgres_store,node_sqlite_store toneMint
class node_workflow_research_py,node_llm_py toneRose
class node_run_demo,node_crash_demo,node_benchmarks toneIndigo
class node_ts_runner,node_ts_state_store,node_ts_llm,node_ts_redis,node_ts_research toneTeal
```

## Components

### Python runtime

Primary async agent runtime and its operational entrypoints.

- [Agent engine](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/engine.py): async loop · Main step loop: load state, run handler, save checkpoint, advance. · `python/stateful_agents/engine.py`
- [Agent state](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/state.py): checkpoint model · Durable workflow state carrying identity, step, payload, and fencing token. · `python/stateful_agents/state.py`

### Coordination

Locking and fencing for concurrent workers.

- [Distributed lock](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/lock.py): Redis lock · Acquisition, renewal, release, and monotonic fencing token issuance. · `python/stateful_agents/lock.py`

### State stores

Durable checkpoint backends behind a shared protocol.

- [Store protocol](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/base.py): persistence API · Common save/load contract with fencing enforcement at the storage boundary. · `python/stateful_agents/stores/base.py`
- [Memory store](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/memory_store.py): store backend · In-memory baseline implementation of the state store protocol. · `python/stateful_agents/stores/memory_store.py`
- [Redis store](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/redis_store.py): store backend · Durable state backend using Redis. · `python/stateful_agents/stores/redis_store.py`
- [Postgres store](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/postgres_store.py): store backend · Durable state backend using Postgres. · `python/stateful_agents/stores/postgres_store.py`
- [SQLite store](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/stores/sqlite_store.py): store backend · Durable state backend using SQLite. · `python/stateful_agents/stores/sqlite_store.py`

### Workflow logic

Application step logic and external model boundary.

- [Research flow](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/workflows/research.py): sample workflow · Named workflow steps with resumable chunks and state transitions. · `python/stateful_agents/workflows/research.py`
- [LLM boundary](https://github.com/adityapainuli/stateful-agents/blob/main/python/stateful_agents/llm.py): model adapter · Abstraction for external model calls used by workflow code. · `python/stateful_agents/llm.py`

### Ops

Demos and benchmarks that exercise and characterize the runtime.

- [Research demo](https://github.com/adityapainuli/stateful-agents/blob/main/python/demos/run_research.py): demo entrypoint · Normal execution path for the sample workflow. · `python/demos/run_research.py`
- [Crash demo](https://github.com/adityapainuli/stateful-agents/blob/main/python/demos/crash_and_resume.py): fault-injection demo · Kills a worker mid-run to validate resume from checkpoints. · `python/demos/crash_and_resume.py`
- [Benchmarks](https://github.com/adityapainuli/stateful-agents/blob/main/python/benchmarks/run_bench.py): measurement harness · Latency, throughput, and cold-resume characterization across stores. · `python/benchmarks/run_bench.py`

### TS reference

Older TypeScript prototype kept as an architectural reference.

- [TS runner](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/agent.runner.ts): prototype runtime · Original TypeScript agent runner kept as a reference implementation. · `engine/src/agent.runner.ts`
- [TS store](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/stores/state.store.ts): prototype store · TypeScript state store abstraction mirroring the Python persistence boundary. · `engine/src/stores/state.store.ts`
- [TS LLM](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/llm.ts): prototype adapter · TypeScript model-call boundary used by the prototype workflow. · `engine/src/llm.ts`
- [TS Redis](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/utils/redis.ts): prototype utils · Redis helper utilities for the prototype runtime. · `engine/src/utils/redis.ts`
- [TS research](https://github.com/adityapainuli/stateful-agents/blob/main/engine/src/workflows/research.ts): prototype workflow · Prototype research workflow mirroring the Python sample flow. · `engine/src/workflows/research.ts`

## Connections

- Agent engine → Agent state: loads/saves · Engine checkpoints workflow progress in durable state.
- Agent engine → Store protocol: uses · Engine depends on the storage protocol, not a concrete backend.
- Agent engine → Distributed lock: coordinates · Workers acquire and renew locks before advancing steps.
- Agent engine → Research flow: runs · Engine invokes named workflow steps.
- Research flow → LLM boundary: calls · Workflow reaches the external model boundary.
- Distributed lock → Redis store: Redis primitives · Locking and fencing are implemented with Redis.
- Store protocol → Memory store: backend · One concrete store implementation.
- Store protocol → Redis store: backend · One concrete store implementation.
- Store protocol → Postgres store: backend · One concrete store implementation.
- Store protocol → SQLite store: backend · One concrete store implementation.
- Redis store → Agent state: persists · Store reads and writes checkpointed agent state.
- Postgres store → Agent state: persists · Store reads and writes checkpointed agent state.
- SQLite store → Agent state: persists · Store reads and writes checkpointed agent state.
- Memory store → Agent state: persists · Store reads and writes checkpointed agent state.
- Research demo → Agent engine: exercises · Normal demo runs the Python engine through the research workflow.
- Crash demo → Agent engine: exercises · Fault-injection demo validates restart-safe progress.
- Benchmarks → Store protocol: measures · Benchmarks compare store tradeoffs and resume cost.
- TS runner → TS store: uses · Prototype runner depends on the prototype store abstraction.
- TS runner → TS LLM: calls · Prototype workflow uses a model boundary.
- TS runner → TS research: runs · Prototype runner executes the sample workflow.
- TS store → TS Redis: backed by · Prototype storage uses Redis utilities.
