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

Lab 4:容错 KV 与复制状态机

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

Lab 4:容错 KV 与复制状态机

Lab 3 的 Raft 只复制命令;Lab 4 把它接到真正的状态机:请求先进入 Raft,提交后由每个副本按相同顺序执行。

TL;DR

  • 4A 实现 RSM:Submit 调用 raft.Start,reader 从 applyCh 取提交命令并调用 DoOp。
  • 4B 实现 KV:Get 也进入 Raft,避免隔离 Leader 返回过期数据;Put 通过版本号实现条件更新和至多一次执行。
  • 4C 复用 3D 快照:业务状态序列化后和 Raft 状态一起保存,重启或安装快照后恢复 KV 表。
  • 当前实现位置:implementation/6.5840/src/kvraft1/rsm/、kvraft1/server.go、kvraft1/client.go。
  • 本轮 RSM 与完整 KV -race 测试返回 PASS;已修复 ErrWrongLeader 后重试的结果判定问题。多客户端快照场景内部的线性一致性检查有超时,详细限制见 分布式共识系统专栏索引。

目录

章节内容
原文逐行翻译Lab 4 总目标、RSM、KV 和失败处理
RSM 实现Submit、reader 和等待结果
KV 实现Get/Put 状态机与 Clerk 重试
快照接入业务快照与 Raft 快照协作
测试验收4A–4C 结果

原文逐行翻译

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

<!-- source: lab-kvraft1.html:25 block=0 -->

简介

Introduction

<!-- source: lab-kvraft1.html:27 block=1 -->

In this lab you will build a fault-tolerant key/value storage service using your Raft library from Lab 3.

在本实验中,你将使用 Lab 3 实现的 Raft 库,构建一个容错键值存储服务。

To clients, the service looks similar to the server of Lab 2.

从客户端看,这个服务与 Lab 2 的服务器相似。

However, instead of a single server, the service consists of a set of servers that use Raft to help them maintain identical databases.

不过,它不是单台服务器,而是一组借助 Raft 维护相同数据库的服务器。

Your key/value service should continue to process client requests as long as a majority of the servers are alive and can communicate, in spite of other failures or network partitions.

即使出现其他故障或网络分区,只要多数服务器仍然存活并且能够互相通信,键值服务就应该继续处理客户端请求。

After Lab 4, you will have implemented all parts (Clerk, Service, and Raft) shown in the diagram of Raft interactions.

完成 Lab 4 后,你就实现了 Raft 交互图中的全部部分:Clerk、Service 和 Raft。

<!-- source: lab-kvraft1.html:44 block=2 -->

Clients will interact with your key/value service through a Clerk, as in Lab 2.

客户端会像 Lab 2 一样,通过 Clerk 与键值服务交互。

A Clerk implements the Put and Get methods with the same semantics as Lab 2: Puts are at-most-once and the Puts/Gets must form a linearizable history.

Clerk 实现 Put 和 Get 方法,语义与 Lab 2 相同:Put 至多执行一次,而且 Put/Get 必须形成线性一致的历史。

<!-- source: lab-kvraft1.html:50 block=3 -->

Providing linearizability is relatively easy for a single server.

单台服务器提供线性一致性相对容易。

It is harder if the service is replicated, since all servers must choose the same execution order for concurrent requests, must avoid replying to clients using state that isn't up to date, and must recover their state after a failure in a way that preserves all acknowledged client updates.

复制服务则更困难:所有服务器必须为并发请求选择相同的执行顺序,不能用过期状态回复客户端,而且在故障后恢复状态时,必须保留所有已经向客户端确认的更新。

<!-- source: lab-kvraft1.html:58 block=4 -->

This lab has three parts.

本实验分为三部分。

In part A, you will implement a replicated-state machine package, rsm, using your raft implementation; rsm is agnostic of the requests that it replicates.

A 部分使用你实现的 Raft 编写复制状态机包 rsm;rsm 不需要理解所复制请求的具体含义。

In part B, you will implement a replicated key/value service using rsm, but without using snapshots.

B 部分使用 rsm 实现复制键值服务,暂时不使用快照。

In part C, you will use your snapshot implementation from Lab 3D, which will allow Raft to discard old log entries.

C 部分使用 Lab 3D 的快照实现,让 Raft 能够丢弃旧日志条目。

Please submit each part by the respective deadline.

请在各部分相应的截止日期前提交。

<!-- source: lab-kvraft1.html:68 block=5 -->

You should review the extended Raft paper, in particular Section 7 (but not 8).

你应该复习 Raft 扩展论文,尤其是第 7 节,但不包括第 8 节。

For a wider perspective, have a look at Chubby, Paxos Made Live, Spanner, Zookeeper, Harp, Viewstamped Replication, and Bolosky et al.

如果想获得更广泛的视角,可以阅读 Chubby、Paxos Made Live、Spanner、Zookeeper、Harp、Viewstamped Replication,以及 Bolosky 等人的论文。

<!-- source: lab-kvraft1.html:76 block=6 -->

Start early.

尽早开始。

<!-- source: lab-kvraft1.html:79 block=7 -->

开始实验

Getting Started

<!-- source: lab-kvraft1.html:81 block=8 -->

We supply you with skeleton code and tests in src/kvraft1.

我们在 src/kvraft1 中提供了骨架代码和测试。

The skeleton code uses the skeleton package src/kvraft1/rsm to replicate a server.

骨架代码使用 src/kvraft1/rsm 骨架包来复制服务器。

A server must implement the StateMachine interface defined in rsm to replicate itself using rsm.

服务器必须实现 rsm 定义的 StateMachine 接口,才能使用 rsm 复制自身。

Most of your work will be implementing rsm to provide server-agnostic replication.

你的主要工作是实现 rsm,提供不依赖具体服务器业务的复制功能。

You will also need to modify kvraft1/client.go and kvraft1/server.go to implement the server-specific parts.

你还需要修改 kvraft1/client.go 和 kvraft1/server.go,实现与具体服务器有关的部分。

This split allows you to re-use rsm in the next lab.

这种划分使你能在下一个实验中复用 rsm。

You may be able to re-use some of your Lab 2 code (e.g., re-using the server code by copying or importing the "src/kvsrv1" package) but it is not a requirement.

你可以复用部分 Lab 2 代码,例如通过复制或导入 src/kvsrv1 包复用服务器代码,但这不是强制要求。

<!-- source: lab-kvraft1.html:95 block=9 -->

To get up and running, execute the following commands.

执行下面的命令开始实验。

Don't forget the git pull to get the latest software.

别忘了运行 git pull 获取最新代码。

<!-- source: lab-kvraft1.html:98 block=10 -->
text
$ cd ~/6.5840
$ git pull
..
<!-- source: lab-kvraft1.html:104 block=11 -->

A 部分:复制状态机(RSM)

Part A: replicated state machine (RSM)

<!-- source: lab-kvraft1.html:106 block=12 -->
text
$ cd src
$ make rsm1
=== RUN   TestBasic4A
Test RSM basic (reliable network)...
    rsm_test.go:28: expected 0 instead of 0
<!-- source: lab-kvraft1.html:114 block=13 -->

In the common situation of a client/server service using Raft for replication, the service interacts with Raft in two ways: the service leader submits client operations by calling raft.Start(), and all service replicas receive committed operations via Raft's applyCh, which they execute.

在客户端/服务器服务使用 Raft 进行复制的常见场景中,服务通过两种方式与 Raft 交互:服务 leader 调用 raft.Start() 提交客户端操作,而所有服务副本通过 Raft 的 applyCh 接收并执行已提交的操作。

On the leader, these two activities interact.

这两种活动会在 leader 上相互配合。

At any given time, some server goroutines are handling client requests, have called raft.Start(), and each is waiting for its operation to commit and to find out what the result of executing the operation is.

在任意时刻,可能有一些服务器 goroutine 正在处理客户端请求,已经调用了 raft.Start(),各自等待操作提交并获知执行结果。

And as committed operations appear on the applyCh, each needs to be executed by the service, and the results need to be handed to the goroutine that called raft.Start() so that it can return the result to the client.

当已提交操作出现在 applyCh 上时,服务必须执行每个操作,并把执行结果交给调用 raft.Start() 的 goroutine,让它能够向客户端返回结果。

<!-- source: lab-kvraft1.html:127 block=14 -->

The rsm package encapsulates the above interaction.

rsm 包封装了上述交互。

It sits as a layer between the service (e.g. a key/value database) and Raft.

它是服务(例如键值数据库)与 Raft 之间的一层。

In rsm/rsm.go you will need to implement a "reader" goroutine that reads the applyCh, and a rsm.Submit() function that calls raft.Start() for a client operation and then waits for the reader goroutine to hand it the result of executing that operation.

你需要在 rsm/rsm.go 中实现一个读取 applyCh 的 reader goroutine,以及 rsm.Submit() 函数:后者为客户端操作调用 raft.Start(),然后等待 reader goroutine 返回该操作的执行结果。

<!-- source: lab-kvraft1.html:135 block=15 -->

The service that is using rsm appears to the rsm reader goroutine as a StateMachine object providing a DoOp() method.

在 rsm 的 reader goroutine 看来,使用 rsm 的服务是一个提供 DoOp() 方法的 StateMachine 对象。

The reader goroutine should hand each committed operation to DoOp(); DoOp()'s return value should be given to the corresponding rsm.Submit() call for it to return.

reader goroutine 应将每个已提交操作交给 DoOp();DoOp() 的返回值应交给对应的 rsm.Submit() 调用,再由该调用返回。

DoOp()'s argument and return value have type any; the actual values should have the same types as the argument and return values that the service passes to rsm.Submit(), respectively.

DoOp() 的参数和返回值类型都是 any;实际值的类型应分别对应服务传给 rsm.Submit() 的参数类型,以及服务从它获得的返回值类型。

<!-- source: lab-kvraft1.html:147 block=16 -->

The service should pass each client operation to rsm.Submit().

服务应该把每个客户端操作传给 rsm.Submit()。

To help the reader goroutine match applyCh messages with waiting calls to rsm.Submit(), Submit() should wrap each client operation in an Op structure along with a unique identifier.

为了帮助 reader goroutine 将 applyCh 消息与正在等待的 rsm.Submit() 调用匹配,Submit() 应把每个客户端操作及其唯一标识符包装到 Op 结构体中。

Submit() should then wait until the operation has committed and been executed, and return the result of execution (the value returned by DoOp()).

随后 Submit() 应等待操作提交并执行,再返回执行结果,即 DoOp() 的返回值。

If raft.Start() indicates that the current peer is not the Raft leader, Submit() should return an rpc.ErrWrongLeader error.

如果 raft.Start() 表明当前节点不是 Raft leader,Submit() 应返回 rpc.ErrWrongLeader 错误。

Submit() should detect and handle the situation in which leadership changed just after it called raft.Start(), causing the operation to be lost (never committed).

Submit() 还应检测并处理这种情况:刚调用 raft.Start() 就发生领导权变更,使操作丢失、永远没有提交。

<!-- source: lab-kvraft1.html:164 block=17 -->

For Part A, the rsm tester acts as the service, submitting operations that it interprets as increments on a state consisting of a single integer.

在 A 部分中,rsm 测试器充当服务,提交的操作被解释为对一个整数状态进行递增。

In Part B you'll use rsm as part of a key/value service that implements StateMachine (and DoOp()), and calls rsm.Submit().

在 B 部分中,你会把 rsm 用于键值服务,该服务实现 StateMachine(包括 DoOp()),并调用 rsm.Submit()。

<!-- source: lab-kvraft1.html:171 block=18 -->

If all goes well, the sequence of events for a client request is:

如果一切顺利,一次客户端请求会经历以下事件:

<!-- source: lab-kvraft1.html:173 block=19 -->

The client sends a request to the service leader.

客户端向服务 leader 发送请求。

<!-- source: lab-kvraft1.html:174 block=20 -->

The service leader calls rsm.Submit() with the request.

服务 leader 将该请求传给 rsm.Submit()。

<!-- source: lab-kvraft1.html:175 block=21 -->

rsm.Submit() calls raft.Start() with the request, and then waits.

rsm.Submit() 将请求传给 raft.Start(),然后等待。

<!-- source: lab-kvraft1.html:177 block=22 -->

Raft commits the request and sends it on all peers' applyChs.

Raft 提交请求,并将它发送到所有节点的 applyCh。

<!-- source: lab-kvraft1.html:178 block=23 -->

The rsm reader goroutine on each peer reads the request from the applyCh and passes it to the service's DoOp().

每个节点上的 rsm reader goroutine 从 applyCh 读取请求,并传给服务的 DoOp()。

<!-- source: lab-kvraft1.html:181 block=24 -->

On the leader, the rsm reader goroutine hands the DoOp() return value to the Submit() goroutine that originally submitted the request, and Submit() returns that value.

在 leader 上,rsm reader goroutine 将 DoOp() 的返回值交给最初提交请求的 Submit() goroutine,再由 Submit() 返回该值。

<!-- source: lab-kvraft1.html:188 block=25 -->

Implement rsm.go: the Submit() method and a reader goroutine.

实现 rsm.go:包括 Submit() 方法和 reader goroutine。

You have completed this task if you pass the rsm 4A tests:

通过下面的 rsm 4A 测试,就完成了这个任务:

<!-- source: lab-kvraft1.html:195 block=26 -->
text
  $ cd src
  $ make RUN="-run 4A" rsm1
go build -race -o main/rsm1d main/rsm1d.go
cd kvraft1/rsm; go test -v -race -run 4A 
=== RUN   TestBasic4A
Test RSM basic (reliable network)...
  ... Passed --  time  4.2s #peers 3 #RPCs    50 #Ops   10
--- PASS: TestBasic4A (4.57s)
=== RUN   TestConcurrent4A
Test concurrent submit (reliable network)...
  ... Passed --  time  1.0s #peers 3 #RPCs    28 #Ops   50
--- PASS: TestConcurrent4A (1.39s)
=== RUN   TestLeaderFailure4A
Test Leader Failure (reliable network)...
  ... Passed --  time  2.9s #peers 3 #RPCs    32 #Ops    2
--- PASS: TestLeaderFailure4A (3.29s)
=== RUN   TestLeaderPartition4A
Test Leader Partition (reliable network)...
2026/03/11 10:43:46 partition leader 0
  ... Passed --  time  3.6s #peers 3 #RPCs    61 #Ops    2
--- PASS: TestLeaderPartition4A (4.04s)
=== RUN   TestRestartReplay4A
Test Restart (reliable network)...
  ... Passed --  time 28.4s #peers 3 #RPCs   467 #Ops  101
--- PASS: TestRestartReplay4A (28.79s)
=== RUN   TestShutdown4A
Test Shutdown (reliable network)...
  ... Passed --  time 10.0s #peers 3 #RPCs     0 #Ops    0
--- PASS: TestShutdown4A (10.38s)
=== RUN   TestRestartSubmit4A
Test Restart and submit (reliable network)...
  ... Passed --  time 39.8s #peers 3 #RPCs   463 #Ops  102
--- PASS: TestRestartSubmit4A (40.21s)
PASS
ok  	6.5840/kvraft1/rsm	93.691s
<!-- source: lab-kvraft1.html:235 block=27 -->

You should not need to add any fields to the Raft ApplyMsg, or to Raft RPCs such as AppendEntries, but you are allowed to do so.

你应该不需要给 Raft 的 ApplyMsg 或 AppendEntries 等 Raft RPC 增加字段,不过允许这样做。

<!-- source: lab-kvraft1.html:239 block=28 -->

Your solution needs to handle an rsm leader that has called Start() for a request submitted with Submit() but loses its leadership before the request is committed to the log.

你的方案必须处理这种情况:rsm leader 已经为通过 Submit() 提交的请求调用 Start(),却在请求提交到日志之前失去领导权。

One way to do this is for the rsm to detect that it has lost leadership, by noticing that Raft's term has changed or a different request has appeared at the index returned by Start(), and return rpc.ErrWrongLeader from Submit().

一种办法是让 rsm 通过发现 Raft 的 term 改变,或 Start() 返回的日志位置出现另一条请求,检测到领导权丢失,然后让 Submit() 返回 rpc.ErrWrongLeader。

If the ex-leader is partitioned by itself, it won't know about new leaders; but any client in the same partition won't be able to talk to a new leader either, so it's OK in this case for the server to wait indefinitely until the partition heals.

如果旧 leader 被单独隔离在一个网络分区中,它不会知道新 leader 的存在;但同一分区内的客户端也无法联系新 leader,所以此时服务器无限等待直到分区恢复,是可以接受的。

<!-- source: lab-kvraft1.html:258 block=29 -->

B 部分:不使用快照的键值服务

Part B: Key/value service without snapshots

<!-- source: lab-kvraft1.html:260 block=30 -->
text
$ cd src
$ make RUN="-run 4B" kvraft1
go build -race -o main/kvraft1d main/kvraft1d.go
cd kvraft1 && go test -v -race -run 4B 
=== RUN   TestBasic4B
Test: one client (4B basic) (reliable network)...
Fatal: Wrong error
<!-- source: lab-kvraft1.html:270 block=31 -->

Now you will use the rsm package to replicate a key/value server.

现在你将使用 rsm 包复制一个键值服务器。

Each of the servers ("kvservers") will have an associated rsm/Raft peer.

每台服务器(kvserver)都有对应的 rsm/Raft 节点。

Clerks send Put() and Get() RPCs to the kvserver whose associated Raft is the leader.

Clerk 把 Put() 和 Get() RPC 发送给其 Raft 节点是 leader 的 kvserver。

The kvserver code submits the Put/Get operation to rsm, which replicates it using Raft and invokes your server's DoOp at each peer, which should apply the operations to the peer's key/value database; the intent is for the servers to maintain identical replicas of the key/value database.

kvserver 把 Put/Get 操作提交给 rsm,由它使用 Raft 复制,并在每个节点调用服务器的 DoOp;DoOp 应把操作应用到节点的键值数据库,目的是让服务器维护内容相同的键值数据库副本。

<!-- source: lab-kvraft1.html:280 block=32 -->

A Clerk sometimes doesn't know which kvserver is the Raft leader.

Clerk 有时不知道哪个 kvserver 是 Raft leader。

If the Clerk sends an RPC to the wrong kvserver, or if it cannot reach the kvserver, the Clerk should re-try by sending to a different kvserver.

如果 Clerk 把 RPC 发给了错误的 kvserver,或者无法联系该 kvserver,它应换一个 kvserver 重试。

If the key/value service commits the operation to its Raft log (and hence applies the operation to the key/value state machine), the leader reports the result to the Clerk by responding to its RPC.

如果键值服务把操作提交到 Raft 日志,并因此将其应用到键值状态机,leader 就通过 RPC 响应向 Clerk 报告结果。

If the operation failed to commit (for example, if the leader was replaced), the server reports an error, and the Clerk retries with a different server.

如果操作未能提交,例如 leader 被替换,服务器就报告错误,Clerk 再换一台服务器重试。

<!-- source: lab-kvraft1.html:291 block=33 -->

Your first task is to implement a solution that works when there are no dropped messages, and no failed servers.

你的第一个任务是实现一个在没有消息丢失、没有服务器故障时能够工作的方案。

<!-- source: lab-kvraft1.html:296 block=34 -->

Feel free to copy your client code from Lab 2 (kvsrv1/client.go) into kvraft1/client.go.

你可以把 Lab 2 的客户端代码 kvsrv1/client.go 复制到 kvraft1/client.go。

You will need to add logic for deciding which kvserver to send each RPC to.

你需要增加逻辑,决定每个 RPC 发给哪台 kvserver。

<!-- source: lab-kvraft1.html:301 block=35 -->

You'll also need to implement Put() and Get() RPC handlers in server.go.

你还需要在 server.go 中实现 Put() 和 Get() RPC 处理函数。

These handlers should submit the request to Raft using rsm.Submit().

这些处理函数应通过 rsm.Submit() 把请求提交给 Raft。

As the rsm package reads commands from applyCh, it should invoke the DoOp method, which you will have to implement in server.go.

rsm 从 applyCh 读取命令时,应调用 DoOp 方法;你需要在 server.go 中实现该方法。

<!-- source: lab-kvraft1.html:309 block=36 -->

You have completed this task when you reliably pass the first test in the test suite, with make RUN="-run TestBasic4B" kvraft1.

当运行 make RUN="-run TestBasic4B" kvraft1,能够稳定通过测试套件中的第一个测试时,这个任务就完成了。

<!-- source: lab-kvraft1.html:317 block=37 -->

A kvserver should not complete a Get() RPC if it is not part of a majority (so that it does not serve stale data).

如果 kvserver 不在能够形成多数派的一侧,就不应完成 Get() RPC,以免提供过期数据。

A simple solution is to enter every Get() (as well as each Put()) in the Raft log using Submit().

一种简单办法是使用 Submit() 将每个 Get() 和每个 Put() 都写入 Raft 日志。

You don't have to implement the optimization for read-only operations that is described in Section 8.

你不需要实现论文第 8 节介绍的只读操作优化。

<!-- source: lab-kvraft1.html:325 block=38 -->

It's best to add locking from the start because the need to avoid deadlocks sometimes affects overall code design.

最好从一开始就加入锁,因为避免死锁的要求有时会影响整体代码设计。

The tester runs your code with the race detector by default.

测试器默认启用竞态检测器运行你的代码。

<!-- source: lab-kvraft1.html:330 block=39 -->

Now you should modify your solution to continue in the face of network and server failures.

现在你应该修改方案,让它在网络和服务器故障时也能继续工作。

One problem you'll face is that a Clerk may have to send an RPC multiple times until it finds a kvserver that replies positively.

你会遇到的一个问题是:Clerk 可能必须多次发送 RPC,才能找到一台成功回应的 kvserver。

If a leader fails just after committing an entry to the Raft log, the Clerk may not receive a reply, and thus may re-send the request to another leader.

如果 leader 刚把条目提交到 Raft 日志就故障,Clerk 可能收不到响应,因此会把请求重新发送给另一个 leader。

Each call to Clerk.Put() should result in just a single execution for a particular version number.

对于特定版本号,每次 Clerk.Put() 调用只能导致一次执行。

<!-- source: lab-kvraft1.html:344 block=40 -->

Add code to handle failures.

添加处理故障的代码。

Your Clerk can use a similar retry plan as in lab 2, including returning ErrMaybe if a response to a retried Put RPC is lost.

Clerk 可以使用与 Lab 2 类似的重试方案,包括在重试的 Put RPC 的响应丢失时返回 ErrMaybe。

You are done when your code reliably passes all the 4B tests, with make RUN="-run 4B" kvraft1.

当代码能通过 make RUN="-run 4B" kvraft1 稳定通过全部 4B 测试时,就完成了这一部分。

<!-- source: lab-kvraft1.html:353 block=41 -->

Recall that the rsm leader may lose its leadership and return rpc.ErrWrongLeader from Submit().

请记住,rsm leader 可能失去领导权,让 Submit() 返回 rpc.ErrWrongLeader。

In this case you should arrange for the Clerk to re-send the request to other servers until it finds the new leader.

这时应让 Clerk 把请求重新发给其他服务器,直到找到新 leader。

<!-- source: lab-kvraft1.html:358 block=42 -->

You will probably have to modify your Clerk to remember which server turned out to be the leader for the last RPC, and send the next RPC to that server first.

你可能需要修改 Clerk,让它记住上一次 RPC 找到的 leader,并优先把下一次 RPC 发给该服务器。

This will avoid wasting time searching for the leader on every RPC, which may help you pass some of the tests quickly enough.

这样就不必每次 RPC 都浪费时间寻找 leader,可能有助于在测试规定的时间内完成。

<!-- source: lab-kvraft1.html:369 block=43 -->

Your code should now pass the Lab 4B tests, like this:

现在你的代码应该像下面这样通过 Lab 4B 测试:

<!-- source: lab-kvraft1.html:372 block=44 -->
text
$ cd src
$ make RUN="-run 4B" kvraft1
go build -race -o main/kvraft1d main/kvraft1d.go
cd kvraft1 && go test -v -race -run 4B 
=== RUN   TestBasic4B
Test: one client (4B basic) (reliable network)...
  ... Passed --  time  3.5s #peers 5 #RPCs   395 #Ops  122
--- PASS: TestBasic4B (4.11s)
=== RUN   TestSpeed4B
Test: one client (4B speed) (reliable network)...
  ... Passed --  time 33.4s #peers 3 #RPCs  3291 #Ops 1002
--- PASS: TestSpeed4B (33.80s)
=== RUN   TestConcurrent4B
Test: many clients (4B many clients) (reliable network)...
  ... Passed --  time  4.1s #peers 5 #RPCs   953 #Ops  558
--- PASS: TestConcurrent4B (4.69s)
=== RUN   TestUnreliable4B
Test: many clients (4B many clients) (unreliable network)...
  ... Passed --  time  4.6s #peers 5 #RPCs   685 #Ops  210
--- PASS: TestUnreliable4B (5.22s)
=== RUN   TestOnePartition4B
Test: one client (4B progress in majority) (unreliable network)...
  ... Passed --  time  4.9s #peers 5 #RPCs   231 #Ops    4
Test: no progress in minority (4B) (unreliable network)...
  ... Passed --  time  1.8s #peers 5 #RPCs   110 #Ops    7
Test: completion after heal (4B) (unreliable network)...
  ... Passed --  time  1.1s #peers 5 #RPCs    43 #Ops    4
--- PASS: TestOnePartition4B (8.36s)
=== RUN   TestManyPartitionsOneClient4B
Test: partitions, one client (4B partitions, one client) (reliable network)...
  ... Passed --  time  9.4s #peers 5 #RPCs   520 #Ops  114
--- PASS: TestManyPartitionsOneClient4B (10.08s)
=== RUN   TestManyPartitionsManyClients4B
Test: partitions, many clients (4B partitions, many clients (4B)) (reliable network)...
  ... Passed --  time 16.1s #peers 5 #RPCs  1271 #Ops  558
--- PASS: TestManyPartitionsManyClients4B (16.68s)
=== RUN   TestPersistOneClient4B
Test: restarts, one client (4B restarts, one client 4B ) (reliable network)...
  ... Passed --  time  8.4s #peers 5 #RPCs   311 #Ops   62
--- PASS: TestPersistOneClient4B (9.01s)
=== RUN   TestPersistConcurrent4B
Test: restarts, many clients (4B restarts, many clients) (reliable network)...
  ... Passed --  time  8.5s #peers 5 #RPCs   994 #Ops  350
--- PASS: TestPersistConcurrent4B (9.11s)
=== RUN   TestPersistConcurrentUnreliable4B
Test: restarts, many clients (4B restarts, many clients ) (unreliable network)...
  ... Passed --  time 10.3s #peers 5 #RPCs   672 #Ops  114
--- PASS: TestPersistConcurrentUnreliable4B (10.89s)
=== RUN   TestPersistPartition4B
Test: restarts, partitions, many clients (4B restarts, partitions, many clients) (reliable network)...
  ... Passed --  time 14.3s #peers 5 #RPCs   804 #Ops   94
--- PASS: TestPersistPartition4B (14.95s)
=== RUN   TestPersistPartitionUnreliable4B
Test: restarts, partitions, many clients (4B restarts, partitions, many clients) (unreliable network)...
  ... Passed --  time 22.0s #peers 5 #RPCs  1229 #Ops  102
--- PASS: TestPersistPartitionUnreliable4B (22.64s)
=== RUN   TestPersistPartitionUnreliableLinearizable4B
Test: restarts, partitions, random keys, many clients (4B restarts, partitions, random keys, many clients) (unreliable network)...
  ... Passed --  time 24.1s #peers 7 #RPCs  4464 #Ops  444
--- PASS: TestPersistPartitionUnreliableLinearizable4B (24.94s)
PASS
ok  	6.5840/kvraft1	175.518s
<!-- source: lab-kvraft1.html:437 block=45 -->

The numbers after each Passed are real time in seconds, number of peers, number of RPCs sent (including client RPCs), and number of key/value operations executed (Clerk Get/Put calls).

每个 Passed 后面的数字依次表示:实际耗时(秒)、节点数量、发送的 RPC 数量(包含客户端 RPC),以及执行的键值操作数量(Clerk 的 Get/Put 调用)。

<!-- source: lab-kvraft1.html:443 block=46 -->

C 部分:使用快照的键值服务

Part C: Key/value service with snapshots

<!-- source: lab-kvraft1.html:445 block=47 -->

As things stand now, your key/value server doesn't call your Raft library's Snapshot() method, so a rebooting server has to replay the complete persisted Raft log in order to restore its state.

目前你的键值服务器还没有调用 Raft 库的 Snapshot() 方法,因此重启的服务器必须重放全部持久化 Raft 日志,才能恢复状态。

Now you'll modify kvserver and rsm to cooperate with Raft to save log space and reduce restart time, using Raft's Snapshot() from Lab 3D.

现在你要修改 kvserver 和 rsm,让它们使用 Lab 3D 的 Raft Snapshot() 与 Raft 协作,节省日志空间并缩短重启时间。

<!-- source: lab-kvraft1.html:452 block=48 -->

The tester passes maxraftstate to your StartKVServer(), which passes it to rsm.

测试器将 maxraftstate 传给 StartKVServer(),后者再把它传给 rsm。

maxraftstate indicates the maximum allowed size of your persistent Raft state in bytes (including the log, but not including snapshots).

maxraftstate 表示允许持久化的 Raft 状态最大字节数,包括日志,但不包括快照。

You should compare maxraftstate to rf.PersistBytes().

你应把 maxraftstate 与 rf.PersistBytes() 进行比较。

Whenever your rsm detects that the Raft state size is approaching this threshold, it should save a snapshot by calling Raft's Snapshot.

当 rsm 检测到 Raft 状态大小接近这个阈值时,就应该调用 Raft 的 Snapshot 保存快照。

rsm can create this snapshot by calling the Snapshot method of the StateMachine interface to obtain a snapshot of the kvserver.

rsm 可以调用 StateMachine 接口的 Snapshot 方法,获取 kvserver 的快照。

If maxraftstate is -1, you do not have to snapshot.

如果 maxraftstate 为 -1,就不要求制作快照。

The maxraftstate limit applies to the GOB-encoded bytes your Raft passes as the first argument to persister.Save().

maxraftstate 限制的是 Raft 传给 persister.Save() 第一个参数的 GOB 编码字节。

<!-- source: lab-kvraft1.html:469 block=49 -->

You can find the source for the persister object in tester1/persister.go.

persister 对象的源码位于 tester1/persister.go。

<!-- source: lab-kvraft1.html:473 block=50 -->

Modify your rsm so that it detects when the persisted Raft state grows too large, and then hands a snapshot to Raft.

修改 rsm,使其能检测持久化的 Raft 状态何时过大,并在此时把快照交给 Raft。

When a rsm server restarts, it should read the snapshot with persister.ReadSnapshot() and, if the snapshot's length is greater than zero, pass the snapshot to the StateMachine's Restore() method.

当 rsm 服务器重启时,它应调用 persister.ReadSnapshot() 读取快照;如果快照长度大于零,就把快照传给 StateMachine 的 Restore() 方法。

You complete this task if you pass TestSnapshot4C in rsm.

通过 rsm 中的 TestSnapshot4C,就完成了这个任务。

<!-- source: lab-kvraft1.html:483 block=51 -->
text
$ cd src
$ make RUN="-run 4C" kvraft1
go build -race -o main/kvraft1d main/kvraft1d.go
cd kvraft1 && go test -v -race -run 4C 
=== RUN   TestSnapshotRPC4C
Test: snapshots, one client (4C SnapshotsRPC) (reliable network)...
Test: InstallSnapshot RPC (4C) (reliable network)...
signal: killed
FAIL	6.5840/kvraft1	61.186s
<!-- source: lab-kvraft1.html:496 block=52 -->

Think about when rsm should snapshot its state and what should be included in the snapshot beyond just the server state.

思考 rsm 应在何时制作状态快照,以及除服务器状态以外,快照还应包含什么。

Raft stores each snapshot in the persister object using Save(), along with corresponding Raft state.

Raft 使用 Save(),将每份快照与对应的 Raft 状态一同存入 persister 对象。

You can read the latest stored snapshot using ReadSnapshot().

你可以使用 ReadSnapshot() 读取最近保存的快照。

<!-- source: lab-kvraft1.html:504 block=53 -->

Capitalize all fields of structures stored in the snapshot.

快照中保存的结构体字段都应以大写字母开头。

<!-- source: lab-kvraft1.html:507 block=54 -->

Implement the kvraft1/server.go Snapshot() and Restore() methods, which rsm calls.

实现 kvraft1/server.go 中由 rsm 调用的 Snapshot() 和 Restore() 方法。

Modify rsm to handle applyCh messages that contain snapshots.

修改 rsm,使它能处理包含快照的 applyCh 消息。

<!-- source: lab-kvraft1.html:513 block=55 -->

You may have bugs in your Raft and rsm library that this task exposes.

这个任务可能暴露 Raft 和 rsm 库中的错误。

If you make changes to your Raft implementation make sure it continues to pass all of the Lab 3 tests.

如果修改了 Raft 实现,请确保它仍然能够通过 Lab 3 的全部测试。

<!-- source: lab-kvraft1.html:516 block=56 -->

A reasonable amount of time to take for the Lab 4 tests is 400 seconds of real time and 700 seconds of CPU time.

Lab 4 测试合理的运行时间为实际时间 400 秒、CPU 时间 700 秒。

<!-- source: lab-kvraft1.html:521 block=57 -->

Your code should pass the 4C tests (as in the example here) as well as the 4A+B tests (and your Raft must continue to pass the Lab 3 tests).

你的代码应该通过 4C 测试(如下例),以及 4A 和 4B 测试;Raft 也必须继续通过 Lab 3 测试。

<!-- source: lab-kvraft1.html:524 block=58 -->
text
$ make RUN="-run 4C" kvraft1
go build -race -o main/kvraft1d main/kvraft1d.go
cd kvraft1 && go test -v -race -run 4C 
=== RUN   TestSnapshotRPC4C
Test: snapshots, one client (4C SnapshotsRPC) (reliable network)...
Test: InstallSnapshot RPC (4C) (reliable network)...
  ... Passed --  time  4.8s #peers 3 #RPCs   248 #Ops   72
--- PASS: TestSnapshotRPC4C (5.18s)
=== RUN   TestSnapshotSize4C
Test: snapshots, one client (4C snapshot size is reasonable) (reliable network)...
  ... Passed --  time 21.0s #peers 3 #RPCs  2569 #Ops 1200
--- PASS: TestSnapshotSize4C (21.42s)
=== RUN   TestSpeed4C
Test: snapshots, one client (4C speed) (reliable network)...
  ... Passed --  time 24.9s #peers 3 #RPCs  3208 #Ops 1002
--- PASS: TestSpeed4C (25.32s)
=== RUN   TestSnapshotRecover4C
Test: restarts, snapshots, one client (4C restarts, snapshots, one client) (reliable network)...
  ... Passed --  time  8.2s #peers 5 #RPCs   273 #Ops   50
--- PASS: TestSnapshotRecover4C (8.78s)
=== RUN   TestSnapshotRecoverManyClients4C
Test: restarts, snapshots, many clients (4C restarts, snapshots, many clients ) (reliable network)...
info: linearizability check timed out, assuming history is ok
info: linearizability check timed out, assuming history is ok
info: linearizability check timed out, assuming history is ok
  ... Passed --  time 12.5s #peers 5 #RPCs  3525 #Ops 1670
--- PASS: TestSnapshotRecoverManyClients4C (13.15s)
=== RUN   TestSnapshotUnreliable4C
Test: snapshots, many clients (4C unreliable net, snapshots, many clients) (unreliable network)...
  ... Passed --  time  5.5s #peers 5 #RPCs   773 #Ops  230
--- PASS: TestSnapshotUnreliable4C (6.16s)
=== RUN   TestSnapshotUnreliableRecover4C
Test: restarts, snapshots, many clients (4C unreliable net, restarts, snapshots, many clients) (unreliable network)...
  ... Passed --  time 10.7s #peers 5 #RPCs   804 #Ops   78
--- PASS: TestSnapshotUnreliableRecover4C (11.28s)
=== RUN   TestSnapshotUnreliableRecoverConcurrentPartition4C
Test: restarts, partitions, snapshots, many clients (4C unreliable net, restarts, partitions, snapshots, many clients) (unreliable network)...
  ... Passed --  time 17.4s #peers 5 #RPCs   894 #Ops   94
--- PASS: TestSnapshotUnreliableRecoverConcurrentPartition4C (17.97s)
=== RUN   TestSnapshotUnreliableRecoverConcurrentPartitionLinearizable4C
Test: restarts, partitions, snapshots, random keys, many clients (4C unreliable net, restarts, partitions, snapshots, random keys, many clients) (unreliable network)...
  ... Passed --  time 19.6s #peers 7 #RPCs  2957 #Ops  368
--- PASS: TestSnapshotUnreliableRecoverConcurrentPartitionLinearizable4C (20.45s)
PASS
ok  	6.5840/kvraft1	130.724s

RSM 实现

mermaid
sequenceDiagram
    participant C as Client
    participant S as RSM Submit
    participant R as Raft
    participant A as applyCh reader
    participant M as StateMachine
    C->>S: request
    S->>R: Start(Op{id, request})
    R-->>A: committed ApplyMsg
    A->>M: DoOp(request)
    M-->>A: result
    A-->>S: result for id
    S-->>C: response

本实现用 Op{Me, ID, Req} 标识操作;Submit 为每个等待者保存日志下标和 term。reader 执行命令后按操作 ID 唤醒等待者;如果同一日志下标最终出现了另一个操作,原等待者返回 ErrWrongLeader。

节点重启后 ID 不能从 0 重新开始,否则新请求可能与旧日志中的操作 ID 相同。实现用启动时的时间戳作为 ID 序列起点,避免 reader 把旧操作误认为新请求。

KV 实现

KV 状态是 map[string]rpc.GetReply:值中同时保存字符串和版本号。

  • Get 通过 rsm.Submit 进入日志,键不存在返回 ErrNoKey。
  • Put(key, value, version) 只有在当前版本匹配时更新,写入后版本加一。
  • 第一次明确收到 ErrVersion 时,Put 确定没有执行,返回 ErrVersion。
  • 请求 RPC 丢失后再次遇到 ErrVersion 时,之前的请求可能已经执行,返回 ErrMaybe。
  • 收到 ErrWrongLeader 后也必须保留不确定性:RSM 可能已提交操作,但在返回结果前失去领导权。后续收到 ErrVersion 时应返回 ErrMaybe,不能宣称原请求一定未执行。
  • Clerk 记住最近一次成功的 Leader,并在网络错误或 ErrWrongLeader 后轮询其他节点。

快照接入

mermaid
flowchart LR
    Apply[KV 操作已应用] --> Size{Raft 状态超过阈值?}
    Size -->|否| Continue[继续接收命令]
    Size -->|是| Encode[KV Snapshot]
    Encode --> RaftSnapshot[raft.Snapshot(index, data)]
    RaftSnapshot --> Save[Raft state + KV snapshot]
    Save --> Restart[重启 / InstallSnapshot]
    Restart --> Restore[恢复 KV map]

reader 每次执行命令后检查 PersistBytes();超过 maxraftstate 时调用状态机的 Snapshot(),再调用 raft.Snapshot(commandIndex, snapshot)。RSM 启动时读取 Persister.ReadSnapshot() 并调用 Restore,Raft 后续发送快照或日志尾部时,KV 状态就能保持连续。

测试验收

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

历史阶段结果(非本轮最终验收;最新状态见专栏索引):

  • 4A:基础 RSM、并发、Leader 故障、分区、重启重放、关闭和重启提交全部通过;
  • 4B:基础 KV、速度、并发、不可靠网络、分区、重启和线性一致性测试通过;最后一个随机键线性一致性测试已单独连续 3 次通过;
  • 4C:快照 RPC、快照大小、速度、恢复、不可靠网络、并发分区和随机键线性一致性全部通过;
  • 全部测试使用 -race。

2026-09-19 回归首先在 TestManyPartitionsManyClients4B 发现服务端版本为 193,而客户端只记录 192 次成功、0 次不确定。随后新增 client_regression_test.go,固定“先 ErrWrongLeader、再 ErrVersion”的回复序列:修复前错误返回 ErrVersion,修复后返回 ErrMaybe;直接收到版本冲突仍返回 ErrVersion。测试中的长时间等待发生在后台检查失败之后,不能误诊为单纯性能不足。

修复后,该分区测试连续 3 次通过,总耗时 38.361 秒;重新构建 daemon 后,完整 go test -race -count=1 -v -timeout 6m ./kvraft1 返回 PASS,耗时 210.453 秒。TestSnapshotRecoverManyClients4C 内有 3 次 linearizability check timed out, assuming history is ok 提示;这只是框架超时后接受了历史,并不等同于这些历史获得了完整线性一致性验证。

下一步

下一阶段是 Lab 5 Sharded KV:把 KV 数据按配置分片,在配置切换时迁移 shard,并保证迁移过程中的请求仍然线性一致。

参考资料

← 返回列表
← 上一篇 Lab 3D:快照与日志压缩 下一篇 → Lab 5:分片 KV 与分片迁移

评论 (0)

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