目录
正在加载目录…
正在阅读专栏 分布式共识系统专栏 第 3 篇 · 共 59 篇 · 5%

Raft Figure 2 与 3A/3B 日志复制

发布于 2026-09-21 10:04 · 最后编辑于 2026-09-21 10:04 · 版本 v1 · 字数 9,321 · 预计阅读 19 分钟 👁 18 次阅读

Raft Figure 2 与 3A/3B 日志复制

3A 让集群选出 Leader;3B 让 Leader 把命令复制到多数派,并按顺序交给状态机。

TL;DR

  • 3B 的目标是让 make RUN="-run 3B" raft1 的全部测试通过。
  • 日志在实现中使用 0-based 下标,并在下标 0 放置 term 为 0 的 dummy entry。
  • Leader 通过 nextIndex 为每个 Follower 构造 AppendEntries;成功后更新 matchIndex。
  • Leader 只有在当前 term 的日志条目获得多数派确认后,才推进 commitIndex。
  • 独立的 applier 按 lastApplied + 1 的顺序把已提交条目发送到 applyCh。
  • 当前实现位置:implementation/6.5840/src/raft1/raft.go。

名词解释

名词含义
PrevLogIndex新条目前一个日志条目的下标
PrevLogTermPrevLogIndex 对应条目的 term
nextIndex[i]Leader 下一次发送给节点 i 的日志下标
matchIndex[i]Leader 确认节点 i 已复制到的最大下标
commitIndex已被多数派确认、可以交给状态机的最大下标
lastApplied已经发送给状态机的最大下标
Election restriction只有日志足够新(至少不落后)的 Candidate 才能获得投票

目录

章节内容
原文逐行翻译MIT Lab 3A、3B 的目标、全部提示与示例输出
实现模型日志复制和提交的状态关系
代码实现本次实现对应到 raft.go 的字段和流程
测试验收官方 3A/3B 测试结果

原文逐行翻译

来源:本地 source/lab-raft1.html。HTML 的排版换行合并成完整句子,每句英文后紧跟中文;源码行号与块编号供核对。命令、代码和终端输出原样保留。下面的 PASS/FAIL 输出均为原文示例,不代表本机测试结果。

<!-- source: lab-raft1.html:185 block=20 -->

3A 部分:领导者选举

Part 3A: leader election

<!-- source: lab-raft1.html:187 block=21 -->

Implement Raft leader election and heartbeats (AppendEntries RPCs with no log entries).

实现 Raft 领导者选举和心跳,即不携带日志条目的 AppendEntries RPC。

The goal for Part 3A is for a single leader to be elected, for the leader to remain the leader if there are no failures, and for a new leader to take over if the old leader fails or if packets to/from the old leader are lost.

3A 的目标是:选出唯一 leader;没有故障时保持其领导权;旧 leader 故障,或发往、来自旧 leader 的消息丢失时,由新 leader 接管。

Run make RUN="-run 3A" raft1 in the src directory to test your 3A code.

在 src 目录运行 make RUN="-run 3A" raft1 测试 3A 代码。

<!-- source: lab-raft1.html:198 block=22 -->

Follow the paper's Figure 2.

遵循论文的 Figure 2。

At this point you care about sending and receiving RequestVote RPCs, the Rules for Servers that relate to elections, and the State related to leader election,

此阶段重点关注 RequestVote RPC 的发送和接收、服务器规则中与选举有关的部分,以及领导者选举相关的状态。

<!-- source: lab-raft1.html:202 block=23 -->

Add the Figure 2 state for leader election to the Raft struct in raft.go.

把 Figure 2 中与领导者选举有关的状态加入 raft.go 的 Raft 结构体。

<!-- source: lab-raft1.html:206 block=24 -->

Fill in the RequestVoteArgs and RequestVoteReply structs.

补全 RequestVoteArgs 和 RequestVoteReply 结构体。

Modify Make() to create a background goroutine that will kick off leader election periodically by sending out RequestVote RPCs when it hasn't heard from another peer for a while.

修改 Make(),创建后台 goroutine:如果一段时间没有收到其他节点的消息,就发送 RequestVote RPC,定期发起领导者选举。

Implement the RequestVote() RPC handler so that servers will vote for one another.

实现 RequestVote() RPC 处理函数,让服务器能够互相投票。

<!-- source: lab-raft1.html:217 block=25 -->

To implement heartbeats, define an AppendEntries RPC struct (though you may not need all the arguments yet), and have the leader send them out periodically.

为了实现心跳,定义 AppendEntries RPC 结构体,此时可能尚不需要全部参数,并让 leader 定期发送它。

Write an AppendEntries RPC handler method.

编写 AppendEntries RPC 处理方法。

<!-- source: lab-raft1.html:224 block=26 -->

The tester requires that the leader send heartbeat RPCs no more than ten times per second.

测试器要求 leader 每秒发送心跳 RPC 不超过十轮。

<!-- source: lab-raft1.html:228 block=27 -->

The tester requires your Raft to elect a new leader within five seconds of the failure of the old leader (if a majority of peers can still communicate).

如果多数节点仍能够通信,测试器要求 Raft 在旧 leader 故障后的五秒内选出新 leader。

<!-- source: lab-raft1.html:233 block=28 -->

The paper's Section 5.2 mentions election timeouts in the range of 150 to 300 milliseconds.

论文第 5.2 节提到 150~300 毫秒的选举超时范围。

Such a range only makes sense if the leader sends heartbeats considerably more often than once per 150 milliseconds (e.g., once per 10 milliseconds).

只有 leader 发送心跳的频率显著高于每 150 毫秒一次,例如每 10 毫秒一次,这个范围才合理。

Because the tester limits you tens of heartbeats per second, you will have to use an election timeout larger than the paper's 150 to 300 milliseconds, but not too large, because then you may fail to elect a leader within five seconds.

由于测试器限制每秒的心跳次数,你需要采用比论文中 150~300 毫秒更长的选举超时,但也不能过长,否则可能无法在五秒内选出 leader。

<!-- source: lab-raft1.html:242 block=29 -->

You may find Go's rand useful.

Go 的 rand 可能会有帮助。

<!-- source: lab-raft1.html:247 block=30 -->

You'll need to write code that takes actions periodically or after delays in time.

你需要编写周期性执行操作或延迟执行操作的代码。

The easiest way to do this is to create a goroutine with a loop that calls time.Sleep(); see the ticker() goroutine that Make() creates for this purpose.

最简单的方法是创建一个在循环中调用 time.Sleep() 的 goroutine;可以参考 Make() 为此创建的 ticker() goroutine。

Don't use Go's time.Timer or time.Ticker, which are difficult to use correctly.

不要使用 Go 的 time.Timer 或 time.Ticker,因为它们不容易被正确使用。

<!-- source: lab-raft1.html:257 block=31 -->

If your code has trouble passing the tests, read the paper's Figure 2 again; the full logic for leader election is spread over multiple parts of the figure.

如果代码难以通过测试,请重新阅读 Figure 2;完整的领导者选举逻辑分散在图中的多个位置。

<!-- source: lab-raft1.html:262 block=32 -->

Don't forget to implement GetState().

别忘了实现 GetState()。

<!-- source: lab-raft1.html:265 block=33 -->

Go RPC sends only struct fields whose names start with capital letters.

Go RPC 只发送名称以大写字母开头的结构体字段。

Sub-structures must also have capitalized field names (e.g. fields of log records in an array).

嵌套结构体的字段也必须以大写字母开头,例如数组中的日志记录字段。

The labgob package will warn you about this; don't ignore the warnings.

labgob 会对此发出警告,不要忽略这些警告。

<!-- source: lab-raft1.html:270 block=34 -->

The most challenging part of this lab may be the debugging.

本实验最有挑战性的部分可能是调试。

Refer to the Guidance page for debugging tips.

调试建议见 Guidance 页面。

<!-- source: lab-raft1.html:274 block=35 -->

If you fail a test, the tester produces a file that visualizes a timeline with events marked along it, including network partitions, crashed servers, and checks performed.

测试失败时,测试器会生成可视化时间线文件,在其中标注网络分区、服务器崩溃和执行过的检查等事件。

Here's an example of the visualization.

原文在这里提供了一个可视化示例。

Further, you can add your own annotations by writing, for example, tester.Annotate("Server 0", "short description", "details").

此外,你可以添加自己的标注,例如调用 tester.Annotate("Server 0", "short description", "details")。

<!-- source: lab-raft1.html:285 block=36 -->

Be sure you pass the 3A tests before submitting Part 3A, so that you see something like this:

提交 3A 前务必通过 3A 测试,看到类似下面的输出:

<!-- source: lab-raft1.html:289 block=37 -->
text
$ make RUN="-run 3A" raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race -run 3A 
=== RUN   TestInitialElection3A
Test (3A): initial election (reliable network)...
  ... Passed --  time  3.5s #peers 3 #RPCs    32 #Ops    0
--- PASS: TestInitialElection3A (3.84s)
=== RUN   TestReElection3A
Test (3A): election after network failure (reliable network)...
  ... Passed --  time  6.2s #peers 3 #RPCs    68 #Ops    0
--- PASS: TestReElection3A (6.54s)
=== RUN   TestManyElections3A
Test (3A): multiple elections (reliable network)...
  ... Passed --  time  9.8s #peers 7 #RPCs   684 #Ops    0
--- PASS: TestManyElections3A (10.68s)
PASS
ok      6.5840/raft1    22.095s
$
<!-- source: lab-raft1.html:310 block=38 -->

Each "Passed" line contains five numbers; these are the time that the test took in seconds, the number of Raft peers, the number of RPCs sent during the test, the total number of bytes in the RPC messages, and the number of log entries that Raft reports were committed.

原文说,每条 Passed 行包含五个数字,依次为:测试耗时(秒)、Raft 节点数、测试期间发送的 RPC 数、RPC 消息总字节数,以及 Raft 报告已提交的日志条目数。

Your numbers will differ from those shown here.

你的数字会与示例不同。

You can ignore the numbers if you like, but they may help you sanity-check the number of RPCs that your implementation sends.

你可以忽略这些数字,但它们能帮助你粗略检查实现发送的 RPC 数量是否合理。

For all of labs 3, 4, and 5, the grading script will fail your solution if it takes more than 600 seconds for all of the tests, or if any individual test takes more than 120 seconds.

对 Lab 3、4、5,如果完整测试耗时超过 600 秒,或任意单项测试耗时超过 120 秒,评分脚本就会判定方案失败。

<!-- source: lab-raft1.html:323 block=39 -->

When we grade your submissions, we will run the tests without the -race flag.

评分时,我们运行测试不会使用 -race 参数。

However, you should make sure that your code consistently passes the tests with the -race flag.

不过,你应该确保代码在启用 -race 时也能稳定通过测试。

<!-- source: lab-raft1.html:329 block=40 -->

3B 部分:日志

Part 3B: log

<!-- source: lab-raft1.html:331 block=41 -->

Implement the leader and follower code to append new log entries, so that make RUN="-run 3B" raft1 passes all tests.

实现 leader 和 follower 追加新日志条目的代码,使 make RUN="-run 3B" raft1 通过全部测试。

<!-- source: lab-raft1.html:337 block=42 -->

Run git pull to get the latest lab software.

运行 git pull 获取最新实验代码。

<!-- source: lab-raft1.html:340 block=43 -->

The Raft paper views the log as 1-indexed, but we suggest that you implement it as 0-indexed, starting with a dummy entry at index=0 that has term 0.

Raft 论文将日志视为从 1 开始编号,但我们建议实现时从 0 开始,在 index=0 放置一个 term 为 0 的占位条目。

That allows the very first AppendEntries RPC to contain 0 as PrevLogIndex, and be a valid index into the log.

这样,第一个 AppendEntries RPC 就能把 PrevLogIndex 设为 0,并且它仍是有效的日志索引。

<!-- source: lab-raft1.html:347 block=44 -->

Your first goal should be to pass TestBasicAgree3B().

第一个目标应该是通过 TestBasicAgree3B()。

Start by implementing Start(), then write the code to send and receive new log entries via AppendEntries RPCs, following Figure 2.

先实现 Start(),再按 Figure 2 编写通过 AppendEntries RPC 发送和接收新日志条目的代码。

Send each newly committed entry on applyCh on each peer.

在每个节点上,把每条新提交的条目发送到 applyCh。

<!-- source: lab-raft1.html:354 block=45 -->

You will need to implement the election restriction (section 5.4.1 in the paper).

你需要实现论文第 5.4.1 节中的选举限制。

<!-- source: lab-raft1.html:358 block=46 -->

Your code may have loops that repeatedly check for certain events.

代码中可能有反复检查某些事件的循环。

Don't have these loops execute continuously without pausing, since that will slow your implementation enough that it fails tests.

不要让循环毫不停顿地运行,否则会拖慢实现,甚至无法通过测试。

Use Go's condition variables, or insert a time.Sleep(10 * time.Millisecond) in each loop iteration.

可以使用 Go 的条件变量,或在每轮循环中插入 time.Sleep(10 * time.Millisecond)。

<!-- source: lab-raft1.html:368 block=47 -->

Do yourself a favor for future labs and write (or re-write) code that's clean and clear.

为了让后续实验更轻松,请编写或重写出清晰整洁的代码。

<!-- source: lab-raft1.html:371 block=48 -->

If you fail a test, look at raft_test.go and trace the test code from there to understand what's being tested.

如果某个测试失败,请查看 raft_test.go 并沿着测试代码追踪,理解它到底在测试什么。

<!-- source: lab-raft1.html:377 block=49 -->

The tests for upcoming labs may fail your code if it runs too slowly.

后续实验可能因为代码运行过慢而判定失败。

You can check how much real time and CPU time your solution uses with the time command.

你可以用 time 命令检查方案消耗的实际时间和 CPU 时间。

Here's typical output:

下面是典型输出:

<!-- source: lab-raft1.html:382 block=50 -->
text
$ make RUN="-run 3B" raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race -run 3B 
=== RUN   TestBasicAgree3B
Test (3B): basic agreement (reliable network)...
  ... Passed --  time  1.6s #peers 3 #RPCs    18 #Ops    3
--- PASS: TestBasicAgree3B (1.96s)
=== RUN   TestRPCBytes3B
Test (3B): RPC byte count (reliable network)...
  ... Passed --  time  3.3s #peers 3 #RPCs    50 #Ops   11
--- PASS: TestRPCBytes3B (3.71s)
=== RUN   TestFollowerFailure3B
Test (3B): test progressive failure of followers (reliable network)...
  ... Passed --  time  5.4s #peers 3 #RPCs    58 #Ops    3
--- PASS: TestFollowerFailure3B (5.77s)
=== RUN   TestLeaderFailure3B
Test (3B): test failure of leaders (reliable network)...
  ... Passed --  time  6.5s #peers 3 #RPCs   110 #Ops    3
--- PASS: TestLeaderFailure3B (6.89s)
=== RUN   TestFailAgree3B
Test (3B): agreement after follower reconnects (reliable network)...
  ... Passed --  time  6.0s #peers 3 #RPCs    61 #Ops    7
--- PASS: TestFailAgree3B (6.37s)
=== RUN   TestFailNoAgree3B
Test (3B): no agreement if too many followers disconnect (reliable network)...
  ... Passed --  time  4.0s #peers 5 #RPCs   107 #Ops    2
--- PASS: TestFailNoAgree3B (4.55s)
=== RUN   TestConcurrentStarts3B
Test (3B): concurrent Start()s (reliable network)...
  ... Passed --  time  1.4s #peers 3 #RPCs    12 #Ops    0
--- PASS: TestConcurrentStarts3B (1.75s)
=== RUN   TestRejoin3B
Test (3B): rejoin of partitioned leader (reliable network)...
  ... Passed --  time  7.8s #peers 3 #RPCs   120 #Ops    4
--- PASS: TestRejoin3B (8.15s)
=== RUN   TestBackup3B
Test (3B): leader backs up quickly over incorrect follower logs (reliable network)...
  ... Passed --  time 27.7s #peers 5 #RPCs  1370 #Ops  102
--- PASS: TestBackup3B (28.27s)
=== RUN   TestCount3B
Test (3B): RPC counts aren't too high (reliable network)...
  ... Passed --  time  2.7s #peers 3 #RPCs    32 #Ops    0
--- PASS: TestCount3B (3.05s)
PASS
ok      6.5840/raft1    71.716s
$
<!-- source: lab-raft1.html:429 block=51 -->

The "ok 6.5840/raft 71.716s" means that Go measured the time taken for the 3B tests to be 71.716 seconds of real (wall-clock) time.

ok 6.5840/raft 71.716s 表示 Go 测得 3B 测试消耗了 71.716 秒实际时间,也就是墙钟时间。

If your solution uses much more than a few minutes of real time for the 3B tests, you may run into trouble later on.

如果你的方案运行 3B 测试需要远超几分钟的实际时间,后面可能会遇到问题。

Look for time spent sleeping or waiting for RPC timeouts, loops that run without sleeping or waiting for conditions or channel messages, or large numbers of RPCs sent.

检查时间是否花在休眠或等待 RPC 超时上,是否存在既不休眠、也不等待条件或通道消息的循环,或者是否发送了大量 RPC。

实现模型

mermaid
flowchart LR
    Start[Start(command)] --> Append[Leader 追加 LogEntry]
    Append --> AE[AppendEntries PrevLog + Entries]
    AE --> Ack[Follower 成功响应]
    Ack --> Match[更新 matchIndex]
    Match --> Majority{多数派确认?}
    Majority -->|是| Commit[推进 commitIndex]
    Commit --> Apply[applier 顺序发送 ApplyMsg]
    Apply --> SM[上层状态机]

Leader 对每个 Follower 单独维护复制进度。nextIndex 决定本次 RPC 从哪里开始,PrevLogIndex 和 PrevLogTerm 用来检查两边日志前缀是否一致;如果不一致,Follower 返回冲突位置,Leader 回退 nextIndex 后重试。

mermaid
stateDiagram-v2
    [*] --> Follower
    Follower --> Candidate: election timeout
    Candidate --> Leader: majority votes
    Leader --> Follower: higher term / valid leader RPC
    Candidate --> Follower: higher term / valid leader RPC
    Leader --> Leader: AppendEntries success

日志提交和日志应用是两个不同动作:复制到多数派只推进 commitIndex;applier 再按照连续下标推进 lastApplied,保证上层状态机不会跳过中间条目。

代码实现

1. Figure 2 的日志状态

当前 Raft 增加了:

go
log         []LogEntry
commitIndex int
lastApplied int
nextIndex   []int
matchIndex  []int

LogEntry 保存命令和产生它的 term:

go
type LogEntry struct {
    Command interface{}
    Term    int
}

2. Start 立即返回

Start 只在本地追加条目、返回下标和 term,不等待网络复制完成。Leader 将自己的 matchIndex 更新到新条目位置,后续心跳周期会把条目发送给 Follower。

3. AppendEntries

Leader 发送:

  • 当前 Term 和 LeaderID;
  • PrevLogIndex、PrevLogTerm;
  • 从 nextIndex[peer] 开始的日志切片;
  • LeaderCommit。

Follower 先检查 term 和前置日志。如果前置日志不存在或 term 不匹配,就返回冲突位置;匹配后再覆盖冲突后缀并追加新条目。Follower 只能把 commitIndex 推进到 min(LeaderCommit, PrevLogIndex + len(Entries)),且不能倒退。不能直接用本地 lastLogIndex:该 RPC 未核对的尾部可能仍属于旧 leader 的冲突日志。

2026-09-19 的回归测试固定了这个反例:follower 在索引 3 保存冲突条目,而 RPC 只确认到索引 2,即使 LeaderCommit=3 也只能提交到 2。另一个回归测试让请求正常送达、回复延迟,确认第三次周期心跳不会被两条尚未返回的 RPC 堵住。对应源码为 raft1/regression_test.go。

4. 提交规则

Leader 收到成功响应后更新 matchIndex,然后寻找最大的 N,满足:

  1. 超过半数节点的 matchIndex 至少为 N;
  2. log[N].Term == currentTerm。

第二个条件是 Figure 2 的关键限制:Leader 不能仅凭复制数量直接提交旧 term 的条目,但提交当前 term 的条目后,之前的连续日志也会随之提交。

5. 选举限制

RequestVote 携带 Candidate 的最后日志下标和 term。Follower 按“最后日志 term 更大,或 term 相同但下标不小于自己”的规则判断 Candidate 是否足够新;日志落后的 Candidate 即使 term 更新,也不能获得投票。

6. 顺序应用

实现使用 sync.Cond 唤醒 applier,而不是让每个 RPC 直接向 applyCh 发送。applier 每次只把 lastApplied + 1 发送出去,然后再继续处理下一条,这样可以保证 ApplyMsg 按日志顺序到达上层服务。

测试验收

执行命令:

bash
cd "/Users/maxingfang/w/w/21 数据库实现/04 分布式共识系统/implementation/6.5840/src"
make RUN='-run 3A' raft1
make RUN='-run 3B' raft1

本次实际验收结果:

  • 3A:TestInitialElection3A、TestReElection3A、TestManyElections3A 全部通过。
  • 3B:基础复制、RPC 字节数、Follower 故障、Leader 故障、重新加入、无多数派不提交、并发 Start、日志回退、RPC 数量全部通过。
  • 测试使用 -race,未报告数据竞争。
  • git diff --check 通过。

下一步

下一阶段是 3C 持久化:在 term、votedFor 和 log 发生变化时保存状态,并在节点重启后恢复;需要保持当前 3A/3B 测试继续通过。

参考资料

← 返回列表
← 上一篇 分布式共识与复制状态机 下一篇 → Lab 3C:持久化与重启恢复

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论