Skip to content
ahnaf-labPublic

About

A terminal TUI simulating Raft leader election and log replication across deterministic virtual nodes, where you partition, crash or slow down nodes with keypresses and watch the cluster heal itself…

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

raftlab

A terminal TUI simulating Raft leader election and log replication across deterministic virtual nodes. Partition, crash, or slow down nodes with keypresses and watch the cluster heal itself live in ASCII.

This milestone adds a scenario recorder: a fixed --size/--seed/ --ticks/--fault/--propose run can be bundled into a Scenario, run once to capture every tick's rendered frame as a Transcript, saved to disk as a golden-transcript JSON file with --record, and replayed later with --replay -- which reruns that same scenario fresh and fails loudly if any tick's frame no longer matches what was recorded. That turns "does the cluster still behave the same way" into a plain equality check, usable both as a regression test (a scenario and its golden transcript checked into the repo) and as a canned demo (replay a known-interesting fault sequence without re-typing its flags). This builds on the replication view (client commands proposed to the leader, replicated to peers, and committed by quorum, rendered as C/u log tokens), fault injection (a deterministic, tick-keyed schedule of crash/recover/partition/heal/ slow/unslow actions that Simulation.step() applies before each round), the cluster view (per-tick ASCII render), and the Raft core (term, vote, log state machine) from the previous milestones. Faults are bound to the same five single-character keys (c/r/p/h/s/u) an interactive TUI would read live from the keyboard; today they're driven by the scripted --fault TICK:KEY[:ARG] and --propose TICK:COMMAND flags a Scenario bundles up. There is still no real networking, timers, or interactive keypress loop -- a Simulation just steps the cluster forward one deterministic round at a time.

  • raftlab/types.py -- the RPC payloads and roles from the Raft paper (RequestVote, AppendEntries, LogEntry, Role).
  • raftlab/node.py -- a single node's state machine: term/vote bookkeeping, the election-restriction log comparison, log matching/truncation on AppendEntries, restart() (a crashed node loses its volatile role and commit state but keeps its persisted term/vote/log, per the paper), and recompute_commit_index() (leader-only: advances commit_index to the highest entry a quorum has replicated, restricted by the paper's section 5.4.2 rule against committing an earlier-term entry by replica count alone).
  • raftlab/election.py -- a deterministic driver that runs a candidate's vote request against a fixed set of peers in a fixed order, optionally recording each RPC hop as an event.
  • raftlab/cluster.py -- builds a seeded N-node cluster for simulation and tests, and holds its fault state: which nodes are crashed, the current partition (a list of disjoint node groups; RPCs only cross within a group), and which nodes are marked slow.
  • raftlab/faults.py -- the five fault actions (Fault/FaultKind), a FaultSchedule mapping tick -> faults to apply, the keypress-to-fault binding (KEY_ACTIONS, fault_from_keypress), and the --fault flag's TICK:KEY[:ARG] spec parser.
  • raftlab/events.py -- frozen records of one tick's RPC hops (vote requested/granted/rejected, heartbeat/AppendEntries sent/acked, a command proposed to or committed by the leader, a dropped proposal or message, a fault taking effect, or the leader-elected transition).
  • raftlab/proposals.py -- a Proposal/ProposalSchedule pairing, mapping tick -> client commands to hand to the current leader, and the --propose flag's TICK:COMMAND spec parser.
  • raftlab/simulation.py -- Simulation.step() applies any faults due this tick, then any proposed commands, then runs an election round while there is no leader or a replication round once there is one. The leader's AppendEntries now carries whatever log entries a peer is still missing (empty once caught up, i.e. a plain heartbeat) and, after replies are in, the leader advances its own commit index once a quorum has an entry. A crashed or partitioned-off peer's RPC is never delivered (MessageDropped, reason crashed/partitioned); a slow peer's RPC is delivered but its reply is lost every second time it's addressed (reason slow) -- a simple, deterministic stand-in for an overloaded link that avoids an asynchronous multi-tick message queue.
  • raftlab/render.py -- turns a cluster's state and a tick's events into an ASCII frame: one line per node (including CRASHED/(slow) status, the current partition groups, and each node's log as C<term>/u<term> tokens for committed/uncommitted entries), followed by one arrow per event.
  • raftlab/cli.py -- raftlab command: builds a Scenario from --size/--seed/--ticks/repeated --fault/--propose flags, runs it, and prints rendered frames tick by tick; --record PATH additionally saves the run as a golden transcript, and --replay PATH reruns the scenario saved in an existing transcript and reports whether every tick still matches.
  • raftlab/scenario.py -- Scenario (the JSON-serializable inputs to one run: size, seed, ticks, and --fault/--propose spec strings), Transcript (a scenario plus the exact rendered frame from every tick, with save/load and a tick-by-tick diff), and run_scenario which runs a scenario end to end and returns its transcript.

Install

Requires Python 3.9+. No third-party dependencies -- everything is built on the standard library.

pip install -e .

Usage

Render a seeded cluster tick by tick from the command line:

raftlab --size 5 --seed 42 --ticks 6

or, without installing the console script:

python -m raftlab --size 5 --seed 42 --ticks 6

Each tick prints every node's role/term/commit state and log (as C<term>/u<term> tokens for committed/uncommitted entries), then the vote or heartbeat arrows exchanged that tick:

-- tick 1 --
[node-0] FOLLOWER  term=1   commit=0   votedFor=node-1   log=[]
[node-1] LEADER    term=1   commit=0   votedFor=node-1   log=[]
[node-2] FOLLOWER  term=1   commit=0   votedFor=node-1   log=[]
[node-3] FOLLOWER  term=0   commit=0   votedFor=-        log=[]
[node-4] FOLLOWER  term=0   commit=0   votedFor=-        log=[]

  node-1 --RequestVote(term=1)--> node-0
  node-0 --VoteGranted(term=1)--> node-1
  node-1 --RequestVote(term=1)--> node-2
  node-2 --VoteGranted(term=1)--> node-1
  *** node-1 elected leader for term 1 ***

Schedule faults with repeated --fault TICK:KEY[:ARG] flags -- crash, recover, slow, unslow (each take a node id), heal (no arg), and partition (pipe-separated, comma-separated node groups):

raftlab --size 5 --seed 2 --ticks 5 --fault 2:c:node-2
-- tick 2 --
[node-0] FOLLOWER  term=2   commit=0   votedFor=node-1   log=[]
[node-1] LEADER    term=2   commit=0   votedFor=node-1   log=[]
[node-2] CRASHED   term=1   commit=0   votedFor=node-2   log=[]
[node-3] FOLLOWER  term=2   commit=0   votedFor=node-1   log=[]
[node-4] FOLLOWER  term=0   commit=0   votedFor=-        log=[]

  !!! fault: crash node-2 !!!
  node-1 --RequestVote(term=2)--> node-0
  node-0 --VoteGranted(term=2)--> node-1
  node-1 -x-> node-2 (crashed)
  node-1 --RequestVote(term=2)--> node-3
  node-3 --VoteGranted(term=2)--> node-1
  *** node-1 elected leader for term 2 ***

The crashed node (node-2, the previous leader) is skipped entirely, the remaining nodes re-elect a new leader (node-1) once it stops hearing heartbeats, and the cluster heals -- all from a deterministic, scripted fault schedule rather than live keypresses.

Schedule client commands with repeated --propose TICK:COMMAND flags; each is handed to whichever node is leader at the start of that tick and replicated on the next AppendEntries round:

raftlab --size 3 --seed 2 --ticks 3 --propose "2:set x=1"
-- tick 2 --
[node-0] FOLLOWER  term=1   commit=0   votedFor=node-2   log=[u1]
[node-1] FOLLOWER  term=1   commit=0   votedFor=-        log=[u1]
[node-2] LEADER    term=1   commit=1   votedFor=node-2   log=[C1]

  client --propose(term=1, index=1)--> node-2
  node-2 --AppendEntries(term=1, entries=1)--> node-0
  node-0 --Ack--> node-2
  node-2 --AppendEntries(term=1, entries=1)--> node-1
  node-1 --Ack--> node-2
  *** node-2 committed index 1 ***

The leader (node-2) appends the command and -- once it has heard back from a quorum -- marks index 1 committed (C1) that same tick. The followers have already replicated it (u1, replicated but not yet known to be committed) and only learn it's committed on the next round, once the leader's commit index reaches them via leader_commit -- the one-round-trip commit lag real Raft also has.

Or drive it programmatically:

from raftlab import Cluster, FaultSchedule, ProposalSchedule, Simulation, render_cluster

cluster = Cluster(size=5, seed=42)
schedule = FaultSchedule()
schedule.crash(3, "node-1")
schedule.recover(6, "node-1")
proposals = ProposalSchedule()
proposals.add(2, "set x=1")
simulation = Simulation(cluster, schedule=schedule, proposals=proposals)

events = simulation.step()
print(render_cluster(cluster, events=events, tick=simulation.tick))

Record a fixed fault/propose sequence as a golden transcript, then replay it later and check it still behaves the same way. --record writes the transcript (the scenario plus every tick's rendered frame); --replay reads a transcript, so it's the file --record just produced, not the plain scenario file:

raftlab --size 5 --seed 2 --ticks 10 --fault 3:c:node-2 --fault 7:r:node-2 \
    --propose "2:set x=1" --record /tmp/crash_and_recover.transcript.json
raftlab --replay /tmp/crash_and_recover.transcript.json
replay OK: 10 tick(s) matched the recorded transcript at '/tmp/crash_and_recover.transcript.json'

If the simulation's behavior ever changes, --replay prints exactly which ticks drifted and exits with a non-zero status instead:

replay FAILED against '/tmp/crash_and_recover.transcript.json':
  - tick 3 frame differs from the recorded transcript

scenarios/crash_and_recover.json is a plain scenario (just the size/seed/ticks/fault/propose settings, no frames) checked into this repo, and tests/golden/crash_and_recover.json is the matching golden transcript test_scenario.py loads, reruns, and diffs on every test run -- the same mechanism available programmatically as raftlab.Scenario, raftlab.Transcript, and raftlab.run_scenario.

Run the test suite:

python -m pytest

Status

Built autonomously, one milestone at a time. Each milestone only ships once its test suite passes; this one adds a scenario recorder -- a fixed --size/--seed/--ticks/--fault/--propose run can be saved as a Scenario, captured tick by tick as a Transcript, written to disk with --record, and checked against a fresh run with --replay, giving golden- transcript regression tests and reproducible demos -- on top of the replication view (client commands proposed to the leader, replicated to peers, and committed by quorum), fault injection (a deterministic crash/recover/partition/heal/slow/unslow schedule), the ASCII cluster view, and the Raft state machine core from earlier milestones. There is still no live interactive TUI or real networking/timers.

About

A terminal TUI simulating Raft leader election and log replication across deterministic virtual nodes, where you partition, crash or slow down nodes with keypresses and watch the cluster heal itself…

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages