TxTransactions Lab
GitHub
IV · Implement distributed decisions

Replicate the decision log.

A coordinator's decision can survive its current leader only if the protocol preserves the record through replication and future elections. Trace the entries and votes that make that possible.

You will: inspect term/index pairs, implement election log comparison, trace AppendEntries prefix matching, and locate quorum commit before acknowledgement. Prerequisites: consensus versus atomic commit. Runtime: a three-node Raft-style log core with explicit send events.

A term is a numbered leadership period. An index is a log position. Together they identify an entry when a leader asks a follower to match a prefix.

Concept diagram · before the experiment

Replicating a decision needs a protocol, not just copies

A leader-only entry may disappear from the surviving group if acknowledged too early. A Raft-style protocol combines majority replication, terms, election log restrictions and prefix matching to preserve committed entries. A coordinator quorum is separate from all required participant YES votes.
Read the diagram: A majority is meaningful together with the election and log rules that preserve its entries. For Raft-style commit advancement, the leader commits an entry from its current term on a majority, bringing its earlier prefix with it. Agreement among coordinator replicas does not invent missing participant votes. Open full diagram

Predict

A writes COMMIT locally and replies before either follower has it. A becomes unreachable. Can B and C elect a leader whose log does not contain that decision? What must change before the original reply is justified?

The state behind the replicas

Each node has a durable log and term/vote state. A log entry has an index, term and command. The leader tracks each follower's nextIndex and confirmed matchIndex. Its commitIndex identifies the prefix it may expose as committed.

Before appending a suffix, a follower checks that the preceding entry matches the leader's expected position and term. A mismatch rejects the request; the leader backs nextIndex up and sends a longer suffix. This is why the repaired scenario sends to C twice after the election: its first request assumes a prefix that C does not yet have.

Election voters grant at most one vote per term and require an up-to-date candidate log: compare the last entry's term first, then its index. A candidate with a longer log from an older term may still be less up to date. A majority election and these log rules help preserve committed history.

For this core, the leader advances commitIndex to N only when a majority has confirmed through N and the entry at N is from the leader's current term. Committing that current-term prefix also commits preceding entries. This restriction matters after an election; counting old-term copies alone is not the full rule.

Control the experiment

The page loads Baseline with three empty replica logs and local acknowledgement. Select Run to end. In Replica logs and protocol state, compare A’s COMMIT with the new leader’s committed prefix. Did the decision survive the election?

An executable three-node Raft-style log core: durable entries/votes, up-to-date elections, prefix matching/backtracking and current-term majority commit. Sends are explicit atomic events; no timers, partitions with concurrent leaders, membership changes, snapshots or production Raft claim.

Edit the experiment

Change the JSON settings and select Step or Run to end. Restore scenario reloads the selected preset.

Select Step to inspect the initial state.

    Each replica has its own log lane. Entry labels distinguish locally stored entries from that node’s committed prefix; a down node keeps its stable log in the picture. Compare the lanes through the election and prefix-repair events.

    Choose Repair and select Run to end. Revisit both AppendEntries to C steps. Compare Response and Previous index, then find COMMIT in the new leader’s committed prefix. Why does C accept the second request?

    Inspect and implement the election rule

    Expand the source to inspect actual vote, replication and commit-index calculations. Select Test implementation in the bench. In Your JavaScript implementation, compare the final term first, then the final index if the terms match. Test again and compare the shorter newer-term candidate with the longer older-term candidate.

    Read the engine code executed by this lab

    These functions come directly from the running engine. Shared helpers and every mechanism are in the complete downloadable module.

    function upToDate(candidate, voter) {
      const a=candidate.at(-1)||{term:0,index:0},b=voter.at(-1)||{term:0,index:0};
      return a.term>b.term||(a.term===b.term&&a.index>=b.index);
    }
    
    function replicatedLog(config) {
      choose(config,'ack',['local','quorum']);
      const node=()=>({live:true,term:1,log:[],commitIndex:0,vote:null,voteTerm:0,role:'follower'});
      const s={nodes:{A:node(),B:node(),C:node()},leader:'A',nextIndex:{B:1,C:1},matchIndex:{A:0,B:0,C:0},target:null,acknowledged:[],votes:[],rpc:null,recovered:null,readAttempted:false};
      s.nodes.A.role='leader';
      const same=(a,b)=>a&&b&&a.index===b.index&&a.term===b.term&&a.command===b.command;
      const t=recorder(s,s=>[check('every acknowledgement refers to a quorum-committed entry',s.acknowledged.every(a=>a.quorumCommitted)),check('after failover the acknowledged decision remains in the committed prefix',s.readAttempted&&s.acknowledged.length?s.acknowledged.every(a=>same(s.nodes[s.leader].log[a.index-1],a)&&s.nodes[s.leader].commitIndex>=a.index):null)]);
      for(const op of program(config)) {
        const [action,arg]=op.split(':');
        if(action==='crash'||action==='restart') {
          if(!s.nodes[arg])throw Error('Name node A, B or C.');s.nodes[arg].live=action==='restart';s.nodes[arg].role='follower';t.emit(`${action} ${arg}; stable log and vote survive`);continue;
        }
        if(action==='elect') {
          const candidate=s.nodes[arg];if(!candidate?.live)throw Error('Candidate must be live.');
          candidate.term++;candidate.role='candidate';s.votes=[];
          for(const [name,voter] of Object.entries(s.nodes))if(voter.live&&candidate.term>=voter.term) {
            if(candidate.term>voter.term){voter.term=candidate.term;voter.vote=null;voter.voteTerm=0;voter.role='follower';}
            if((voter.voteTerm!==candidate.term||voter.vote===arg)&&upToDate(candidate.log,voter.log)){voter.vote=arg;voter.voteTerm=candidate.term;s.votes.push(name);}
          }
          if(s.votes.length>=2){candidate.role='leader';s.leader=arg;s.nextIndex={};s.matchIndex={A:0,B:0,C:0};s.matchIndex[arg]=candidate.log.length;for(const name of Object.keys(s.nodes))if(name!==arg)s.nextIndex[name]=candidate.log.length+1;}
          t.emit(`${arg} requests votes in term ${candidate.term}: ${s.votes.length>=2?'elected':'no majority'}`);continue;
        }
        const leader=s.nodes[s.leader];if(!leader.live||leader.role!=='leader')throw Error('Elect a live leader before continuing.');
        if(action==='append') {
          if(!['COMMIT','NOOP'].includes(arg))throw Error('Append COMMIT or NOOP.');
          const entry={index:leader.log.length+1,term:leader.term,command:arg};leader.log.push(entry);s.matchIndex[s.leader]=entry.index;
          if(arg==='COMMIT')s.target=copy(entry);t.emit(`Leader appends ${arg} at index ${entry.index}, term ${entry.term}`);
        }else if(action==='replicate') {
          const follower=s.nodes[arg];if(!follower||arg===s.leader)throw Error('Choose a follower A, B or C.');
          if(!follower.live){t.emit(`${arg} is unreachable; no replication acknowledgement`);continue;}
          if(leader.term<follower.term)throw Error('Stale leader term: elect a current leader.');
          if(follower.term<leader.term){follower.vote=null;follower.voteTerm=0;}follower.term=leader.term;follower.role='follower';
          const next=s.nextIndex[arg]??1,prev=next-1,expected=leader.log[prev-1];
          if(prev>0&&!same(follower.log[prev-1],expected)) {
            s.nextIndex[arg]=Math.max(1,next-1);s.rpc={to:arg,prevIndex:prev,result:'prefix mismatch; backtrack nextIndex'};
          }else {
            const entries=leader.log.slice(next-1);let i=0;
            while(i<entries.length&&same(follower.log[next-1+i],entries[i]))i++;
            if(i<entries.length)follower.log=[...follower.log.slice(0,next-1+i),...copy(entries.slice(i))];
            s.matchIndex[arg]=prev+entries.length;s.nextIndex[arg]=s.matchIndex[arg]+1;
            for(let n=leader.log.length;n>leader.commitIndex;n--)if(leader.log[n-1].term===leader.term&&Object.values(s.matchIndex).filter(index=>index>=n).length>=2){leader.commitIndex=n;break;}
            follower.commitIndex=Math.max(follower.commitIndex,Math.min(leader.commitIndex,follower.log.length));
            s.rpc={to:arg,prevIndex:prev,result:'prefix matched; entries persisted',matchIndex:s.matchIndex[arg]};
          }
          t.emit(`AppendEntries to ${arg}: ${s.rpc.result}`);
        }else if(action==='ack') {
          if(!s.target)throw Error('Append a COMMIT decision first.');
          const valid=same(leader.log[s.target.index-1],s.target)&&leader.commitIndex>=s.target.index;
          if(config.ack==='local'||valid){s.acknowledged.push({...s.target,quorumCommitted:valid});t.emit('Acknowledge the decision to its caller');}
          else t.emit('Withhold acknowledgement: the decision is not yet quorum committed');
        }else if(action==='recover') {
          s.readAttempted=true;s.recovered=leader.log.slice(0,leader.commitIndex).find(e=>e.command==='COMMIT')||null;t.emit('Read the recovered committed prefix after the explicit election/replication schedule');
        }else throw Error(`Unknown replicated-log operation ${op}`);
      }
      return t.finish();
    }
    Implementation bench · write the algorithm

    Implement the election log check

    solve(candidateLog, voterLog) returns true when the candidate is at least as up to date: compare last-entry term first, then index if terms tie. An empty log has term 0/index 0. Log length alone is insufficient.

    The trace above uses the published algorithm. Test your own function here against the named cases.

    Test the starter to find the cases it misses.

      Compare the reference implementation

      Attempt the named cases before comparing your solution.

      function solve(candidate, voter) {
        const a=candidate.at(-1)||{term:0,index:0},b=voter.at(-1)||{term:0,index:0};
        return a.term>b.term||(a.term===b.term&&a.index>=b.index);
      }
      Download your code

      Change one thing

      In Repair, open Edit the experiment, remove "replicate:B" before "ack", and select Run to end. Read the acknowledgement step and compare with Repair. Choose missing-majority and run again. Which step shows why a client reply is withheld?

      Return to Repair and replace schedule with ["append:COMMIT","replicate:B","ack","crash:A","elect:C"]. Select Run to end and inspect Election votes. Then append "append:NOOP" and run again. The input error explains why a leader-only operation cannot run. Remove that final entry and run to inspect the valid election history again.

      Hint 1 · Separate local append from committed prefix

      An entry in one stable log has survived that node's process restart, but is not necessarily protected against replacement after a different majority elects a leader.

      Hint 2 · Order election candidates by term, then index

      Do not compare array lengths first. Terms identify leadership epochs; only when last terms tie does the last index break the tie.

      Why this result occurs

      A local-only acknowledgement can name an entry absent from every available majority. The repair makes the entry quorum committed before replying, then preserves it through an up-to-date election and log-prefix repair. The explicit NOOP establishes a current-term committed prefix on the new leader. This lab implements a bounded log core, not all of Raft: no election timers, concurrent leaders, arbitrary delayed messages, membership changes or log snapshots are simulated.

      Transfer the idea

      Place the two-phase coordinator's PREPARE and COMMIT records in this replicated log. Explain why preserving a recorded decision does not supply a missing participant YES vote. Then identify the atomicity boundary between a committed log entry and each participant's local data changes. Consensus replication and atomic commit solve connected but different problems.

      Success criteria: cite term/index pairs and actual votes; show withheld acknowledgement without a majority and the prefix-repair backtrack; pass the election comparison bench and separate committed coordinator history from participant commit.

      Primary source: Ongaro and Ousterhout, In Search of an Understandable Consensus Algorithm, especially the log replication and leader completeness rules.

      Your design record

      Explain what happened and cite the run or SQL result that supports it.

      Write your design notes

      Download notes and evidence

      Downloads include current editor text. Run evidence stays on this page until you leave.