How adityapainuli/stateful-agents works
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: base.py Store protocol · engine.py Agent engine · state.py Agent state · agent.runner.ts TS runner
Components 18
Python runtime
Primary async agent runtime and its operational entrypoints.
- Agent engine · Main step loop: load state, run handler, save checkpoint, advance.
python/stateful_agents/engine.py - Agent state · Durable workflow state carrying identity, step, payload, and fencing token.
python/stateful_agents/state.py
Coordination
Locking and fencing for concurrent workers.
- Distributed 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 · Common save/load contract with fencing enforcement at the storage boundary.
python/stateful_agents/stores/base.py - Memory store · In-memory baseline implementation of the state store protocol.
python/stateful_agents/stores/memory_store.py - Redis store · Durable state backend using Redis.
python/stateful_agents/stores/redis_store.py - Postgres store · Durable state backend using Postgres.
python/stateful_agents/stores/postgres_store.py - SQLite store · Durable state backend using SQLite.
python/stateful_agents/stores/sqlite_store.py
Workflow logic
Application step logic and external model boundary.
- Research flow · Named workflow steps with resumable chunks and state transitions.
python/stateful_agents/workflows/research.py - LLM boundary · 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 · Normal execution path for the sample workflow.
python/demos/run_research.py - Crash demo · Kills a worker mid-run to validate resume from checkpoints.
python/demos/crash_and_resume.py - Benchmarks · 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 · Original TypeScript agent runner kept as a reference implementation.
engine/src/agent.runner.ts - TS store · TypeScript state store abstraction mirroring the Python persistence boundary.
engine/src/stores/state.store.ts - TS LLM · TypeScript model-call boundary used by the prototype workflow.
engine/src/llm.ts - TS Redis · Redis helper utilities for the prototype runtime.
engine/src/utils/redis.ts - TS research · Prototype research workflow mirroring the Python sample flow.
engine/src/workflows/research.ts
Connections 21
- 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.