Skip to content
dyohnPublic

About

Inspired by the modern classic "Designing Data-Intensive Applications" by Martin Kleppmann, this repository implements a simple experimental database for exploration, testing, and knowledge acquisition.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Rainman

A three-node, leader-based, replicated key-value store built from scratch in Python and deployed via Docker. Rainman demonstrates the core concepts from Designing Data-Intensive Applications (Kleppmann) — write-ahead logging, single-leader replication, crash recovery, and leader election — and explores LLM-driven agentic processes as a fault management mechanism.

Two hybrid AI agents run alongside the cluster: an Adversary Fault Injector that uses an LLM to choose and time fault injections (kill, pause, partition, WAL corruption), and a Consistency Observer that monitors cluster health and produces natural-language narrations of anomalies. Correctness is evaluated against a pre-computed oracle derived from the Yelp Open Dataset.


Architecture

 ┌──────────────────────────────────────────────────────────────┐
 │  Docker network: rainman_net                                 │
 │                                                              │
 │  ┌──────────┐  replicate   ┌──────────┐                      │
 │  │  node1   │ ───────────▶ │  node2   │                      │
 │  │ (leader) │              └──────────┘                      │
 │  └──────────┘ ───────────▶ ┌──────────┐                      │
 │                  replicate │  node3   │                      │
 │                             └──────────┘                     │
 │   heartbeats every 200 ms ──────────────────────────────▶    │
 └──────────────────────────────────────────────────────────────┘
          ▲ /health polls              ▲ docker commands
          │                            │
 ┌────────┴──────────────┐   ┌─────────┴────────────────────┐
 │  ConsistencyObserver  │   │     AdversaryAgent           │
 │  (host process)       │   │     (host process)           │
 └───────────────────────┘   └──────────────────────────────┘

Each node is a FastAPI application backed by an append-only WAL and an in-memory dict. The leader assigns LSNs, writes to its own WAL, fans out to both followers concurrently, and confirms the write to the client only after a majority (2 of 3) have persisted it. Leader election is driven by randomised heartbeat timeouts (600–1000 ms) and a majority vote protocol.


Prerequisites

Requirement Version Notes
Docker Desktop 27+ Provides docker compose
Python 3.13+ Must match requires-python in pyproject.toml
Ollama any Required for LLM narration; agents degrade gracefully without it
llama3.2 model — ollama pull llama3.2

To check your versions:

docker --version
python3 --version
ollama --version

Setup

git clone <repo-url> rainman
cd rainman

# Create the virtual environment and install the package in editable mode.
./devSetup.sh
source venv/bin/activate

devSetup.sh creates venv/, installs all runtime and dev dependencies, and runs pip install -e . so the rainman package is importable from any directory inside the repo.


Running the Demo

1. Start the cluster

docker compose up --build -d

Three containers start on rainman_net. Each one replays its WAL on startup and begins the election countdown. The first leader is usually elected within 2 seconds.

Confirm a leader has emerged:

curl -s http://localhost:8001/health | python3 -m json.tool
curl -s http://localhost:8002/health | python3 -m json.tool
curl -s http://localhost:8003/health | python3 -m json.tool

One node should show "role": "leader"; the others should show "role": "follower" with a matching "leader_id".

2. Prepare a dataset

Option A — Yelp Open Dataset (recommended for a realistic workload):

Download the dataset from the Yelp Dataset page (free for academic use) and place yelp_academic_dataset_business.json and yelp_academic_dataset_review.json in data/raw/. Then:

python scripts/sample_data.py --businesses 1000 --reviews 5000

Option B — Synthetic data (no download required):

python scripts/generate_synthetic.py

This produces structurally equivalent files in data/sample/.

3. Build the correctness oracle

python scripts/build_oracle.py

Writes data/expected_state.json — the ground-truth final state that verify_cluster.py checks the cluster against.

4. Run the end-to-end demo

python run_demo.py

The demo orchestrates nine steps automatically:

  1. Preflight — verifies the cluster is up and a leader has been elected
  2. Oracle — builds expected_state.json if absent
  3. Bulk load — streams businesses.jsonl into the leader
  4. Observer start — launches ConsistencyObserver as a subprocess
  5. Adversary start — launches AdversaryAgent as a subprocess
  6. Review stream — streams reviews.jsonl into the leader; redirects on 409 (leader changed), retries on 503 (majority ack failed)
  7. Convergence — polls /health until all live nodes agree on LSN
  8. Verify — runs scripts/verify_cluster.py and prints the result
  9. Shutdown — terminates both agent subprocesses

Expected duration: several minutes, depending on dataset size and how aggressively the adversary acts.

Watch the agents in separate terminals while the demo runs:

# Terminal 2 — adversary decisions
tail -f logs/adversary_agent.log

# Terminal 3 — observer narrations
tail -f logs/observer.log

Manual Cluster Commands

# Stop one node (clean exit — stays down until you start it again)
docker compose stop node1

# Start a stopped node (replays WAL on startup)
docker compose start node1

# Hard-kill a node (simulates crash)
docker compose kill node2

# Restart a node
docker compose restart node3

# Check all containers
docker compose ps

# Tear down and wipe WAL state for a clean run
docker compose down
rm -rf data/node1 data/node2 data/node3

Direct key-value operations (replace $PORT with 8001, 8002, or 8003):

# Write a key (must target the leader)
curl -X PUT http://localhost:$PORT/kv/my_key \
  -H "Content-Type: application/json" \
  -d '{"value": {"hello": "world"}}'

# Read a key (any node)
curl http://localhost:$PORT/kv/my_key

# Check node health
curl http://localhost:$PORT/health

Running the Agents Manually

For development and debugging, run each component in its own terminal:

# Terminal 1 — cluster
docker compose up --build

# Terminal 2 — observer
source venv/bin/activate
python -m rainman.agents.recovery_agent \
    --config config/adversary_config.json \
    --cluster config/cluster.json

# Terminal 3 — adversary
source venv/bin/activate
python -m rainman.agents.adversary_agent \
    --config config/adversary_config.json \
    --cluster config/cluster.json \
    --project-dir .

Both agents read host_port from cluster.json to reach nodes at http://localhost:{host_port} and require no Docker networking knowledge.


Scripts Reference

Script Purpose
scripts/sample_data.py Reservoir-sample N businesses and M reviews from the Yelp raw files
scripts/generate_synthetic.py Generate a structurally equivalent synthetic dataset (no Yelp download needed)
scripts/build_oracle.py Pre-compute data/expected_state.json — the correctness ground truth
scripts/verify_cluster.py Diff live cluster state against the oracle; report mismatches
scripts/load_businesses.py Bulk-load data/sample/businesses.jsonl into the leader
scripts/load_reviews.py Stream data/sample/reviews.jsonl into the leader

Tests and Lint

# Run the full test suite
./runTests.sh
# or directly:
pytest tests/ -v

# Lint
ruff check src/

# Format
ruff format src/

The test suite covers storage, replication, election, and agent logic. All tests run against real filesystems and in-memory state with no HTTP or Docker calls (those boundaries are mocked at the function level).


Connection to DDIA

Component Chapter
WAL + in-memory hash index Ch. 3 — Storage and Retrieval
Single-leader replication, majority ack Ch. 5 — Replication
Leader election and failover Ch. 5 — Replication
Network partitions and split-brain Ch. 8 — The Trouble with Distributed Systems
Recovery and convergence after failure Ch. 9 — Consistency and Consensus
Replication log as ordered event stream Ch. 11 — Stream Processing
Observability and anomaly detection Ch. 1 — Reliable, Scalable, Maintainable

Repository Layout

/
├── CLAUDE.md                        ← project context and coding standards
├── docker-compose.yml               ← three-node cluster definition
├── Dockerfile                       ← single image used by all nodes
├── pyproject.toml                   ← hatchling build config, ruff config
├── devSetup.sh                      ← venv creation + editable install
├── runTests.sh                      ← pytest wrapper
├── run_demo.py                      ← end-to-end demo orchestrator
├── docs/
│   ├── project-description.md      ← full architecture and build plan
│   └── demo-run.md                 ← annotated demo run transcript
├── src/
│   └── rainman/
│       ├── node/
│       │   ├── main.py              ← FastAPI node application
│       │   ├── storage.py           ← WAL + dict storage engine
│       │   ├── replication.py       ← leader fanout, follower apply
│       │   └── election.py          ← heartbeat, timeout, vote logic
│       └── agents/
│           ├── recovery_agent.py    ← Consistency Observer
│           └── adversary_agent.py   ← LLM-driven fault injector
├── scripts/
│   ├── sample_data.py
│   ├── generate_synthetic.py
│   ├── build_oracle.py
│   ├── verify_cluster.py
│   ├── load_businesses.py
│   └── load_reviews.py
├── config/
│   ├── cluster.json                 ← node hostnames, ports, priority order
│   └── adversary_config.json        ← fault catalog + Ollama model config
├── data/
│   ├── raw/                         ← Yelp JSON files (gitignored)
│   ├── sample/                      ← sampled working datasets (gitignored)
│   └── expected_state.json          ← correctness oracle output
├── logs/                            ← runtime logs (gitignored)
└── tests/
    ├── test_storage.py
    ├── test_replication.py
    ├── test_election.py
    └── test_agents.py

License

MIT

About

Inspired by the modern classic "Designing Data-Intensive Applications" by Martin Kleppmann, this repository implements a simple experimental database for exploration, testing, and knowledge acquisition.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages