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

Lab 3C:持久化与重启恢复

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

Lab 3C:持久化与重启恢复

Raft 的安全性不能只存在于内存中;节点重启后,term、投票和日志必须恢复到崩溃前的状态。

TL;DR

  • Figure 2 中需要持久化的是 currentTerm、votedFor 和 log。
  • 教学实验用 Persister 模拟稳定存储,不直接写磁盘。
  • 使用 labgob 把三项状态编码成字节数组,再调用 Save;启动时用 ReadRaftState 恢复。
  • 每次 term、投票或日志发生变化时都要调用 persist()。
  • 3C 还要求日志冲突时快速回退 nextIndex,避免逐条回退导致测试过慢。
  • 当前实现已经通过官方全部 3C 测试,并保持 3A/3B 通过。

目录

章节内容
原文逐行翻译MIT Lab 3C 持久化说明的逐行翻译
持久化状态Figure 2 的三项持久化字段
代码实现persist、readPersist 和调用时机
快速回退冲突 term、起始下标和日志长度
测试验收3C 官方测试结果

原文逐行翻译

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

<!-- source: lab-raft1.html:439 block=52 -->

3C 部分:持久化

Part 3C: persistence

<!-- source: lab-raft1.html:441 block=53 -->

If a Raft-based server reboots it should resume service where it left off.

基于 Raft 的服务器重启后,应从中断处恢复服务。

This requires that Raft keep persistent state that survives a reboot.

这要求 Raft 保存能够跨重启保留的持久化状态。

The paper's Figure 2 mentions which state should be persistent.

论文 Figure 2 指出了哪些状态应当持久化。

<!-- source: lab-raft1.html:447 block=54 -->

A real implementation would write Raft's persistent state to disk each time it changed, and would read the state from disk when restarting after a reboot.

实际实现会在 Raft 的持久化状态每次变化时把它写入磁盘,并在重启时从磁盘读取。

Your implementation won't use the disk; instead, it will save and restore persistent state from a Persister object (see tester1/persister.go).

本实验的实现不使用磁盘,而是通过 Persister 对象保存和恢复持久化状态,见 tester1/persister.go。

Whoever calls Raft.Make() supplies a Persister that initially holds Raft's most recently persisted state (if any).

调用 Raft.Make() 的代码会提供一个 Persister,其中初始保存着 Raft 最近一次持久化的状态(如果存在)。

Raft should initialize its state from that Persister, and should use it to save its persistent state each time the state changes.

Raft 应从这个 Persister 初始化状态,并在每次持久化状态变化时用它保存状态。

Use the Persister's ReadRaftState() and Save() methods.

使用 Persister 的 ReadRaftState() 和 Save() 方法。

<!-- source: lab-raft1.html:461 block=55 -->

Complete the functions persist() and readPersist() in raft.go by adding code to save and restore persistent state.

补全 raft.go 中的 persist() 和 readPersist(),加入保存和恢复持久化状态的代码。

You will need to encode (or "serialize") the state as an array of bytes in order to pass it to the Persister.

为了把状态传给 Persister,你需要将其编码,也就是序列化成字节数组。

Use the labgob encoder; see the comments in persist() and readPersist().

使用 labgob 编码器,参考 persist() 和 readPersist() 中的注释。

labgob is like Go's gob encoder but prints error messages if you try to encode structures with lower-case field names.

labgob 类似 Go 的 gob 编码器,但如果你尝试编码包含小写字段名的结构体,它会打印错误信息。

For now, pass nil as the second argument to persister.Save().

目前,把 nil 作为 persister.Save() 的第二个参数。

Insert calls to persist() at the points where your implementation changes persistent state.

在实现修改持久化状态的位置插入 persist() 调用。

Once you've done this, and if the rest of your implementation is correct, you should pass all of the 3C tests.

完成后,如果其余实现正确,就应该能够通过全部 3C 测试。

<!-- source: lab-raft1.html:480 block=56 -->

You will probably need the optimization that backs up nextIndex by more than one entry at a time.

你可能需要实现一次将 nextIndex 回退多个条目的优化。

Look at the extended Raft paper starting at the bottom of page 7 and top of page 8 (marked by a gray line).

阅读扩展论文第 7 页底部至第 8 页顶部、由灰线标出的部分。

The paper is vague about the details; you will need to fill in the gaps.

论文对细节描述得比较模糊,你需要补齐。

One possibility is to have a rejection message include:

一种方法是让拒绝响应包含以下信息:

<!-- source: lab-raft1.html:488 block=57 -->
text
    XTerm:  term in the conflicting entry (if any)
    XIndex: index of first entry with that term (if any)
    XLen:   log length

XTerm:冲突条目的任期(如果存在)。
XIndex:该任期第一条日志的索引(如果存在)。
XLen:日志长度。

<!-- source: lab-raft1.html:492 block=58 -->

Then the leader's logic can be something like:

随后,leader 的逻辑可以类似下面这样:

<!-- source: lab-raft1.html:496 block=59 -->
text
  Case 1: leader doesn't have XTerm:
    nextIndex = XIndex
  Case 2: leader has XTerm:
    nextIndex = (index of leader's last entry for XTerm) + 1
  Case 3: follower's log is too short:
    nextIndex = XLen

情况 1:leader 没有 XTerm,令 nextIndex = XIndex。
情况 2:leader 有 XTerm,令 nextIndex 等于 leader 中该任期最后一个条目的索引加一。
情况 3:follower 日志过短,令 nextIndex = XLen。

<!-- source: lab-raft1.html:503 block=60 -->

A few other hints:

还有几条提示:

<!-- source: lab-raft1.html:509 block=61 -->

Run git pull to get the latest lab software.

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

<!-- source: lab-raft1.html:512 block=62 -->

The 3C tests are more demanding than those for 3A or 3B, and failures may be caused by problems in your code for 3A or 3B.

3C 测试比 3A、3B 更严格,失败也可能源于 3A 或 3B 的代码问题。

<!-- source: lab-raft1.html:518 block=63 -->

Your code should pass all the 3C tests (as shown below), as well as the 3A and 3B tests.

你的代码应通过下面所示的全部 3C 测试,同时继续通过 3A 和 3B。

<!-- source: lab-raft1.html:522 block=64 -->
text
$ make RUN="-run 3C" raft1
go build -race -o main/raft1d main/raft1d.go
cd raft1 && go test -v -race -run 3C 
=== RUN   TestPersist13C
Test (3C): basic persistence (reliable network)...
  ... Passed --  time  7.6s #peers 3 #RPCs    58 #Ops    6
--- PASS: TestPersist13C (7.99s)
=== RUN   TestPersist23C
Test (3C): more persistence (reliable network)...
  ... Passed --  time 21.6s #peers 5 #RPCs   287 #Ops   16
--- PASS: TestPersist23C (22.17s)
=== RUN   TestPersist33C
Test (3C): partitioned leader and one follower crash, leader restarts (reliable network)...
  ... Passed --  time  3.8s #peers 3 #RPCs    30 #Ops    4
--- PASS: TestPersist33C (4.11s)
=== RUN   TestFigure83C
Test (3C): Figure 8 (reliable network)...
  ... Passed --  time 48.5s #peers 5 #RPCs   499 #Ops    2
--- PASS: TestFigure83C (49.08s)
=== RUN   TestUnreliableAgree3C
Test (3C): unreliable agreement (unreliable network)...
  ... Passed --  time  5.1s #peers 5 #RPCs   288 #Ops  246
--- PASS: TestUnreliableAgree3C (5.68s)
=== RUN   TestFigure8Unreliable3C
Test (3C): Figure 8 (unreliable) (unreliable network)...
  ... Passed --  time 53.6s #peers 5 #RPCs  3200 #Ops    2
--- PASS: TestFigure8Unreliable3C (54.19s)
=== RUN   TestReliableChurn3C
Test (3C): churn (reliable network)...
  ... Passed --  time 18.2s #peers 5 #RPCs  1701 #Ops    1
--- PASS: TestReliableChurn3C (18.80s)
=== RUN   TestUnreliableChurn3C
Test (3C): unreliable churn (unreliable network)...
  ... Passed --  time 17.3s #peers 5 #RPCs  1253 #Ops    1
--- PASS: TestUnreliableChurn3C (17.92s)
PASS
ok      6.5840/raft1    180.983s
$
<!-- source: lab-raft1.html:563 block=65 -->

It is a good idea to run the tests multiple times before submitting.

提交之前最好多运行几次测试。

持久化状态

mermaid
flowchart LR
    Change[term / vote / log 变化] --> Encode[labgob 编码]
    Encode --> Save[Persister.Save]
    Save --> Crash[节点崩溃]
    Crash --> Read[Persister.ReadRaftState]
    Read --> Decode[labgob 解码]
    Decode --> Resume[恢复 Raft 状态]

持久化内容:

go
currentTerm int
votedFor    int
log         []LogEntry

commitIndex、lastApplied、nextIndex、matchIndex 和当前角色属于易失状态。重启后它们可以重新初始化或通过后续 RPC 重新建立。

代码实现

3C 的最小思路是按约定格式编码 currentTerm、votedFor 和 log,并以对应格式解码。若尚未实现快照,可以这样保存(教学示意,不是当前源码的逐字摘录):

go
rf.persister.Save(w.Bytes(), nil)

当前完整实现已包含 3D:使用 RFT2 格式标识、长度前缀、由 labgob 编码的 persistedHeader 和逐条编码的日志,并缓存日志编码以减少重复工作。头部还包含快照边界和日志长度;保存时实际调用 Persister.Save(raftState, rf.snapshot),不能继续传 nil 丢弃已有快照。恢复路径见 raft1/raft.go 的 readPersist()。

本次实现插入持久化调用的位置包括:

  • Candidate 开始新 term,并投票给自己;
  • Follower 发现更高 term;
  • Follower 接受投票并更新 votedFor;
  • Follower 追加或覆盖日志;
  • Leader 在 Start 中追加客户端命令。

启动时 Make 先建立默认 dummy entry,再调用 readPersist(persister.ReadRaftState())。如果读到有效状态,就覆盖默认的 term、投票和日志;如果没有状态,则保留空日志的 dummy entry。

快速回退

You will probably need the optimization that backs up nextIndex by more than one entry at a time.
你可能需要一种优化,让 nextIndex 一次回退多个条目。

原文建议拒绝响应携带三项信息:

text
XTerm:  冲突条目的 term(如果存在)
XIndex: 该 term 第一次出现的下标(如果存在)
XLen:   Follower 的日志长度

Leader 的处理可以分成三种情况:

  1. Leader 没有 XTerm:把 nextIndex 设为 XIndex。
  2. Leader 有 XTerm:把 nextIndex 设为 Leader 中该 term 最后一个条目的下一个位置。
  3. Follower 日志太短:把 nextIndex 设为 XLen。

当前实现将这些信息对应为 ConflictTerm 和 ConflictIndex,从而在日志分叉较长时快速找到共同前缀。

测试验收

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

实际结果:

  • TestPersist13C、TestPersist23C、TestPersist33C 通过;
  • TestFigure83C、TestUnreliableAgree3C、TestFigure8Unreliable3C 通过;
  • TestReliableChurn3C、TestUnreliableChurn3C 通过;
  • 测试使用 -race,未报告数据竞争。

下一步

3D 将加入 Snapshot 和 InstallSnapshot:状态机确认某个日志位置后,Raft 可以截断旧日志,并在 Follower 落后到日志已被截断时发送快照。

参考资料

← 返回列表
← 上一篇 Raft Figure 2 与 3A/3B 日志复制 下一篇 → Lab 3D:快照与日志压缩

评论 (0)

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