Cosmos SDK 原地存储迁移(ADR-041)深度解析:从 JSON 导出到 In-Place Store Migrations 的升级方案
Cosmos SDK 原地存储迁移(ADR-041)深度解析:从 JSON 导出到 In-Place Store Migrations 的升级方案
导读
本篇文章围绕 Cosmos SDK 架构决策文档 ADR-041(In-Place Store Migrations)展开,系统讲解该框架如何用「原地状态存储迁移」替代传统的「JSON 导出-脚本迁移-重新导入」升级流程。读者将掌握 ConsensusVersion 模块共识版本机制、RegisterMigration 迁移函数注册、VersionMap 版本追踪、RunMigrations 执行引擎与 x/upgrade 升级处理器(UpgradeHandler)的完整配合方式,并可直接参考 simapp 中的落地实现为自己的链应用升级方案。
一、背景:传统 JSON 迁移流程及其痛点
在 ADR-041 之前,当一次链升级引入了模块内的状态破坏性变更(state-breaking changes)时,标准流程是:
- 在旧二进制上执行
simd export,将全链状态导出为 JSON 文件; - 用
simd genesis migrate对 JSON 文件运行迁移脚本; - 用
simd unsafe-reset-all清空所有 KV store; - 以迁移后的 JSON 作为新创世文件启动新链(可选用自定义初始区块高度)。
这套流程存在两个突出问题(见 ADR-041 Context):
- 耗时长:
export命令可能耗时数小时,随后在新链上用迁移后的 JSON 执行InitChain还要再花数小时; - 文件体积大:导出 JSON 可达 100MB~1GB,查看、编辑、传输都很困难,还催生了诸如流式创世(streaming genesis)之类的额外工作。
因此该 ADR 提出:直接在 KV store 上原地修改数据,彻底绕开 JSON 导出-处理-导入这一环节,这就是 In-Place Store Migrations(原地存储迁移)。
二、模块共识版本:ConsensusVersion
迁移的触发依据是每个模块的"共识版本"。ADR 在 AppModule 接口上新增一个方法(在当前代码库中体现为独立的扩展接口 HasConsensusVersion,见 types/module/module.go):
// HasConsensusVersion is the interface for declaring a module consensus version.
type HasConsensusVersion interface {
// ConsensusVersion is a sequence number for state-breaking change of the
// module. It should be incremented on each consensus-breaking change
// introduced by the module. To avoid wrong/empty versions, the initial version
// should be set to 1.
ConsensusVersion() uint64
}
关键约束:
ConsensusVersion()返回一个uint64,表示该模块的状态破坏性版本号;- 模块每引入一次共识破坏性变更,必须递增该版本号;
- 为避免零值误判,模块初始版本必须设为 1(在 Cosmos SDK 中,版本 1 对应 v0.41 系列模块的初始状态)。
以当前仓库的 x/auth 为例(见 x/auth/module.go):
const (
ConsensusVersion = 7
GovModuleName = "gov"
)
而 x/upgrade 自身的 ConsensusVersion 也在 x/upgrade/module.go 中实现。可以看到,历经多轮状态演进后,模块的共识版本号已从 1 逐步递增(如 x/auth 到 7、x/bank 到 4),这正是 ADR-041 机制长期运转的结果。
三、模块级迁移函数:RegisterMigration 与 Migrator
3.1 在 Configurator 中注册迁移
每个共识破坏性变更都需要一个从 N 到 N+1 的迁移脚本。ADR 规定这些脚本必须在模块的 RegisterServices 方法中、通过 Configurator 新增的 RegisterMigration 方法按递增顺序注册:
func (am AppModule) RegisterServices(cfg module.Configurator) {
// --snip--
cfg.RegisterMigration(types.ModuleName, 1, func(ctx sdk.Context) error {
// Perform in-place store migrations from ConsensusVersion 1 to 2.
})
cfg.RegisterMigration(types.ModuleName, 2, func(ctx sdk.Context) error {
// Perform in-place store migrations from ConsensusVersion 2 to 3.
})
// etc.
}
由此推出规则:若模块新共识版本为 N,则必须注册 N-1 个迁移函数(分别覆盖 1→2、2→3 … N-1→N)。
3.2 接口定义与校验逻辑
RegisterMigration 的接口定义位于 types/module/configurator.go:
RegisterMigration(moduleName string, fromVersion uint64, handler MigrationHandler) error
其底层实现有两个值得注意的校验:
- 版本不能为 0:
if fromVersion == 0 { return ... "module migration versions should start at 1" },确保与"初始版本为 1"的约定一致; - 禁止重复注册:同一模块同一
fromVersion只能注册一次,否则返回ErrLogic错误。
此外注释中明确:如果 ConsensusVersion 递增但未引入任何 store 变更,则必须注册一个 no-op 空函数;若缺少某个版本的迁移处理器,升级逻辑(RunMigrations)会报错中断。
3.3 Migrator 包装器与 Migrate{M}to{N} 命名
ADR 指出:迁移函数由各模块的 keeper 持有(因为 keeper 拥有执行原地迁移所需的 sdk.StoreKey)。为了不让 keeper 过度膨胀,引入 Migrator 包装结构体。当前仓库中 x/auth 的实践(见 x/auth/keeper/migrations.go):
// Migrator is a struct for handling in-place store migrations.
type Migrator struct {
keeper AccountKeeper
queryServer grpc.Server
}
// NewMigrator returns a new Migrator.
func NewMigrator(keeper AccountKeeper, queryServer grpc.Server) Migrator {
return Migrator{keeper: keeper, queryServer: queryServer}
}
迁移函数以 Migrate{M}to{N} 命名。x/auth 在 RegisterServices 中把 Migrator 方法与 Configurator 绑定:
m := keeper.NewMigrator(am.accountKeeper, cfg.QueryServer())
if err := cfg.RegisterMigration(types.ModuleName, 5, m.Migrate5to6); err != nil {
panic(fmt.Sprintf("failed to migrate x/%s from version 5 to 6: %v", types.ModuleName, err))
}
if err := cfg.RegisterMigration(types.ModuleName, 6, m.Migrate6to7); err != nil {
panic(fmt.Sprintf("failed to migrate x/%s from version 6 to 7: %v", types.ModuleName, err))
}
而 x/upgrade 模块同样用 Migrator 注册 1→2 迁移(见 x/upgrade/module.go)。
3.4 迁移实现存放位置
ADR 建议迁移实现代码放在各模块的 migrations/ 目录下,并在 Migrate{M}to{N} 方法中调用。本仓库中 x/auth 即按此约定组织:x/auth/migrations/v6、x/auth/migrations/v7。例如 x/auth/migrations/v7/migrate.go 负责 v6→v7 迁移——为 Params 增加 SigVerifyCostMlDsa65 字段(该迁移有配套的 migrate_test.go 验证:先将字段置 0,迁移后恢复默认值)。
需要说明:ADR 撰写时引用的 x/bank/legacy/v043 目录在当前版本仓库中已不复存在(x/bank 已全面重构为 cosmossdk.io/collections 风格),当前 x/bank 的 store key 布局可见 x/bank/types/keys.go(如 BalancesPrefix、SendEnabledPrefix、DenomMetadataPrefix 等),其迭代演进正是 ADR-028 长度前缀地址等变更推动 store 迁移的成果。各模块的具体迁移逻辑因 store 演化而异,不属于本 ADR 的讨论范围。
四、在 x/upgrade 中追踪模块版本:VersionMap
4.1 存储设计与键值格式
ADR 在 x/upgrade 的 store 中引入一个新的前缀用于记录每个模块的当前版本,逻辑上等价于 map[string]uint64(模块名 → 模块共识版本)。
需要特别注意:ADR 正文中给出的前缀描述与实际最终实现存在差异。ADR 文中写"key prefix used is 0x1",但格式示例中又写作 0x2 | {bytes(module_name)} => BigEndian(module_consensus_version);而当前仓库 x/upgrade/types/keys.go 的实际常量是:
const (
// PlanByte specifies the Byte under which a pending upgrade plan is stored in the store
PlanByte = 0x0
// DoneByte is a prefix to look up completed upgrade plan by name
DoneByte = 0x1
// VersionMapByte is a prefix to look up module names (key) and versions (value)
VersionMapByte = 0x2
// ProtocolVersionByte is a prefix to look up Protocol Version
ProtocolVersionByte = 0x3
)
即以 VersionMapByte = 0x2 作为模块版本映射的前缀,键值格式为:
0x2 | {bytes(module_name)} => BigEndian(module_consensus_version)
这与 ADR 中的格式示例一致(读者在阅读历史版本资料时应以 keys.go 的实现为准)。
4.2 读写实现
x/upgrade keeper 提供一对读写方法(见 x/upgrade/keeper/keeper.go):
SetModuleVersionMap(ctx, vm):遍历VersionMap,对模块名排序后,以BigEndian编码版本值写入前缀0x2之下,保证确定性的遍历顺序;GetModuleVersionMap(ctx):迭代0x2前缀下的全部键值,还原为module.VersionMap(键去掉首字节前缀,值用binary.BigEndian.Uint64解码)。
VersionMap 类型定义在 types/module/module.go:
// VersionMap is a map of moduleName -> version
type VersionMap map[string]uint64
4.3 UpgradeHandler 签名变更
ADR 将 UpgradeHandler 签名从 func(ctx, plan) 扩展为接收并返回 VersionMap:
- type UpgradeHandler func(ctx sdk.Context, plan Plan)
+ type UpgradeHandler func(ctx sdk.Context, plan Plan, versionMap VersionMap) (VersionMap, error)
当前仓库中该类型的定义见 x/upgrade/README.md:
type UpgradeHandler func(ctx context.Context, plan Plan, fromVM module.VersionMap) (module.VersionMap, error)
4.4 ApplyUpgrade 执行流程
ApplyUpgrade 的实际实现(x/upgrade/keeper/keeper.go)完整地体现了 ADR 的设计意图:
func (k Keeper) ApplyUpgrade(ctx context.Context, plan types.Plan) error {
handler := k.upgradeHandlers[plan.Name]
if handler == nil {
return fmt.Errorf("ApplyUpgrade should never be called without first checking HasHandler")
}
vm, err := k.GetModuleVersionMap(ctx) // 从 state 取旧 VersionMap
// ... 开启 verbose 日志 ...
updatedVM, err := handler(ctx, plan, vm) // 执行用户升级处理器
// ... 关闭 verbose 日志 ...
err = k.SetModuleVersionMap(ctx, updatedVM) // 将更新后的版本映射写回 state
// ... 递增 protocol version ...
}
即:先从 x/upgrade store 查询 VersionMap 传入 handler;handler 内部实际执行迁移函数(见下一节);成功后返回更新后的 VersionMap 落盘。
4.5 gRPC 查询端点
ADR 还提出增加一个 gRPC 查询端点,让应用开发者可以在升级处理器运行前核对 VersionMap。该能力已在 x/upgrade 中实现为 Query/ModuleVersions RPC(见 x/upgrade/types/query.pb.go):
- 请求
QueryModuleVersionsRequest支持可选字段module_name:留空则返回全部模块版本列表; - 响应
QueryModuleVersionsResponse包含[]*ModuleVersion; ModuleVersion(x/upgrade/types/upgrade.pb.go)由name(模块名)与version(共识版本)组成;- HTTP 路由为
GET /cosmos/upgrade/v1beta1/module_versions(见 query.pb.gw.go)。
五、执行迁移引擎:module.Manager.RunMigrations
5.1 核心逻辑
所有迁移处理器在启动时(RegisterServices 阶段)注册进 Configurator。真正执行迁移的入口是 module.Manager.RunMigrations(types/module/module.go)。其内部流程为:
- 确定迁移执行顺序:优先使用
Manager.OrderMigrations(可通过SetOrderMigrations自定义);未设置时使用DefaultMigrationsOrder; - 遍历每个模块:
- 从传入的
fromVM中取出该模块旧版本M; - 通过模块的
ConsensusVersion()取得新版本N; - 若
N > M,则顺序执行M → M+1 → M+2 … → N的所有已注册迁移; - 特殊情形:若
fromVM中不存在该模块(即升级期间新增的模块),则不运行迁移函数,而是直接执行该模块的InitGenesis(以DefaultGenesis初始化),并将当前共识版本写入x/upgradestore;
- 从传入的
- 缺失必要迁移时(例如未在
Configurator注册),函数返回错误。
5.2 源码实现细节
RunMigrations 的遍历核心:
for _, moduleName := range modules {
module := m.Modules[moduleName]
fromVersion, exists := fromVM[moduleName]
toVersion := uint64(0)
if module, ok := module.(HasConsensusVersion); ok {
toVersion = module.ConsensusVersion()
}
if exists {
// 模块已在 fromVM 中:执行 fromVersion -> toVersion 的原地迁移
err := c.runModuleMigrations(sdkCtx, moduleName, fromVersion, toVersion)
} else {
// 新模块:运行 InitGenesis(使用 DefaultGenesis 的空创世状态)
module.InitGenesis(sdkCtx, c.cdc, module.DefaultGenesis(c.cdc))
}
updatedVM[moduleName] = toVersion
}
注释中还指出 fromVM 中不存在该模块的两种典型场景:① 升级新增模块;② 链首次从 < v0.43 升级到 v0.43+(此前所有模块尚未写入 x/upgrade 的版本映射 store)。
5.3 单个模块的逐版本迁移:runModuleMigrations
Configurator 内部的 runModuleMigrations 负责单模块的顺序迁移:
- 若
toVersion <= 1或fromVersion == toVersion,直接 no-op; - 若模块未注册任何迁移,返回
ErrNotFound("no migrations found for module %s"); - 从
fromVersion到toVersion逐个执行迁移函数,中途任何版本缺失都会报错("no migration found for module %s from version %d to version %d"),以此保证迁移链完整。
5.4 迁移顺序:DefaultMigrationsOrder
默认迁移顺序是按模块名升序排列,但 x/auth 除外,它被固定排在最后(见 types/module/module.go 中 DefaultMigrationsOrder 的实现,其注释引用 issue #10591)。应用开发者也可以通过 Manager.SetOrderMigrations 自定义顺序。
5.5 在 UpgradeHandler 中调用
实践中,RunMigrations 应在 UpgradeHandler 内部被调用。ADR 给出的示例在当前仓库 simapp/upgrades.go 中有完整落地(升级名 v054-to-v055):
app.UpgradeKeeper.SetUpgradeHandler(
UpgradeName,
func(ctx context.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) {
sdk.UnwrapSDKContext(ctx).Logger().Debug("this is a debug level message to test that verbose logging mode has properly been enabled during a chain upgrade")
return app.ModuleManager.RunMigrations(ctx, app.Configurator(), fromVM)
},
)
关于新增模块的 InitGenesis 行为,RunMigrations 的文档注释(types/module/module.go)给出了一个进阶技巧:若开发者希望跳过新模块 foo 的 InitGenesis,只需在传给 RunMigrations 的 fromVM 中手动设置 fromVM["foo"] = foo.AppModule{}.ConsensusVersion(),使 diff 为空即可。
在 simapp/app.go 中,RegisterUpgradeHandlers() 被要求在 ModuleManager 与 configurator 均就绪后调用,因为升级处理器依赖 RunMigrations 与 Configurator 的完整注册状态。
5.6 升级时序
假设链在区块 n 触发升级,ADR 规定的时序为:
- 旧二进制:从区块
N开始(即新二进制接管的区块高度)在BeginBlock中停机;其 store 中保存着旧二进制各模块的ConsensusVersion; - 新二进制:从区块
N启动。由于新二进制中已SetUpgradeHandler,该处理器会在新二进制的BeginBlock中运行。在x/upgrade的ApplyUpgrade内部,先从(旧二进制写入的)store 中取出VersionMap传入RunMigrations,在模块自身的BeginBlock之前完成全部模块 store 的原地迁移。
在实现层面,x/upgrade 模块的 PreBlock(见 x/upgrade/module.go)承担了这一"先于其他模块执行"的职责,其注释明确约定:PreBlock 必须在所有其他模块的 BeginBlock 之前调用。
5.7 初始版本映射的写入
ADR 提到版本映射的初始状态由 app.go 的 InitChainer 设置。当前实现中,x/upgrade keeper 提供 SetInitVersionMap / GetInitVersionMap(x/upgrade/keeper/keeper.go),而 x/upgrade 模块的 InitGenesis 会将这份初始映射与链上已有版本映射合并后写入 store(x/upgrade/module.go),并支持链自定义 init chainer 的场景。
六、后果与边界
6.1 向后兼容性
本 ADR 不向后兼容:所有模块都必须实现新的 ConsensusVersion() 方法,且 UpgradeHandler 函数签名被更改。
但迁移的执行是可选的:模块在递增共识版本时必须注册迁移函数,而应用是否在升级处理器中调用 RunMigrations 由开发者自行决定——完全可以继续沿用传统的 JSON 迁移路径。
6.2 正面影响
- 链升级时无需再操作 JSON 文件;
- 虽然尚未有基准测试数据,但可以合理预期原地迁移比 JSON 迁移更快,主要原因是旧二进制的
simd export与新二进制的InitChain都被跳过。
6.3 负面影响
- 模块开发者必须准确追踪本模块的共识破坏性变更:如果引入了破坏性变更却忘记递增
ConsensusVersion(),RunMigrations将检测不到该迁移,链升级可能失败。相关文档应当明确这一点。
6.4 中性影响
- Cosmos SDK 仍将通过
simd export与simd genesis migrate命令继续支持 JSON 迁移路径; - 本 ADR 的机制不支持创建、重命名或删除 store,仅允许修改已有 store 的键与值;此类操作仍须依赖 Cosmos SDK 已有的
StoreLoader。这一点在 simapp/upgrades.go 的参考实现中有清晰体现——它同时使用了upgradetypes.UpgradeStoreLoader配合storetypes.StoreUpgrades(Added/Deleted字段)来处理 store 级别的变更,与RunMigrations的键值级迁移形成互补。
七、总结
ADR-041 确立了 Cosmos SDK 链升级的两大核心机制:版本追踪(每个模块的 ConsensusVersion + x/upgrade 中的 VersionMap 持久化)与原地迁移(Configurator.RegisterMigration 注册 + Manager.RunMigrations 顺序执行)。二者通过 UpgradeHandler 在区块边界处衔接,使状态破坏性升级从"数小时的 JSON 导出与重放"变为"在既有 KV store 上直接改写"。从当前仓库的 x/auth、x/upgrade 与 simapp/upgrades.go 实现可以看出,这套机制已全面落地并持续演进了多个版本(x/auth 已到版本 7),是 Cosmos SDK 生态链升级的默认推荐方案。