public snapshot · areas/examples/raft-nib/ · system@main · commit da2bf624f03d · shared 2026-11-23T17:23:12Z· frozen: this page does not change when the repository does
1-- Raft: leader election and log replication, every node a fibre on the 2-- simulated network (`docs/language/world.md`). 3-- 4-- Each node listens on its own address, dials every peer for its outbound 5-- messages, and reads each peer's inbound connection in a fibre of its own. 6-- Every reader, and a timer, sends into the node's one mailbox (a channel), and 7-- the node's main loop takes one event at a time from it: a peer's message or a 8-- tick. That loop is the whole of Raft's logic, and it never waits on anything 9-- but its mailbox. 10-- 11-- What a model needs to see is effects, so the program's state is where a real 12-- implementation keeps it: 13-- 14-- `Store` the persistent state — current term, vote, log — which Raft 15-- requires to survive a crash. Every write is a journalled 16-- operation, before the message it justifies is sent. 17-- `Machine` the state machine a committed entry is applied to, once, in 18-- index order. 19-- messages JSON, so a model reads `term`, `kind` and `entries` out of what 20-- one node sent another. 21use"std/net.nib" 22use"std/time.nib" 23use"std/random.nib" 24use"std/io.nib" 25 26dataEntrywhere 27term::Int; 28cmd::String 29 30-- One record shape for every message: the kind says which fields mean 31-- something, and a model reads them all the same way. 32dataMsgwhere 33kind::String; 34term::Int; 35from::String; 36last_index::Int; 37last_term::Int; 38granted::Bool; 39prev_index::Int; 40prev_term::Int; 41entries::Vec<Entry>; 42commit::Int; 43success::Bool; 44match_index::Int 45 46dataEvwhereTick;Got(Msg) 47 48-- A node's volatile state. `term`, `voted` and `log` are copies of what 49-- `Store` holds, kept beside the rest so one value is the node's whole view. 50dataNodewhere 51me::String; 52peers::Vec<String>; 53role::String; 54term::Int; 55voted::String; 56log::Vec<Entry>; 57commit::Int; 58applied::Int; 59votes::Vec<String>; 60next::Map<String,Int>; 61matched::Map<String,Int>; 62deadline::Int; 63beat::Int; 64links::Map<String,Handle> 65 66-- What `Store` gives back to a node that starts: everything it saved. 67dataSavedwhere 68term::Int; 69voted::String; 70log::Vec<Entry> 71 72interfaceStorewhere 73recover(node:String)->Saved; 74save(node:String,term:Int,voted:String)->(); 75append(node:String,keep:Int,entries:Vec<Entry>)->() 76 77-- Two rules this program can be built without, so a check of each has a 78-- known-wrong program to refuse. A node grants at most one vote per term 79-- (`one_vote`), and only to a candidate whose log is at least as up to date as 80-- its own (`check_log`). `Main` binds both as Raft states them; `Mutant` 81-- votes for every candidate that asks; `Careless` ignores the candidate's log. 82interfaceRuleswhere 83one_vote()->Bool; 84check_log()->Bool 85 86effectorStrictisRuleswhere 87one_vote()=true 88check_log()=true 89 90effectorLaxisRuleswhere 91one_vote()=false 92check_log()=true 93 94effectorBlindisRuleswhere 95one_vote()=true 96check_log()=false 97 98interfaceMachinewhere 99apply(node:String,index:Int,cmd:String)->();100applied(node:String)->Vec<String>101102-- An effector's cells outlive the node's fibres, so a crash loses none of103-- what `Disk` holds: a node that starts again recovers it.104effectorDiskisStorewhere105 unkeyed varterms::Map<String,Int>={};106 unkeyed varvotes::Map<String,String>={};107 unkeyed varlogs::Map<String,Vec<Entry>>={};108recover(node)=109Saved{term:Map.get_or(terms,node,0),voted:Map.get_or(votes,node,""),110log:Map.get_or(logs,node,#[])}111save(node,term,voted)=112terms:=Map.set(terms,node,term);votes:=Map.set(votes,node,voted);()113append(node,keep,entries)=114logs:=Map.set(logs,node,Vec.append(Vec.take(Map.get_or(logs,node,#[]),keep),entries));()115116-- A store that writes as `Disk` does but recovers nothing, as a node that117-- never syncs its writes would: after a crash it has forgotten its term and118-- its vote. `Forgetful` binds it, so a check of durability has a program to119-- refuse.120effectorRamisStorewhere121 unkeyed varlogs::Map<String,Vec<Entry>>={};122recover(node)=Saved{term:0,voted:"",log:#[]}123save(node,term,voted)=()124append(node,keep,entries)=125logs:=Map.set(logs,node,Vec.append(Vec.take(Map.get_or(logs,node,#[]),keep),entries));()126127-- A node that starts again applies its log from the first entry, so applying128-- an index the machine already has changes nothing.129effectorKvisMachinewhere130 unkeyed vardone::Map<String,Vec<String>>={};131apply(node,index,cmd)=132lethad=Map.get_or(done,node,#[]);133ifindex==Vec.size(had)+1then(done:=Map.set(done,node,Vec.push(had,cmd));())134else()135applied(node)=Map.get_or(done,node,#[])136137moduleRaftwhere138-- ---- the cluster ------------------------------------------------------139funcport::->Int=7000140funchosts::->Vec<String>=#["10.0.0.1","10.0.0.2","10.0.0.3"]141funcheartbeat_ms::->Int=50142funcmax_log::->Int=6143funcrun_ms::->Int=3000144functick_ms::->Int=10145146funcothers::me:String->Vec<String>=147Vec.filter(hosts()){h->h!=me}148149funcmajority::->Int=Vec.size(hosts())/2+1150151-- ---- reading a message ------------------------------------------------152funcentries_of::items,acc:Vec<Entry>->Vec<Entry>raisesErr.MissingField,Err.NotAnObject,Err.WrongType=153match(items)154[e, ...rest]=>entries_of(rest,Vec.push(acc,Entry{term:Json.int(e,"term"),cmd:Json.string(e,"cmd")}))155[]=>acc156end157158-- A message from a peer is input: a field of the wrong shape is a159-- `WrongType` the reader drops, as it drops a message that is not JSON.160funcdecode::text:String->MsgraisesErr.InvalidJson,Err.MissingField,Err.NotAnObject,Err.NotAList,Err.WrongType=161letdoc=Json.parse(text);162Msg{kind:Json.string(doc,"kind"),term:Json.int(doc,"term"),163from:Json.string(doc,"from"),164last_index:Json.int(doc,"last_index"),last_term:Json.int(doc,"last_term"),165granted:Json.bool(doc,"granted"),prev_index:Json.int(doc,"prev_index"),166prev_term:Json.int(doc,"prev_term"),167entries:entries_of(Json.items(Json.field(doc,"entries")),#[]),168commit:Json.int(doc,"commit"),success:Json.bool(doc,"success"),169match_index:Json.int(doc,"match_index")}170171-- ---- messages -----------------------------------------------------------172funcblank::kind:String,term:Int,from:String->Msg=173Msg{kind:kind,term:term,from:from,last_index:0,last_term:0,granted:false,174prev_index:0,prev_term:0,entries:#[],commit:0,success:false,match_index:0}175176funcvote_req::n:Node->Msg=177#{blank("vote_req",n.term,n.me)withlast_index:Vec.size(n.log),last_term:last_term(n.log)}178179funcvote::n:Node,granted:Bool->Msg=180#{blank("vote",n.term,n.me)withgranted:granted}181182funcappend_req::n:Node,peer:String->Msg=183letprev=Map.get_or(n.next,peer,1)-1;184#{blank("append",n.term,n.me)withprev_index:prev,prev_term:term_at(n.log,prev),185entries:Vec.drop(n.log,prev),commit:n.commit}186187funcappend_reply::n:Node,ok:Bool,upto:Int->Msg=188#{blank("append_ok",n.term,n.me)withsuccess:ok,match_index:upto}189190-- ---- the log -------------------------------------------------------------191-- Index `i` is the log's `i`th entry, from 1; index 0 is before the log and192-- has term 0.193functerm_at::log:Vec<Entry>,i:Int->Int=194ifi<=0||i>Vec.size(log)then0195elsetryVec.get(log,i-1).termrescueErr.IndexOutOfRange(_)=>0end196197funclast_term::log:Vec<Entry>->Int=term_at(log,Vec.size(log))198199-- The log after an `append` at `prev`: entries that agree with what is there200-- are kept, and the first that disagrees cuts the rest. An empty `append` (a201-- heartbeat) cuts nothing, which is Raft's rule and the easy one to break.202funcmerge::log:Vec<Entry>,at:Int,incoming:Vec<Entry>->Vec<Entry>=203ifVec.size(incoming)==0thenlog204else205lethead=tryVec.get(incoming,0)rescueErr.IndexOutOfRange(_)=>Entry{term:0,cmd:""}end;206ifat<Vec.size(log)&&term_at(log,at+1)==head.termthen207merge(log,at+1,Vec.drop(incoming,1))208else209Vec.append(Vec.take(log,at),incoming)210211-- ---- talking to peers ----------------------------------------------------212-- A lost message is Raft's ordinary case, so a send that fails is dropped.213-- A connection that has closed (its peer crashed) is dialled again, once,214-- on the next send to that peer, and a peer that does not answer is left215-- without a link until a later send finds it back.216funcdeliver::conn:Handle,text:String->Bool!Net.Socket=217try(let _ =@Net.Socket.send(conn,Bytes.from_string(text));true)218rescueErr.Closed(_)=>false219rescueHandleRefused(_)=>false220end221222funcredial::n:Node,peer:String->Node!Net.Socket=223try#{nwithlinks:Map.set(n.links,peer,@Net.Socket.connect(peer,port()))}224rescueErr.ConnectFailed(_)=>#{nwithlinks:Map.remove(n.links,peer)}225rescueErr.BindFailed(_)=>#{nwithlinks:Map.remove(n.links,peer)}226end227228funcsend::n:Node,peer:String,m:Msg->Node!Net.Socket=229lettext=tryJson.render(m)rescueErr.Unrenderable(_)=>""end;230letlinked=Map.has(n.links,peer);231letok=text!=""&&linked232&&(trydeliver(Map.get(n.links,peer),text)rescueErr.MissingField(_, _)=>falseend);233ifok||text==""thenn234else235letr=redial(n,peer);236let _ =ifMap.has(r.links,peer)237then(trydeliver(Map.get(r.links,peer),text)rescueErr.MissingField(_, _)=>falseend)238elsefalse;239r240241funcbroadcast::n:Node,m:Msg->Node!Net.Socket=242Vec.fold(n.peers,n,{acc,p->send(acc,p,m)})243244funcreplicate::n:Node->Node!Net.Socket=245Vec.fold(n.peers,n,{acc,p->send(acc,p,append_req(acc,p))})246247-- ---- the rules -------------------------------------------------------------248funcelection_timeout::->Int!Random.Source=249150+(try@Random.Source.next_int(150)rescueErr.OutOfRange(_)=>0end)250251-- A term newer than ours, from anyone, makes us a follower of it.252funcobserve::n:Node,term:Int->Node!Store=253ifterm>n.termthen254let _ =@Store.save(n.me,term,"");255#{nwithrole:"follower",term:term,voted:"",votes:#[]}256elsen257258funcstart_election::n:Node,now:Int->Node!Store,Net.Socket,Random.Source=259letterm=n.term+1;260let _ =@Store.save(n.me,term,n.me);261letc=#{nwithrole:"candidate",term:term,voted:n.me,votes:#[n.me],deadline:now+election_timeout()};262broadcast(c,vote_req(c))263264funcbecome_leader::n:Node,now:Int->Node!Net.Socket=265letnext=Vec.fold(n.peers,{},{m,p->Map.set(m,p,Vec.size(n.log)+1)});266letmatched=Vec.fold(n.peers,{},{m,p->Map.set(m,p,0)});267replicate(#{nwithrole:"leader",next:next,matched:matched,beat:now+heartbeat_ms()})268269funcup_to_date::n:Node,m:Msg->Bool=270letmine=last_term(n.log);271m.last_term>mine||(m.last_term==mine&&m.last_index>=Vec.size(n.log))272273funcon_vote_req::n:Node,m:Msg,now:Int->Node!Store,Net.Socket,Random.Source,Rules=274letfree=n.voted==""||n.voted==m.from||!@Rules.one_vote();275letfresh=up_to_date(n,m)||!@Rules.check_log();276letgrant=m.term==n.term&&free&&fresh;277ifgrantthen278let _ =@Store.save(n.me,n.term,m.from);279letg=#{nwithvoted:m.from,deadline:now+election_timeout()};280send(g,m.from,vote(g,true))281elsesend(n,m.from,vote(n,false))282283funcon_vote::n:Node,m:Msg,now:Int->Node!Net.Socket=284ifn.role=="candidate"&&m.term==n.term&&m.granted285&&Vec.find_index(n.votes){v->v==m.from}<0then286letvotes=Vec.push(n.votes,m.from);287letc=#{nwithvotes:votes};288ifVec.size(votes)>=majority()thenbecome_leader(c,now)elsec289elsen290291funcon_append::n:Node,m:Msg,now:Int->Node!Store,Net.Socket,Random.Source=292ifm.term<n.termthensend(n,m.from,append_reply(n,false,0))293else294letf=#{nwithrole:"follower",deadline:now+election_timeout()};295ifm.prev_index>Vec.size(f.log)||term_at(f.log,m.prev_index)!=m.prev_termthen296send(f,m.from,append_reply(f,false,0))297else298letlog=merge(f.log,m.prev_index,m.entries);299let _ =ifVec.size(m.entries)>0then@Store.append(f.me,Vec.size(log)-Vec.size(Vec.drop(log,m.prev_index)),Vec.drop(log,m.prev_index))else();300letupto=m.prev_index+Vec.size(m.entries);301letg=#{fwithlog:log};302leth=ifm.commit>g.committhen#{gwithcommit:ifm.commit<uptothenm.commitelseupto}elseg;303send(h,m.from,append_reply(h,true,upto))304305-- The largest index a majority holds in the leader's own term, if it is past306-- the commit point.307funccommit_from::n:Node,i:Int->Int=308ifi<=n.committhenn.commit309else310letholders=1+Vec.size(Vec.filter(n.peers){p->Map.get_or(n.matched,p,0)>=i});311ifholders>=majority()&&term_at(n.log,i)==n.termtheni312elsecommit_from(n,i-1)313314funcon_append_ok::n:Node,m:Msg->Node!Net.Socket=315ifn.role!="leader"||m.term!=n.termthenn316elseifm.successthen317lethad=Map.get_or(n.matched,m.from,0);318letupto=ifm.match_index>hadthenm.match_indexelsehad;319letp=#{nwithnext:Map.set(n.next,m.from,upto+1),matched:Map.set(n.matched,m.from,upto)};320#{pwithcommit:commit_from(p,Vec.size(p.log))}321else322letback=Map.get_or(n.next,m.from,1)-1;323letp=#{nwithnext:Map.set(n.next,m.from,ifback<1then1elseback)};324send(p,m.from,append_req(p,m.from))325326-- Every committed entry not yet applied, in index order, once.327funcapply_committed::n:Node->Node!Machine=328ifn.applied>=n.committhenn329else330leti=n.applied+1;331letcmd=tryVec.get(n.log,i-1).cmdrescueErr.IndexOutOfRange(_)=>""end;332let _ =@Machine.apply(n.me,i,cmd);333apply_committed(#{nwithapplied:i})334335-- A leader proposes the next command on each heartbeat, until its log is full.336funcpropose::n:Node->Node!Store=337ifVec.size(n.log)>=max_log()thenn338else339lete=Entry{term:n.term,cmd:"{n.me}/t{n.term}/{Vec.size(n.log)+1}"};340let _ =@Store.append(n.me,Vec.size(n.log),#[e]);341#{nwithlog:Vec.push(n.log,e)}342343funcon_tick::n:Node,now:Int->Node!Store,Net.Socket,Random.Source=344ifn.role=="leader"then345ifnow>=n.beatthen346letp=replicate(propose(n));347#{pwithbeat:now+heartbeat_ms()}348elsen349elseifnow>=n.deadlinethenstart_election(n,now)350elsen351352funchandle::n:Node,ev:Ev,now:Int->Node!Store,Net.Socket,Random.Source,Machine,Rules=353letnext=354matchev355Tick=>on_tick(n,now)356Got(m)=>357leto=observe(n,m.term);358ifm.kind=="vote_req"thenon_vote_req(o,m,now)359elseifm.kind=="vote"thenon_vote(o,m,now)360elseifm.kind=="append"thenon_append(o,m,now)361elseifm.kind=="append_ok"thenon_append_ok(o,m)362elseo363end;364apply_committed(next)365366-- ---- the fibres of one node ----------------------------------------------367-- A tick every `tick_ms`, and one more at `stop`, so the loop wakes to see368-- that the run is over rather than waiting on a mailbox nobody will fill.369functimer::mb:Channel<Ev>,stop:Int->()!Time.Clock=370let _ =@Time.Clock.sleep(tick_ms());371letsent=Channel.send(mb,Tick);372if@Time.Clock.now()>=stop||!sentthen()elsetimer(mb,stop)373374-- A reader ends with its connection: a peer that crashed dials again, and375-- the acceptor gives that connection a reader of its own.376funcreader::conn:Handle,mb:Channel<Ev>,stop:Int->()!Net.Socket,Time.Clock=377letbytes=try@Net.Socket.recv(conn)378rescueErr.Closed(_)=>Bytes.from_string("")379rescueHandleRefused(_)=>Bytes.from_string("")380end;381if@Time.Clock.now()>=stop||Bytes.length(bytes)==0then()382else383letsent=384tryChannel.send(mb,Got(decode(Bytes.to_string(bytes))))385rescueErr.InvalidJson(_)=>true386rescueErr.MissingField(_, _)=>true387rescueErr.NotAnObject(_)=>true388rescueErr.NotAList(_)=>true389rescueErr.WrongType(_)=>true390end;391ifsentthenreader(conn,mb,stop)else()392393-- Every connection a peer opens gets a reader, for as long as the node runs:394-- a peer that restarts opens new ones.395funcacceptor::sw:Switch,mb:Channel<Ev>,stop:Int->()!Net.Socket,Time.Clock=396if@Time.Clock.now()>=stopthen()397else398let _ =try399letconn=@Net.Socket.accept(100);400let _ =fork(sw){->reader(conn,mb,stop)};401()402rescueErr.BindFailed(_)=>()403end;404acceptor(sw,mb,stop)405406-- One try at each peer: a peer not listening yet is dialled again by the407-- first send to it.408funcdial_all::peers:Vec<String>->Map<String,Handle>!Net.Socket=409Vec.fold(peers,{},{links,p->410tryMap.set(links,p,@Net.Socket.connect(p,port()))411rescueErr.ConnectFailed(_)=>links412rescueErr.BindFailed(_)=>links413end})414415funcrun_loop::n:Node,mb:Channel<Ev>,stop:Int->Node!Store,Net.Socket,Random.Source,Machine,Rules,Time.ClockraisesErr.Closed,HandleRefused=416letnow=@Time.Clock.now();417ifnow>=stopthenn418else419letev=Channel.recv(mb);420run_loop(handle(n,ev,@Time.Clock.now()),mb,stop)421422-- One life of a node: listen, recover what `Store` saved, and run until423-- `stop`. A crash ends it from outside, killing every fibre it has.424funcnode::me:String,stop:Int->()!Store,Net.Socket,Random.Source,Machine,Rules,Time.Clock,Io.Print=425try426let _ =@Net.Socket.listen(me,port());427letsaved=@Store.recover(me);428letpeers=others(me);429Switch.run{sw->430letmb=Channel.make(sw);431let _ =fork(sw){->acceptor(sw,mb,stop)};432let _ =fork(sw){->timer(mb,stop)};433letstart=Node{me:me,peers:peers,role:"follower",term:saved.term,voted:saved.voted,434log:saved.log,commit:0,applied:0,votes:#[],next:{},matched:{},435deadline:@Time.Clock.now()+election_timeout(),beat:0,436links:dial_all(peers)};437letfin=run_loop(start,mb,stop);438let _ =Channel.close(mb);439@Io.Print.println("{me}: {fin.role} in term {fin.term}, log {Vec.size(fin.log)}, commit {fin.commit}")440}441rescueErr.BindFailed(m)=>@Io.Print.println("{me}: {m}")442rescueErr.Closed(m)=>@Io.Print.println("{me}: {m}")443rescueHandleRefused(m)=>@Io.Print.println("{me}: {m}")444end445446-- A node's supervisor, outside the node: when a crash kills the node's447-- fibres, the await is refused, and the supervisor starts the node again.448-- Its `listen` waits until the world brings the host back.449funckeep::me:String,stop:Int->()!Store,Net.Socket,Random.Source,Machine,Rules,Time.Clock,Io.Print=450letcrashed=451trySwitch.run{sw->let _ =Fiber.await(fork(sw){->node(me,stop)});false}452rescueHandleRefused(_)=>true453end;454ifcrashed&&@Time.Clock.now()<stopthenkeep(me,stop)else()455456-- ---- the check at the end -------------------------------------------------457-- State machine safety, as the program can see it: every two nodes applied458-- the same command at every index both reached. The model checks this of459-- the journal; the program checks it of itself, so a run says so too.460funcagree::a:Vec<String>,b:Vec<String>,i:Int->Bool=461ifi>=Vec.size(a)||i>=Vec.size(b)thentrue462else463letsame=tryVec.get(a,i)==Vec.get(b,i)rescueErr.IndexOutOfRange(_)=>falseend;464ifsamethenagree(a,b,i+1)elsefalse465466funcconsistent::logs:Vec<Vec<String>>->Bool=467Vec.all(logs){a->Vec.all(logs){b->agree(a,b,0)}}468469funcmain::->String!Store,Net.Socket,Random.Source,Machine,Rules,Time.Clock,Io.PrintraisesHandleRefused=470let _ =Switch.run{sw->471letfs=Vec.map(hosts()){h->fork(sw){->keep(h,run_ms())}};472Vec.fold(fs,(),{ _,f->Fiber.await(f)})473};474letlogs=Vec.map(hosts()){h->@Machine.applied(h)};475letlens=Vec.fold(logs,"",{acc,l->acc++" "++"{Vec.size(l)}"});476ifconsistent(logs)then"safe: applied{lens}"else"UNSAFE: the nodes applied different commands"477478wireMainrunsRaft.mainwhere479Store=Disk,Machine=Kv,Rules=Strict,480Net.Socket=Net.Sim,Time.Clock=Time.Sim,Random.Source=Random.Sim,481Io.Print=Io.Stdout482483wireCarelessrunsRaft.mainwhere484Store=Disk,Machine=Kv,Rules=Blind,485Net.Socket=Net.Sim,Time.Clock=Time.Sim,Random.Source=Random.Sim,486Io.Print=Io.Stdout487488wireMutantrunsRaft.mainwhere489Store=Disk,Machine=Kv,Rules=Lax,490Net.Socket=Net.Sim,Time.Clock=Time.Sim,Random.Source=Random.Sim,491Io.Print=Io.Stdout492493wireForgetfulrunsRaft.mainwhere494Store=Ram,Machine=Kv,Rules=Strict,495Net.Socket=Net.Sim,Time.Clock=Time.Sim,Random.Source=Random.Sim,496Io.Print=Io.Stdout