WuKongIM ChannelV2 三节点灾难恢复:写栅栏、数据面租约与自动故障切换全解析
WuKongIM ChannelV2 三节点灾难恢复:写栅栏、数据面租约与自动故障切换全解析
导读:本文围绕 WuKongIM 仓库中的 ChannelV2 灾难恢复实施计划(docs/superpowers/plans/2026-07-02-channelv2-disaster-recovery.md)展开,完整讲解其设计契约、12 个实施任务与落地源码:从持久化写栅栏(Write Fence)、节点级数据面租约(Data-Plane Lease),到 Slot 支撑的手动迁移执行器、有界自动故障切换与副本修复。读完你可以掌握:三节点集群中单数据节点宕机时如何保证已确认消息零丢失(RPO=0)、死 Leader 频道如何恢复写入、存活 Leader 频道如何持续服务、以及新频道在副本数不足时如何 fail-closed。计划中规划的
pkg/channelv2/pkg/clusterv2/internalv2/test/e2ev2在当前仓库中已落地为pkg/channel/pkg/cluster/internal/test/e2e,文中源码与路径均以仓库实际状态为准。
一、计划背景与目标
该计划的目标非常明确:让一个三节点集群在任意一个数据节点失败时,仍然满足以下承诺——
- 已经通过 ChannelV2 quorum 提交并返回 SENDACK 的消息,不丢失任何一条(RPO = 0);
- 死 Leader 频道自动恢复写入能力;
- 存活 Leader 频道在修复期间继续正常服务;
- 新频道放置在健康副本数无法满足配置的副本数时,fail-closed(拒绝创建),而不是降级创建。
计划的总体技术栈为:Go、pkg/channelv2(现 pkg/channel)、pkg/clusterv2/channels(现 pkg/cluster/channels)、pkg/slot/fsm、pkg/db/meta、internalv2/usecase/management(现 internal/usecase/management)、internalv2/access/manager(现 internal/access/manager)、test/e2ev2(现 test/e2e)。
计划的架构主线是严格有序的多阶段实施:
- 先做持久化写栅栏准入(durable write-fence admission);
- 再做节点级数据面租约守卫(node-level data-plane lease guarding);
- 然后是 Slot 支撑的手动迁移执行器(manual migration executors);
- 最后才做有界自动 Leader 故障切换与副本修复(bounded automatic leader failover and replica repair)。
其中最关键的性能约束是:热路径 SEND 必须保持廉价——append 准入只读取本地频道状态和一个节点级租约标志;所有扫描、探测与追齐(catch-up)工作都运行在有界的后台 worker 中,绝不进入 SEND 热路径。
二、设计契约(Scope Check):先立规矩再动手
计划开篇就给出了必须遵守的设计契约,这些契约也是后续所有测试的验收标准:
- N=3,副本数 3,
MinISR=2——这是默认的部署形态与 quorum 语义; - RPO 为 0:凡是已经通过 ChannelV2 quorum 提交、返回过 SENDACK 的消息,在节点故障后必须完整存在;
- 陈旧或隔离的旧 Leader 必须停止接纳写入,手段是 Leader epoch 栅栏(fencing)+ 节点级数据面租约;
- 新频道 fail-closed:当健康候选节点数少于配置的副本数时,禁止创建新频道;
- 降级的存量频道只有在其存活 ISR 仍满足
MinISR时才可继续服务写入; - 自动工作是受限的:有界(bounded)、限速(rate-limited)、可观测(observable),且与 SEND 热路径扫描完全独立。
计划同时强调:不得在栅栏准入、节点租约与手动执行器测试通过之前实现自动故障切换。这是一个"先手动、后自动"的渐进式落地策略——先给运维一个安全可控的手动路径,验证机制可靠后再开放自动修复。
三、任务总览与文件结构
整个计划分为 12 个任务,从底层机制到黑盒验证逐步推进:
| 任务 | 主题 | 关键产物(当前仓库实际路径) |
|---|---|---|
| Task 1 | 持久化写栅栏与 append 准入 | pkg/channel/types.go、pkg/channel/errors.go、pkg/channel/reactor/append.go |
| Task 2 | 节点级数据面租约守卫 | pkg/cluster/channel_lease.go |
| Task 3 | Slot 支撑的迁移存储门面 | pkg/cluster/channels/migration_store.go |
| Task 4 | 运行时探针与排空原语 | pkg/channel/reactor/bench_runtime.go |
| Task 5 | 手动 Leader 转移执行器 | pkg/cluster/channels/migration_executor.go、migration_leader_transfer.go |
| Task 6 | 手动副本替换执行器 | migration_replica_replace.go |
| Task 7 | Manager 手动迁移 API | internal/access/manager/channel_migration.go |
| Task 8 | 自动死 Leader 故障切换 | failover_planner.go、repair_scanner.go |
| Task 9 | 自动副本修复 | repair_planner.go |
| Task 10 | 可观测性与管理快照 | internal/access/manager/channel_runtime_meta.go |
| Task 11 | 三节点 e2e 杀节点黑盒测试 | test/e2e/message/channel_failover/channel_failover_test.go |
| Task 12 | 全量聚焦验证与提交序列 | — |
四、Task 1:持久化写栅栏(Write Fence)与 Append 准入
4.1 为什么需要写栅栏
迁移或故障切换必须能在改变领导权或成员关系之前,先可靠地停掉新写入。如果直接改 Leader 元数据而不先停止写入,就可能出现"两个节点同时认为自己是 Leader 并接受写入"的分裂窗口。写栅栏的本质是:把"禁止新写入"这个状态本身做成持久化的控制面元数据,并通过 Leader epoch 语义防止陈旧节点继续写入。
4.2 栅栏类型定义
计划在 pkg/channelv2/types.go 中定义了栅栏类型,当前仓库实现位于 pkg/channel/types.go:
// WriteFenceReason identifies the control-plane operation that is blocking new writes.
type WriteFenceReason uint8
const (
WriteFenceReasonUnknown WriteFenceReason = iota
WriteFenceReasonLeaderTransfer
WriteFenceReasonReplicaReplace
WriteFenceReasonFailover
)
// WriteFence is durable control-plane metadata that prevents new leader appends.
type WriteFence struct {
Token string
Version uint64
Reason WriteFenceReason
Until time.Time
}
// Set reports whether the authoritative metadata currently fences writes.
func (f WriteFence) Set() bool {
return f.Token != "" && f.Version != 0
}
关键语义:
Token标识是谁(哪个迁移任务)设置了栅栏,只有持有相同 token 的任务才能清除它;Version是栅栏的版本号,参与排空(drain)与 epoch 校验;Reason区分三种控制面操作:Leader 转移、副本替换、自动故障切换;Set()要求 token 与 version 同时有效,避免空 token 误判。
对应地,pkg/channel/errors.go 中新增了错误:
// ErrNotReady reports that a channel is not ready to serve the request.
ErrNotReady = errors.New("channel: not ready")
// ErrStaleMeta reports that a request was fenced by newer channel metadata.
ErrStaleMeta = errors.New("channel: stale meta")
// ErrWriteFenced reports that durable control-plane metadata is blocking new writes.
ErrWriteFenced = errors.New("channel: write fenced")
同时 Meta 结构体(pkg/channel/types.go)中加入了 WriteFence WriteFence 字段,并带注释 "blocks new leader appends while control-plane migration is active"。
4.3 机器状态机:应用栅栏但不清空 in-flight append
一个关键设计是:应用写栅栏元数据时,绝不能清空正在进行的 append 状态。因为已被接受的 in-flight append 由迁移执行器负责排空。计划中的机器级测试精确地锁定了这个行为:
func TestApplyMetaCopiesWriteFenceWithoutClearingInflight(t *testing.T) {
st := newTestLeaderState(t)
st.PendingAppends[1] = ch.AppendBatchRequest{ChannelID: st.ID}
st.InflightAppend = &ch.AppendBatchRequest{ChannelID: st.ID}
meta := testLeaderMeta(st.ID)
meta.WriteFence = ch.WriteFence{
Token: "migration-1",
Version: 7,
Reason: ch.WriteFenceReasonLeaderTransfer,
}
st.ApplyMeta(meta)
require.Equal(t, meta.WriteFence, st.WriteFence)
require.Len(t, st.PendingAppends, 1)
require.NotNil(t, st.InflightAppend)
}
4.4 Reactor 准入:fence + lease 双闸门
在 reactor 的 append 校验路径中(pkg/channel/reactor/append.go),一旦 rc.state.WriteFence.Set() 为真,立即返回 ch.ErrWriteFenced:
if rc.state.WriteFence.Set() {
return ch.ErrWriteFenced
}
对应的 reactor 测试:
func TestValidateAppendEventRejectsWriteFencedLeader(t *testing.T) {
r, rc := newTestLeaderReactorChannel(t)
rc.StateForTest().WriteFence = ch.WriteFence{
Token: "failover-1",
Version: 1,
Reason: ch.WriteFenceReasonFailover,
}
err := r.validateAppendEvent(context.Background(), rc, testAppendEvent(rc))
require.ErrorIs(t, err, ch.ErrWriteFenced)
}
4.5 缓存失效与一次重试
在 pkg/clusterv2/channels/service.go(现 pkg/cluster/channels/service.go)中,本地 append 返回 ch.ErrWriteFenced 时:
- 使频道 meta 缓存失效;
- 重新加载权威 meta 一次;
- 若重载后仍处于 fenced 状态,返回
ch.ErrWriteFenced; - 若重载后栅栏已清除,则重试一次 append。
4.6 错误映射到可重试 usecase 错误
ch.ErrWriteFenced 需要映射为可重试的 usecase 错误。在 internal/infra/cluster/error_map.go 中,它与 ErrNotReady、ErrNoSlotLeader、放置不可用等一起被映射到 channelappend.ErrRouteNotReady:
case errors.Is(err, transport.ErrDialFailed), errors.Is(err, transport.ErrStopped),
errors.Is(err, transport.ErrNodeNotFound), errors.Is(err, cluster.ErrRouteNotReady),
errors.Is(err, cluster.ErrNoSlotLeader),
appendErrorMatches(err, channelruntime.ErrNotReady),
appendErrorMatches(err, channelruntime.ErrWriteFenced),
appendErrorIsChannelPlacementUnavailable(err):
return fmt.Errorf("%w: %w", channelappend.ErrRouteNotReady, err)
聚焦验证命令(计划原文,可在仓库根目录执行):
GOWORK=off go test ./pkg/channelv2/machine ./pkg/channelv2/reactor ./pkg/clusterv2/channels ./internalv2/infra/cluster
对应到当前仓库:
GOWORK=off go test ./pkg/channel/machine ./pkg/channel/reactor ./pkg/cluster/channels ./internal/infra/cluster
五、Task 2:节点级数据面租约守卫(Data-Plane Lease)
5.1 解决的问题
写栅栏解决的是"迁移任务主动停止写入",但还有一个更隐蔽的问题:被隔离的旧 Leader 可能根本没有感知到自己已被隔离(网络分区),它仍然认为自己持有领导权,继续接纳写入,从而产生脑裂。节点级数据面租约解决的就是这个问题:节点只有持续证明自己与权威 Slot/控制面可见性保持新鲜,才允许本地 ChannelV2 Leader 继续接纳写入。
5.2 租约守卫的实现
当前仓库实现位于 pkg/cluster/channel_lease.go:
type channelDataPlaneLeaseFailureReason string
const (
channelDataPlaneLeaseReasonMissing channelDataPlaneLeaseFailureReason = "data_plane_lease_missing"
channelDataPlaneLeaseReasonExpired channelDataPlaneLeaseFailureReason = "data_plane_lease_expired"
channelDataPlaneLeaseReasonClockInvalid channelDataPlaneLeaseFailureReason = "data_plane_lease_clock_invalid"
channelDataPlaneLeaseReasonMaintenance channelDataPlaneLeaseFailureReason = "restore_maintenance"
)
// channelDataPlaneLeaseError preserves the not-ready contract with a stable diagnostic reason.
type channelDataPlaneLeaseError struct {
reason channelDataPlaneLeaseFailureReason
}
func (e *channelDataPlaneLeaseError) Error() string {
return ch.ErrNotReady.Error() + ": " + string(e.reason)
}
func (e *channelDataPlaneLeaseError) Unwrap() error {
return ch.ErrNotReady
}
实现较计划文档有了明显强化:不仅包含"缺失/过期"两种状态,还加入了时钟回拨检测(ClockInvalid)与维护模式开关(Maintenance,恢复期间拒绝本地与转发的 append)。核心逻辑:
func (g *channelDataPlaneLeaseGuard) AllowChannelAppend(ctx context.Context, _ ch.AppendAdmissionRequest) error {
if err := ctx.Err(); err != nil {
return err
}
if g == nil {
return &channelDataPlaneLeaseError{reason: channelDataPlaneLeaseReasonMissing}
}
if g.maintenance.Load() {
return &channelDataPlaneLeaseError{reason: channelDataPlaneLeaseReasonMaintenance}
}
last := g.lastOK.Load()
now := g.now()
if reason := classifyChannelDataPlaneLease(last, g.ttl, now); reason != "" {
return &channelDataPlaneLeaseError{reason: reason}
}
return nil
}
func classifyChannelDataPlaneLease(last *time.Time, ttl time.Duration, now time.Time) channelDataPlaneLeaseFailureReason {
if last == nil {
return channelDataPlaneLeaseReasonMissing
}
age := now.Sub(*last)
if age < 0 {
return channelDataPlaneLeaseReasonClockInvalid
}
if ttl <= 0 || age > ttl {
return channelDataPlaneLeaseReasonExpired
}
return ""
}
MarkVisible(at) 采用单调推进(monotonic CAS),防止延迟上报的旧时间戳覆盖更新的成功观测;同时处理了时钟回拨导致租约"卡死"的边界:如果当前证据在未来且已超过当前时间,就允许用新观测替换,保证守卫 fail-closed 而不会永久卡住。
5.3 Append 准入守卫接口
计划在 ChannelV2 层定义了通用的准入守卫契约,落地于 pkg/channel/types.go:
// AppendAdmissionRequest describes a leader append admission decision.
type AppendAdmissionRequest struct {
ChannelID ChannelID
ChannelKey ChannelKey
Epoch uint64
LeaderEpoch uint64
Leader NodeID
}
// AppendAdmissionGuard can fail closed before a leader append enters the reactor.
type AppendAdmissionGuard interface {
AllowChannelAppend(context.Context, AppendAdmissionRequest) error
}
// AppendAdmissionGuardFunc adapts a function to AppendAdmissionGuard.
type AppendAdmissionGuardFunc func(context.Context, AppendAdmissionRequest) error
它被穿透 pkg/channel/channel.go、pkg/channel/service/service.go、pkg/channel/reactor/group.go 最终注入 reactor。在 pkg/channel/reactor/append.go 中,本地角色/epoch/fence 检查通过后、接纳新 append 之前调用:
if r.appendAdmissionGuard != nil {
err := r.appendAdmissionGuard.AllowChannelAppend(ctx, ch.AppendAdmissionRequest{
ChannelID: rc.state.ID,
ChannelKey: rc.state.Key,
Epoch: rc.state.Epoch,
LeaderEpoch: rc.state.LeaderEpoch,
Leader: rc.state.Leader,
})
if err != nil {
return err
}
}
5.4 租约如何续期
MarkVisible 只在已有的 Slot/控制可见性路径成功之后被调用(位于 pkg/clusterv2/node_loops.go,现 pkg/cluster/node_loops.go 的 health/report 循环中)。也就是说:租约不是独立心跳,而是复用节点健康上报结果——节点只要能持续证明自己与权威集群控制面通信正常,租约就新鲜;一旦失联,租约过期,本地所有 Channel Leader 的 append 都会 fail-closed。
租约的新鲜度时间戳与 TTL 会出现在本地控制快照中(pkg/clusterv2/node_management.go,现 pkg/cluster/node_management.go),供运维查看。聚焦测试命令:
GOWORK=off go test ./pkg/channel/... ./pkg/cluster -run 'TestChannelDataPlaneLeaseGuard|Test.*Admission'
六、Task 3:Slot 支撑的迁移存储门面(MigrationStore)
6.1 设计目标
迁移任务必须是持久化、可恢复的。计划选择复用现有的 Slot FSM 命令体系:pkg/slot/fsm/channel_migration_cmds.go 是命令契约的权威来源。MigrationStore 是一个类型化门面,屏蔽 Slot FSM 细节,对上层(internalv2)只暴露高层语义。
当前仓库实现位于 pkg/cluster/channels/migration_store.go,核心接口定义:
// MigrationCommandProposer submits encoded Channel migration commands to a physical Slot.
type MigrationCommandProposer interface {
ProposeChannelMigrationCommand(ctx context.Context, slotID uint32, hashSlot uint16, command []byte) error
}
// MigrationTaskReader reads migration state from one hash-slot-scoped metadata shard.
type MigrationTaskReader interface {
GetChannelRuntimeMeta(ctx context.Context, hashSlot uint16, channelID string, channelType int64) (metadb.ChannelRuntimeMeta, error)
GetActiveChannelMigrationTask(ctx context.Context, hashSlot uint16, channelID string, channelType int64) (metadb.ChannelMigrationTask, bool, error)
GetChannelMigrationTask(ctx context.Context, hashSlot uint16, channelID string, channelType int64, taskID string) (metadb.ChannelMigrationTask, bool, error)
ListActiveChannelMigrationTasks(ctx context.Context, hashSlot uint16, limit int) ([]metadb.ChannelMigrationTask, error)
}
type MigrationStore struct {
localNode uint64
router PlacementRouter
proposer MigrationCommandProposer
reader MigrationTaskReader
now func() time.Time
ownerTTL time.Duration
fenceTTL time.Duration
}
6.2 关键方法语义
MigrationStore 提供的方法族(当前仓库中均已实现):
func (s *MigrationStore) CreateLeaderTransfer(ctx context.Context, req CreateLeaderTransferRequest) (metadb.ChannelMigrationTask, error)
func (s *MigrationStore) CreateLeaderFailover(ctx context.Context, req CreateLeaderFailoverRequest) (metadb.ChannelMigrationTask, error)
func (s *MigrationStore) CreateReplicaReplace(ctx context.Context, req CreateReplicaReplaceRequest) (metadb.ChannelMigrationTask, error)
func (s *MigrationStore) Claim(ctx context.Context, task metadb.ChannelMigrationTask, expectedVersion int64) error
func (s *MigrationStore) Advance(ctx context.Context, task metadb.ChannelMigrationTask, expectedVersion int64, phase metadb.ChannelMigrationPhase, status metadb.ChannelMigrationStatus, reason string) error
func (s *MigrationStore) CommitLeaderTransfer(ctx context.Context, task metadb.ChannelMigrationTask) error
func (s *MigrationStore) AddLearner(ctx context.Context, task metadb.ChannelMigrationTask) error
func (s *MigrationStore) PromoteLearnerAndRemoveSource(ctx context.Context, task metadb.ChannelMigrationTask) error
func (s *MigrationStore) SetWriteFence(ctx context.Context, task metadb.ChannelMigrationTask, reason ch.WriteFenceReason) error
func (s *MigrationStore) ClearWriteFence(ctx context.Context, task metadb.ChannelMigrationTask) error
func (s *MigrationStore) Abort(ctx context.Context, task metadb.ChannelMigrationTask, reason string) error
几个值得注意的落地细节:
- 运行时守卫(RuntimeGuard):所有创建/推进命令都携带
migrationRuntimeGuard(meta)——包含期望的ChannelEpoch、LeaderEpoch、Leader、WriteFenceToken/Version、RouteGeneration。任何一步发现元数据与期望不符(比如另一个任务已经动了这条频道),命令会被 Slot FSM 拒绝,从而保证并发安全。 - 任务版本守卫(Guard):
Claim/Advance等都要求调用方传入expectedVersion(即任务UpdatedAtMS),并校验ExpectedStatus/Phase/OwnerNodeID/OwnerLeaseUntilMS。版本冲突(metadb.ErrStaleMeta)时执行器会停止本地运行并让其他 worker 继续。 - 租约语义:
Claim写入OwnerNodeID与OwnerLeaseUntilMS(默认 30s,defaultMigrationOwnerTTL);SetWriteFence写入FenceUntilMS(默认 30s,defaultMigrationFenceTTL)。执行器会按需续租、续栅栏。 - 读路径按 hash slot 隔离:所有读取都通过
routing.Route定位到拥有该频道 runtime meta 的 hash slot,杜绝跨槽脏读。
默认值常量:
const (
defaultMigrationOwnerTTL = 30 * time.Second
defaultMigrationFenceTTL = 30 * time.Second
maxMigrationChannelType = int64(^uint8(0))
)
6.3 创建任务的校验
CreateLeaderTransfer 会先读权威 runtime meta 并校验目标:
func validateLeaderTransferTarget(meta metadb.ChannelRuntimeMeta, desiredLeader uint64) error {
if meta.Leader == desiredLeader {
return fmt.Errorf("%w: desired leader is already current leader", ch.ErrInvalidConfig)
}
if !migrationNodeInList(meta.Replicas, desiredLeader) {
return fmt.Errorf("%w: desired leader is not a channel replica", ch.ErrInvalidConfig)
}
if !migrationNodeInList(meta.ISR, desiredLeader) {
return fmt.Errorf("%w: desired leader is not in channel ISR", ch.ErrInvalidConfig)
}
return nil
}
CreateReplicaReplace 校验 source 必须在 Replicas 中、target 必须不在 Replicas 中:
func validateReplicaReplaceTarget(meta metadb.ChannelRuntimeMeta, sourceNode uint64, targetNode uint64) error {
if !migrationNodeInList(meta.Replicas, sourceNode) {
return fmt.Errorf("%w: source node is not a channel replica", ch.ErrInvalidConfig)
}
if migrationNodeInList(meta.Replicas, targetNode) {
return fmt.Errorf("%w: target node is already a channel replica", ch.ErrInvalidConfig)
}
return nil
}
CreateLeaderFailover 还额外校验观测到的 Leader epoch 与权威 meta 兼容(leaderFailoverEpochCompatible),并把观测到的 HW/epoch 写入任务进度(Progress),供后续阶段作为证明依据。
聚焦测试:
GOWORK=off go test ./pkg/cluster/channels -run 'TestMigrationStore'
七、Task 4:运行时探针与排空原语
7.1 运行时探针(Runtime Probe)
迁移执行器需要在不触碰 SEND 热路径的前提下,证明目标节点的就绪状态、追齐状态与旧 Leader 的排空状态。计划扩展了 RuntimeProbeResult,当前落地于 pkg/channel/reactor/bench_runtime.go,探针结果包含:
LeaderEpoch uint64
ChannelEpoch uint64
Role ch.Role
Status ch.Status
LEO uint64
HW uint64
CheckpointHW uint64
WriteFence ch.WriteFence
InflightAppend bool
PendingAppendCount int
落地实现的关键约束(bench_runtime.go):探针从 ChannelState 快照填充,快照拷贝有界,且不为每个 pending append 分配对象——只报告计数与布尔值:
result.Channels = append(result.Channels, ch.RuntimeProbeChannel{
...
InflightAppend: rc.state.InflightAppend != nil,
PendingAppendCount: len(rc.state.PendingAppends),
})
7.2 排空(Drain)
排空是迁移中最关键的一步:在改变领导权之前,确保旧 Leader 上不再有未完成的写工作。服务边界(pkg/channel/reactor/bench_runtime.go):
// DrainChannel waits until a fenced local leader has no admitted append work and HW covers LEO.
func (g *Group) DrainChannel(ctx context.Context, req ch.DrainChannelRequest) (ch.DrainChannelResult, error) {
...
}
DrainChannelRequest 携带 ChannelID、ChannelType、LeaderEpoch、FenceVersion、Timeout;排空通过轮询运行时快照直到同时满足四个条件:
- 频道仍处于请求的 fence version 栅栏之下;
- 不存在 in-flight append;
- pending append 计数为零;
- 本地 Leader 状态满足
HW >= LEO。
若排空期间 Leader epoch 或 fence version 发生变化,返回 ch.ErrStaleMeta,迁移必须中止重来。对应实现(bench_runtime.go):
result.Drained = state.InflightAppend == nil && len(state.PendingAppends) == 0 && state.HW >= state.LEO
聚焦测试:
GOWORK=off go test ./pkg/channel/... -run 'Test.*Probe|Test.*Drain'
八、Task 5:手动 Leader 转移执行器
8.1 阶段顺序
手动 Leader 转移是自动化之前的"安全阀",其阶段顺序被测试严格锁定:
Validate -> ProbeTarget -> SetWriteFence -> DrainOldLeader -> FinalTargetCatchUp -> CommitLeaderMeta -> VerifyNewLeader -> ClearFence -> Completed
8.2 执行器骨架
MigrationExecutor 是统一的任务循环(当前实现较计划文档增加了大量强化细节):
type MigrationExecutor struct {
localNode uint64
source MigrationTaskSource
store MigrationTaskStore
runtime MigrationRuntime
meta RuntimeMetaReader
observer MigrationObserver
clock func() time.Time
taskLimit int
phaseLimit int
progressReader MigrationTaskProgressReader
}
MigrationRuntime 定义了执行器需要的精确操作:
type MigrationRuntime interface {
ProbeChannel(ctx context.Context, nodeID uint64, channelID string, channelType uint8) (ch.RuntimeProbeChannel, error)
DrainChannel(ctx context.Context, nodeID uint64, req ch.DrainChannelRequest) (ch.DrainChannelResult, error)
ApplyChannelMeta(ctx context.Context, nodeID uint64, meta metadb.ChannelRuntimeMeta) error
}
8.3 执行器的工作纪律
RunOnce(ctx) 的关键纪律(当前实现):
- 每次只取一个可运行任务(
ListRunnableMigrationTasks(..., 1)),且只推进本节点 Slot 拥有的活动任务; - 每 tick 的任务数受
TaskLimit约束(默认 1),单次执行受defaultMigrationExecutorTimeout = 5 * time.Second的预算约束; - 若任务 Owner 是其他节点且其 Owner 租约未过期,则跳过(
task.OwnerNodeID != e.localNode && task.OwnerNodeID != 0 && task.OwnerLeaseUntilMS > now); - 版本冲突即放弃:
isMigrationVersionConflict对metadb.ErrStaleMeta返回 true,此时停止本地运行返回 nil,让其他 worker 继续; - 只有
LeaderFailover任务允许多阶段推进(FailoverPhaseLimit,最大 8),手动 Leader 转移与副本替换每 tick 只推进一个阶段(保持异步边界,避免长时间霸占调度); shouldRenewMigrationFence会在排空/追齐/提交阶段过期前自动续栅栏,防止栅栏中途失效导致旧 Leader 恢复写入。
阶段实现(migration_leader_transfer.go)逐一落实计划的九步:
- Validate:source 是当前 meta Leader、target 在
Replicas与ISR中、MinISR满足、当前没有属于其他活动任务的栅栏; - ProbeTarget:目标运行时
ChannelEpoch一致、当前LeaderEpoch一致、状态 ready、HW >= meta.MaxMessageSeq; - SetWriteFence:以任务 token +
WriteFenceReasonLeaderTransfer写入持久栅栏; - DrainOldLeader:以任务 fence version 对旧 Leader 执行
DrainChannel; - FinalTargetCatchUp:再次探测目标,要求
HW >= oldLeaderDrain.LEO; - CommitLeaderMeta:通过既有 Slot 命令更新
Leader=target、LeaderEpoch+1,保持Replicas/ISR/ChannelEpoch不变(落地为CommitLeaderTransfer,附运行时守卫); - VerifyNewLeader:探测目标直到它报告新
LeaderEpoch下的 Leader 角色; - ClearFence:只清除任务 token 拥有的栅栏;
- Completed:推进任务状态并记录新旧 Leader。
每个阶段推进都携带期望任务版本;版本冲突时停止本地运行返回 nil。
8.4 观察者事件
执行器通过 MigrationObserver 输出低基数事件(migration_executor.go):
type MigrationObserver interface {
MigrationActiveTasks(count int)
MigrationPhase(taskID string, taskType metadb.ChannelMigrationKind, phase metadb.ChannelMigrationPhase, status metadb.ChannelMigrationStatus, reason string)
MigrationDuration(taskType metadb.ChannelMigrationKind, phase metadb.ChannelMigrationPhase, d time.Duration)
MigrationBlocked(reason string)
WriteFenceActive(count int)
WriteFenceDuration(taskID string, fenceVersion uint64, d time.Duration)
}
聚焦测试:
GOWORK=off go test ./pkg/cluster/channels -run 'TestLeaderTransfer|TestMigrationExecutor'
九、Task 6:手动副本替换执行器
9.1 阶段顺序
副本替换用于在保持 MinISR 与 quorum 安全提交的前提下,替换一个失败或下线的副本。阶段顺序:
Validate -> TransferLeaderIfSourceIsLeader -> AddLearner -> BootstrapTarget -> WarmCatchUp -> SetWriteFence -> FinalCatchUp -> PromoteLearnerAndRemoveSource -> VerifyMembership -> ClearFence -> Completed
9.2 关键实现
落地于 migration_replica_replace.go,与存储层方法一一对应:
- Validate:source 在
Replicas中、target 健康且不在Replicas中、无活动任务占用该频道; - TransferLeaderIfSourceIsLeader:若 source 恰是 Leader,先内嵌执行一次 Leader 转移(到 ISR 幸存者),再继续替换;
- AddLearner:用既有 Slot 命令把 target 加为 learner / 非投票副本(落地
AddLearner,进入BootstrapTarget阶段); - BootstrapTarget:从权威频道日志前缀启动 target 复制;
- WarmCatchUp:探测 target 直到落后量低于配置的最终追齐阈值(进入
CutoverFence阶段); - SetWriteFence:以
WriteFenceReasonReplicaReplace停止新写入; - FinalCatchUp:要求 target
HW >= meta.MaxMessageSeq; - PromoteLearnerAndRemoveSource:用 promote/remove 命令原子更新 Replicas 与 ISR(落地
PromoteLearnerAndRemoveSource,进入VerifyMembership阶段); - VerifyMembership:探测 target 与至少
MinISR个幸存者在新 meta 下正常; - ClearFence:清除任务拥有的栅栏;
- Completed:记录 source 与 target。
9.3 fail-closed 放置纪律
计划强调:若健康替换候选少于所需数量,不得减少副本数、不得降低 MinISR——任务进入 blocked 状态,reason 为 no_healthy_replacement。这条纪律由 repair 规划器(Task 9)与副本替换执行器共同保障。
聚焦测试:
GOWORK=off go test ./pkg/cluster/channels -run 'TestReplicaReplace|TestLeaderTransfer|TestMigrationExecutor'
十、Task 7:Manager 手动迁移 API
10.1 Usecase 层
在自动化修复启用之前,运维需要一个安全的手动路径。internalv2/usecase/management/channel_migration.go(现 internal/usecase/management/channel_migration.go)定义 usecase:
type ChannelMigrationUsecase struct {
store ChannelMigrationStore
}
type LeaderTransferInput struct {
ChannelID string
ChannelType uint8
TargetNode uint64
}
type ReplicaReplaceInput struct {
ChannelID string
ChannelType uint8
SourceNode uint64
TargetNode uint64
}
设计纪律:所有校验都放在 usecase 层,与入口无关;HTTP handler 只负责解码、调用 usecase、编码。
10.2 HTTP 端点
Manager handler 落地于 internal/access/manager/channel_migration.go,路由注册在 internal/access/manager/server.go:
POST /manager/channel-migrations/leader-transfer
POST /manager/channel-migrations/replica-replace
GET /manager/channel-migrations/active
GET /manager/channel-migrations/:task_id
POST /manager/channel-migrations/:task_id/abort
(注:计划文档中写作 /api/v2/channel-migrations/...,当前仓库 Manager 路由统一挂在 /manager 前缀下。)
请求体(channel_migration.go):
type ChannelMigrationRequest struct {
ChannelID string `json:"channel_id"`
ChannelType uint8 `json:"channel_type"`
SourceNode uint64 `json:"source_node,omitempty"`
TargetNode uint64 `json:"target_node"`
TaskID string `json:"task_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
成功请求返回 202 Accepted,响应包含 task_id、channel_id、channel_type、kind、status、phase、source_node、target_node、desired_leader、blocker_message、last_error 等字段(ChannelMigrationResponse)。
10.3 频道运行时元数据扩展
internalv2/access/manager/channel_runtime_meta.go(现 internal/access/manager/channel_runtime_meta.go)的响应新增字段,让运维能直接看到栅栏与降级状态:
WriteFenceToken string `json:"write_fence_token,omitempty"`
WriteFenceVersion uint64 `json:"write_fence_version,omitempty"`
WriteFenceReason string `json:"write_fence_reason,omitempty"`
ActiveTaskID string `json:"active_task_id,omitempty"`
Degraded bool `json:"degraded"`
DegradedReason string `json:"degraded_reason,omitempty"`
聚焦测试:
GOWORK=off go test ./internal/usecase/management ./internal/access/manager -run 'Test.*ChannelMigration|Test.*ChannelRuntimeMeta'
十一、Task 8:自动死 Leader 故障切换规划器与调度器
11.1 故障切换决策
当某个频道的当前 ChannelV2 Leader 变得陈旧、缺失、宕机、被移除、正在离开或运行时未就绪时,自动调度器接管。规划器输出明确的决策结构(failover_planner.go):
type FailoverAction uint8
const (
FailoverActionNone FailoverAction = iota
FailoverActionCreateLeaderTransfer
FailoverActionBlocked
)
type FailoverDecision struct {
Action FailoverAction
TargetNode uint64
BlockReason string
ObservedHW uint64
ObservedEpoch uint64
}
阻塞原因常量:
const (
failoverBlockActiveMigration = "active_migration"
failoverBlockNoSafeCandidate = "no_safe_candidate"
failoverBlockTargetLagging = "target_lagging"
)
11.2 候选者要求
规划器(Plan)对每个候选者逐一检查:
- 节点在控制状态中健康且活跃;
- 节点在当前
ISR中; - 节点运行时探针报告相同的
ChannelEpoch; - 节点运行时探针报告的
LeaderEpoch满足迁移证明规则(当前或紧邻前序); - 节点
HW >= meta.MaxMessageSeq,否则记录target_lagging; - 候选者没有低于安全前缀的 pending 截断(
PendingTruncationBelowSafePrefix为 false)。
选优逻辑:在所有健康 ISR 候选中,选 HW 最高者;HW 相同时比较 CheckpointHW。若 RequiredHW > 0 且所有候选 HW 不足,则记录观测到的最高 HW 并返回 blocked(reason target_lagging);没有任何合格候选则返回 no_safe_candidate;频道已有活动迁移任务则直接返回 active_migration。
11.3 修复扫描器(RepairScanner)
调度器落地于 repair_scanner.go,其配置结构:
type RepairScannerConfig struct {
Enabled bool
PageLimit int
MaxPagesPerTick int
MaxTasksPerTick int
Observer RepairObserver
TickInterval time.Duration
}
默认值:
const (
defaultRepairScannerPageLimit = 100
defaultRepairScannerMaxPagesPerTick = 1
defaultRepairScannerMaxTasksPerTick = 1
)
扫描纪律:
- 只扫描本地 Slot Leader 拥有的 hash slot(
LocalLeaderSlotIDs); - 使用有界页大小 + 最大页数推进游标(
ListRepairScannerRuntimeMetaPage+ 每槽游标,Slot 失去领导权即丢弃游标); lastSlot轮转页准入,防止大 Slot 或失败 Slot 饿死其他 Slot;- 已有活动迁移任务的频道抑制重复工作(
ActiveChannelMigrationInHashSlot); - blocked 原因只记录不建任务(
RepairScannerBlocked列表); - 遵守每节点/每槽限速。
死 Leader 的调度动作序列:
- 从有界页读取
ChannelRuntimeMeta; - 用控制节点健康、节点状态、运行时探针错误或 lease-ready=false 识别陈旧 Leader;
- 调用故障切换规划器;
- 创建
WriteFenceReasonFailover的 leader-transfer/failover 任务(CreateLeaderFailover,携带观测 HW/epoch 证明); - 交给既有迁移执行器推进各阶段。
扫描结果与观察者回调(repair_scanner.go):
type RepairObserver interface {
RepairScanPages(pages int)
RepairScanBacklog(backlog int)
FailoverResult(result string)
ReplicaRepairResult(result string)
}
计划还要求:若新增 WK_ 配置项,需在配置结构体上加英文注释、在 wukongim.conf.example 中给出默认值,且默认关闭自动故障切换,直到 e2ev2 覆盖通过。
聚焦测试:
GOWORK=off go test ./pkg/cluster/channels -run 'TestFailover|TestRepairScanner'
十二、Task 9:自动副本修复规划器
12.1 修复决策
当数据节点宕机/移除/离开导致副本数不足时,自动恢复副本数,但不降低 MinISR。规划器落地于 repair_planner.go:
type ReplicaRepairAction uint8
const (
ReplicaRepairActionNone ReplicaRepairAction = iota
ReplicaRepairActionCreateReplicaReplace
ReplicaRepairActionWaitForLeaderFailover
ReplicaRepairActionBlocked
)
type ReplicaRepairDecision struct {
Action ReplicaRepairAction
SourceNode uint64
TargetNode uint64
BlockReason string
Degraded bool
Writable bool
}
阻塞原因:
const (
replicaRepairBlockActiveMigration = "active_migration"
replicaRepairBlockNoHealthyReplacement = "no_healthy_replacement"
replicaRepairBlockMinISRNotMet = "min_isr_not_met"
)
12.2 决策逻辑
Plan 的核心逻辑:
- 仅对
StatusActive的频道决策; degraded= ISR 数量小于 Replicas 数量,或存在不健康副本;writable=MinISR <= 0或健康 ISR 数量>= MinISR;- 若已有活动迁移任务 → blocked(
active_migration); - 若无病态副本 → 无动作;
- 若病态副本恰是 Leader → 先等 Leader 故障切换(
WaitForLeaderFailover),Leader 恢复优先于副本替换; - 若不满足可写条件 → blocked(
min_isr_not_met); - 若无健康替换目标 → blocked(
no_healthy_replacement); - 否则创建副本替换任务(
CreateReplicaReplace)。
12.3 放置一致性纪律
计划特别强调:副本修复的候选策略必须与新频道创建时的放置策略一致。如果放置层目前会用少于配置副本数的副本创建频道,必须改为返回可重试的放置错误并补单元测试——保证"新建频道 fail-closed"不是一句空话。
聚焦测试:
GOWORK=off go test ./pkg/cluster/channels -run 'TestReplicaRepair|TestRepairScanner|TestFailover'
十三、Task 10:可观测性、管理快照与 FLOW 文档
计划要求增加低基数(low-cardinality)指标或观察者事件,全部可在当前仓库的 MigrationObserver/RepairObserver 回调中对应找到:
channelv2_migration_active_tasks -> MigrationActiveTasks(count)
channelv2_migration_phase_duration_seconds -> MigrationDuration(kind, phase, d)
channelv2_migration_blocked_total{reason} -> MigrationBlocked(reason)
channelv2_write_fence_active -> WriteFenceActive(count)
channelv2_write_fence_duration_seconds -> WriteFenceDuration(taskID, fenceVersion, d)
channelv2_repair_scan_pages_total -> RepairScanPages(pages)
channelv2_repair_scan_backlog -> RepairScanBacklog(backlog)
channelv2_failover_total{result} -> FailoverResult(result)
channelv2_replica_repair_total{result} -> ReplicaRepairResult(result)
channelv2_data_plane_lease_ready -> channelDataPlaneLeaseSnapshot.ready
Manager 的节点/频道运行时面需要让运维区分八种状态:Slot Leader、ChannelV2 数据 Leader、优选 Leader、实际运行时角色、活动迁移任务、写栅栏状态、数据面租约新鲜度、降级原因——分别由频道 runtime meta JSON 字段(write_fence_token、active_task_id、degraded 等)与节点控制快照(租约时间戳/TTL)承载。
此外需要更新受影响的 FLOW.md(pkg/channel/FLOW.md、pkg/cluster/FLOW.md、pkg/cluster/channels/FLOW.md 等),纳入新操作顺序:write fence → drain → commit meta → verify → clear fence。
全量聚焦验证:
GOWORK=off go test ./pkg/cluster ./pkg/cluster/channels ./internal/usecase/management ./internal/access/manager
十四、Task 11:三节点 e2e 杀节点黑盒测试
14.1 两个验收用例
计划的最终验收是用真实 wukongimv2 二进制证明用户场景。当前仓库落地于 test/e2e/message/channel_failover/channel_failover_test.go(带 //go:build e2e 构建标签):
用例一 TestChannelThreeNodeLeaderFailoverAfterNodeKill(对应计划中的 TestChannelV2ThreeNodeLeaderFailoverAfterNodeKill):
- 启动三节点集群(ChannelV2 启用、副本数 3);
- 创建足够多频道,确保每个节点都领导一部分频道;
- 发消息直到每个选中频道至少有一条 SENDACK;
- 记录已确认消息 ID 与频道序列号;
- 杀掉当前领导至少一个选中频道的节点;
- 等待 Manager/指标面显示受影响频道迁移完成;
- 向同一批频道继续发消息;
- 读回历史,断言每条 kill 前 SENDACK 消息恰好出现一次;
- 断言故障切换后的消息获得 SENDACK 且频道序列号单调递增;
- 断言 Leader 未被杀的频道在修复期间持续接受消息。
测试中还强化了"修复期间未受影响频道继续服务"(unaffectedDuringRepair 序列号必须大于修复前)与"旧 Leader 重启后仍能接续写入且序列号递增"(afterRestart.Seq > afterFailover.Seq),并配套 requireMessageOnceEventually 逐条核对历史。
用例二 TestChannelNewPlacementFailsClosedWhenReplicaCountUnavailable:
- 启动三个节点、副本数 3;
- 杀掉一个节点;
- 创建新频道或向新频道发首条消息;
- 断言放置返回可重试的 not-ready / placement-unavailable;
- 重启节点;
- 断言新放置恢复为三个副本成功。
测试纪律:长时间等待一律走既有 e2e suite 的轮询辅助函数(requireNodeUnschedulableEventually、sendGroupMessageWithin 等),不使用固定 sleep,仅保留套件已接受的有限重试间隔。快速恢复参数示例(channel_failover_test.go):
const (
fastRecoveryHealthReportInterval = 500 * time.Millisecond
fastRecoveryHealthReportTTL = 5 * time.Second
)
聚焦运行:
GOWORK=off go test ./test/e2e/message/channel_failover -run 'TestChannelThreeNodeLeaderFailoverAfterNodeKill|TestChannelNewPlacementFailsClosedWhenReplicaCountUnavailable' -count=1
十五、Task 12:全量聚焦验证与提交序列
计划收尾要求以证据闭环并避免隐藏无关改动:
GOWORK=off go test \
./pkg/channel/... \
./pkg/cluster \
./pkg/cluster/channels \
./internal/infra/cluster \
./internal/usecase/management \
./internal/access/manager
再跑聚焦 e2e 测试,检查工作树(git status --short),然后按可评审切片提交:
git add pkg/channel pkg/cluster internal wukongim.conf.example
git commit -m "feat: add channel write fencing and lease admission"
git add pkg/cluster/channels internal/usecase/management internal/access/manager
git commit -m "feat: add channel migration executor"
git add pkg/cluster/channels internal pkg/metrics docs
git commit -m "feat: add channel automatic repair"
git add test/e2e/message/channel_failover/channel_failover_test.go
git commit -m "test: cover channel node failure recovery"
每个提交只包含相关改动并通过其聚焦验证。
十六、自检清单:机制正确性的最终防线
计划附带的 Self-Review Checklist 可作为任何同类实现的自检模板:
- [ ] 栅栏元数据持久化、投影、强制生效,且绝不由本地墙钟过期单独清除;
- [ ] 节点数据面租约阻止陈旧隔离 Leader,无需按频道逐条续约;
- [ ] 自动故障切换启用前,手动 Leader 转移可用;
- [ ] 自动副本修复启用前,手动副本替换可用;
- [ ] 自动扫描受 Slot 归属、页上限、最大页数、任务上限约束;
- [ ] 健康候选不足时新放置 fail-closed;
- [ ] 存量降级频道不降低
MinISR; - [ ] Manager 面展示精确的阻塞原因,并区分 Slot 领导权与 ChannelV2 领导权;
- [ ] e2e 用真实二进制证明三节点杀节点恢复;
- [ ] 所有
FLOW.md与wukongim.conf.example与代码行为一致。
十七、仓库落地验证与深入阅读指引
计划文档中的 pkg/channelv2、pkg/clusterv2、internalv2、test/e2ev2 路径在当前仓库中以 pkg/channel、pkg/cluster、internal、test/e2e 落地,核心机制全部有对应实现与测试,可对照验证:
值得进一步阅读的关联设计文档:docs/superpowers/specs/2026-07-02-channelv2-ha-design.md(ChannelV2 高可用设计)以及 docs/superpowers/plans/2026-05-11-channel-replica-migration.md(副本迁移的前置规划)。运维侧若需查看配置与监控面板,可参考 docker/observability/grafana/dashboards/wukongim-v2-runtime-ops.json 与 wukongim.conf.example(当前仓库中的实际配置文件为 wukongim.toml.example 与 cmd/wukongim/wukongim.toml.example)。
结语
ChannelV2 三节点灾难恢复方案的核心方法论可以概括为四句话:先立栅栏(持久化写栅栏停止新写入)、再断脑裂(节点级数据面租约阻止陈旧 Leader)、后手动(Slot 支撑的迁移执行器提供受控路径)、终自动(有界扫描 + 规划器 + 执行器的自动修复闭环)。而这一切都以 RPO=0、MinISR 保护、fail-closed 放置三条硬约束为边界,以"自动工作绝不进入 SEND 热路径"为性能底线。这套"先手动验证、后自动开启"的渐进式落地顺序,对任何追求数据安全与运维可控性的分布式系统都有直接的借鉴价值。