migrating-motoko-actors

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Motoko Actor Migrations

Motoko Actor 迁移

Expert guidance for migrating actor state across canister upgrades with orthogonal persistence.
关于使用正交持久化在 canister 升级过程中迁移 actor 状态的专家指南。

Critical: Never use classical persistence or pre/post upgrade

重要:切勿使用经典持久化或 pre/post upgrade

Do not use classical (legacy) persistence or
system func preupgrade
/
system func postupgrade
. They are error-prone, can leave canisters stuck if they trap, and do not scale.
Also do not use the legacy
(with migration = ...)
actor-attached syntax. This skill covers mops-managed migrations. When a change requires an explicit migration, write it as a timestamped file in
src/backend/migrations/
; the chain replays automatically.
切勿使用经典(legacy)持久化或
system func preupgrade
/
system func postupgrade
。这些方式容易出错,一旦触发 trap 就可能让 canister 陷入卡死状态,而且无法扩展。
也不要使用 legacy 的
(with migration = ...)
actor-attached 语法。本 skill 涵盖 mops 管理的迁移。当变更需要显式迁移时,将其编写为
src/backend/migrations/
中带时间戳的文件;迁移链会自动重放。

How stable state is initialized

stable 状态如何初始化

Stable actor fields have no initializers in the actor body. The chain in
src/backend/migrations/
is what gives them values: the runtime walks it in lexicographic order, running every file on a fresh install and only the files not yet applied to the canister on an upgrade.
Actor body 中的 stable 字段没有初始化器。
src/backend/migrations/
中的迁移链负责为它们提供值:runtime 会按字典序遍历该链,在全新安装时运行每个文件,在升级时只运行尚未应用到 canister 的文件。

When to Use This Skill

何时使用本 skill

  • Planning or implementing a canister upgrade that changes actor state
  • Deciding between implicit vs explicit migration
  • Writing or refactoring a migration function
  • Introducing stable state for the first time (a migration with
    OldActor = {}
    , or fold it into the first one if that is still pending)
  • 规划或实现会更改 actor 状态的 canister 升级
  • 决定使用隐式迁移还是显式迁移
  • 编写或重构 migration function
  • 首次引入 stable 状态(使用
    OldActor = {}
    的 migration,或在首个 migration 尚未应用时将初始化逻辑合并到其中)

Migration Folder Rules

Migration 目录规则

  • All migrations live in
    src/backend/migrations/
    .
    The full chain replays in lexicographic filename order on fresh install; on upgrade, only entries newer than the deployed tail run. (The directory is declared as
    chain = ...
    under
    [canisters.<name>.migrations]
    in
    mops.toml
    ; an imported project using a non-default canister name may place it elsewhere — read
    mops.toml
    rather than assuming.)
  • At most one pending migration per build (
    check-limit = 1
    in
    mops.toml
    ). If a migration is already pending (not yet applied), edit that file to fold in further changes instead of adding another.
    mops check
    compares the deployed
    .most
    baseline and names the latest pending file to fold into when the limit is exceeded. Where a hosting platform owns the migrations section and
    check-limit
    , never edit them to clear an error.
  • Name new files with just the UTC timestamp, no suffix:
    YYYYMMDD_HHMMSS.mo
    . The timestamp must sort after every existing file. Do NOT encode the change in the name (no
    AddPriority
    ,
    AddTags
    ,
    Init
    , …) — any feature-ish name tempts you to add another file for the next change instead of editing the one pending file.
  • Never modify, delete, or rename a migration that was already applied. Applied migrations are tracked by module name, so a rename makes the runtime treat the file as never applied, and an edit to an already-applied file never executes. Some platforms enforce this by making applied migrations read-only, in which case writes to them simply fail. A migration that was not applied yet is pending: edit it rather than add a second migration for the same change.
  • Migrations must be self-contained. Inline BOTH old types AND new types in the migration file. Only
    mo:core/...
    and mops package imports are allowed — never
    ../types
    or any project module. The chain replays forever; a frozen migration that imported
    Types.Note
    becomes wrong the moment
    Note
    changes in an incompatible way. Component-owned opaque state is the reason package imports are allowed:
    AccessControl.initState()
    from
    mo:caffeineai-authorization/access-control
    can only be constructed by importing the package.
  • mops check --fix
    automatically verifies upgrade compatibility.
  • 所有 migration 都位于
    src/backend/migrations/
    。
    全新安装时,完整迁移链会按文件名的字典序重放;升级时,只运行比已部署链尾更新的条目。(该目录通过
    mops.toml
    中
    [canisters.<name>.migrations]
    下的
    chain = ...
    声明;导入的项目如果使用非默认 canister 名称,可能将该目录放在其他位置——请阅读
    mops.toml
    ,不要想当然。)
  • 每次构建最多只能有一个待应用 migration(在
    mops.toml
    中设置
    check-limit = 1
    )。如果已有 migration 尚未应用,请直接编辑该文件以合并后续变更,而不是再添加一个。
    mops check
    会将已部署的
    .most
    基线进行比较;当超出限制时,它会指出应合并变更的最新待应用文件。如果托管平台负责管理 migrations 配置段和
    check-limit
    ,切勿通过编辑它们来清除错误。
  • 仅使用 UTC 时间戳命名新文件,不要添加后缀:
    YYYYMMDD_HHMMSS.mo
    。时间戳必须排在所有现有文件之后。不要在名称中编码变更内容(不要使用
    AddPriority
    、
    AddTags
    、
    Init
    等名称)——带功能含义的名称会诱使你在下一次变更时再添加文件,而不是编辑当前待应用文件。
  • 绝不要修改、删除或重命名已经应用的 migration。 已应用的 migration 会按 module 名称跟踪,因此重命名会让 runtime 将该文件视为从未应用,而编辑已经应用的文件则永远不会执行。有些平台通过将已应用 migration 设为只读来强制执行此规则,此时写入会直接失败。尚未应用的 migration 属于待应用状态:请编辑它,不要为同一变更添加第二个 migration。
  • Migration 必须自包含。 在 migration 文件中同时内联 old types 和 new types。只允许使用
    mo:core/...
    和 mops package imports——绝不能使用
    ../types
    或任何项目 module。迁移链会永久重放;如果冻结的 migration 导入了
    Types.Note
    ,那么
    Note
    一旦发生不兼容变更,该文件就会立即失效。组件持有的 opaque state 是允许 package imports 的原因:只有导入
    mo:caffeineai-authorization/access-control
    package,才能构造
    AccessControl.initState()
    。
  • mops check --fix
    会自动验证升级兼容性。

Two Kinds of Migration

两类迁移

1. Implicit migration (no code)

1. 隐式迁移(无需代码)

The runtime allows the upgrade if the new program is compatible with the old. No migration function needed.
Do NOT add a migration file for changes in the implicit list below. Every migration file replays forever on fresh install; adding a no-op file bloats the chain, slows fresh installs, and creates a frozen artifact you can never delete. A long enough chain becomes undeployable in a way no retry recovers, and
mops check
will not warn you. Fewer migrations are always better.
Identity body = no migration. If your
(old : OldActor) : NewActor
body would just be
old
(or rebuild the same record field-by-field with no transformation), the change is stable-compatible — delete the file.
Allowed without explicit migration (typical compatible changes):
  • Changing mutability of a field (
    var
    to
    let
    or vice versa)
  • Adding variant constructors
  • Changing
    Nat
    to
    Int
    (and other safe supertypes)
  • Other changes that satisfy Motoko stable subtyping
Require explicit migration:
  • Removing any actor field the previous version exposes — consume it in
    OldActor
    , omit from
    NewActor
  • Promoting to
    Any
    or other lossy supertypes
  • Renaming fields (map old to new in migration)
  • Non-trivial transformations (e.g.
    Int
    to
    Float
    , restructuring records)
  • Adding new stable fields (initial values must come from the migration; no inline initializers allowed)
  • Introducing stable state for the first time (the migration supplies the initial values; the actor declares stable fields with types only, no inline initializers)
如果新程序与旧程序兼容,runtime 会允许升级。无需 migration function。
不要为以下隐式列表中的变更添加 migration 文件。 每个 migration 文件都会在全新安装时永久重放;添加空操作文件会膨胀迁移链、拖慢全新安装,并创造一个永远无法删除的冻结产物。迁移链足够长后,会变得无法部署,且任何重试都无法恢复,而
mops check
也不会发出警告。migration 越少永远越好。
恒等函数体 = 无需 migration。 如果你的
(old : OldActor) : NewActor
函数体只会返回
old
(或逐字段重建同一个 record 且不做任何转换),则该变更与 stable 兼容——请删除该文件。
无需显式 migration 的典型兼容变更:
  • 更改字段的可变性(
    var
    改为
    let
    ,或反之)
  • 添加 variant 构造器
  • 将
    Nat
    改为
    Int
    (以及其他安全超类型)
  • 满足 Motoko stable subtyping 的其他变更
需要显式迁移:
  • 移除上一版本公开的任意 actor 字段——在
    OldActor
    中消费它,并从
    NewActor
    中省略
  • 提升为
    Any
    或其他有损超类型
  • 重命名字段(在 migration 中将旧字段映射到新字段)
  • 非平凡转换(例如将
    Int
    转换为
    Float
    、重构 record)
  • 添加新的 stable 字段(初始值必须来自 migration;不允许使用内联初始化器)
  • 首次引入 stable 状态(migration 提供初始值;actor 仅声明 stable 字段的类型,不使用内联初始化器)

2. Explicit migration (migration function)

2. 显式迁移(migration function)

Use when the new state shape or types are not a simple compatible extension of the old.
Extend the pending migration if there is one; otherwise add a new timestamped file to
src/backend/migrations/
. The chain replays automatically.
Rules:
  • Migration function type:
    (old : OldActor) : NewActor
    . Both record types must be stable (no shared/local functions; use primitive types, records, variants, Option, Map, List, etc.).
  • Domain
    OldActor
    : record of old stable fields (names and types as in the previous version). If the retired actor is missing a field the domain expects, the upgrade traps and is aborted.
  • Codomain
    NewActor
    : record of new stable fields; each field must exist in the new actor with the same name and a supertype of the codomain type. Use
    var x = ...
    or
    x = ...
    in the output to match the actor's
    var
    vs
    let
    .
  • On fresh install, the entire chain replays in order starting from an empty actor (
    OldActor = {}
    for the first migration); on upgrade, only entries newer than the deployed tail run. Exception: in a project converted from legacy persistence the first file's
    OldActor
    is the pre-conversion stable shape, not
    {}
    — leave it alone (see
    troubleshooting-motoko-migrations
    ).
  • Each
    NewActor
    field's value comes from the migration body. The actor body has no initializers in enhanced mode.
  • List every stable field in both
    OldActor
    and
    NewActor
    (including unchanged ones) is the canonical form for clarity. A partial
    OldActor
    /
    NewActor
    that lists only the fields being changed (subset form) is also supported: unchanged fields carry through automatically. Either way, a field in
    OldActor
    but not in
    NewActor
    is an explicit discard (possible data loss).
  • If the migration function traps, the upgrade is aborted and the canister remains on the old version. Keep the migration pure and free of operations that can trap unexpectedly.
Multi-step upgrades (e.g. v1 to v2 to v3): Each upgrade step has one migration from the previously deployed version. The next version can use a new migration (or none if the change is stable-compatible).
如果新状态结构或类型并非旧状态的简单兼容扩展,则使用此方式。
如果已有待应用 migration,则扩展它;否则,在
src/backend/migrations/
中添加一个带时间戳的新文件。迁移链会自动重放。
规则:
  • Migration function 类型:
    (old : OldActor) : NewActor
    。两种 record 类型都必须是 stable(不得包含 shared/local functions;可使用 primitive types、records、variants、Option、Map、List 等)。
  • Domain
    OldActor
    :由旧 stable 字段组成的 record(字段名和类型与上一版本一致)。如果退役 actor 缺少 Domain 所期望的字段,升级会触发 trap 并中止。
  • Codomain
    NewActor
    :由新 stable 字段组成的 record;每个字段都必须以相同名称存在于新 actor 中,且 actor 中对应字段的类型必须是 Codomain 类型的超类型。根据 actor 的
    var
    或
    let
    ,在输出中使用
    var x = ...
    或
    x = ...
    。
  • 全新安装时,完整迁移链会从空 actor 开始按顺序重放(首个 migration 使用
    OldActor = {}
    );升级时,只运行比已部署链尾更新的条目。例外:从 legacy 持久化转换而来的项目,其首个文件的
    OldActor
    是转换前的 stable shape,而不是
    {}
    ——不要修改它(参见
    troubleshooting-motoko-migrations
    )。
  • 每个
    NewActor
    字段的值都来自 migration body。在 enhanced mode 下,actor body 中没有初始化器。
  • 在
    OldActor
    和
    NewActor
    中都列出每一个 stable 字段(包括未变更的字段)是清晰表达的标准形式。也支持只列出待变更字段的部分形式(subset form),未变更字段会自动继承。无论采用哪种形式,
    OldActor
    中存在但
    NewActor
    中不存在的字段都表示显式丢弃(可能造成数据丢失)。
  • 如果 migration function 触发 trap,升级会中止,canister 将继续运行旧版本。保持 migration 纯粹,并避免执行可能意外触发 trap 的操作。
多步骤升级(例如 v1 到 v2 到 v3):每个升级步骤都包含一条从先前已部署版本出发的 migration。下一版本可以使用新的 migration,或者在变更与 stable 兼容时不使用 migration。

Authoring a migration

编写 migration

Pick a bare UTC-timestamp filename (
YYYYMMDD_HHMMSS.mo
, no suffix) that sorts after every existing entry, then write the module:
motoko
module {
  type OldActor = { /* old stable fields, inlined */ };
  type NewActor = { /* new stable fields */ };

  public func migration(old : OldActor) : NewActor {
    { /* produce new fields from old */ };
  };
};
  • Must be a
    module
    exporting
    public func migration(old : OldActor) : NewActor
    (the function name is required — the chain runner discovers it by name).
  • Both
    OldActor
    and
    NewActor
    must be inlined in the file — no project imports.
选择一个仅含 UTC 时间戳的文件名(
YYYYMMDD_HHMMSS.mo
,无后缀),并确保其排在所有现有条目之后,然后编写 module:
motoko
module {
  type OldActor = { /* old stable fields, inlined */ };
  type NewActor = { /* new stable fields */ };

  public func migration(old : OldActor) : NewActor {
    { /* produce new fields from old */ };
  };
};
  • 必须是一个导出
    public func migration(old : OldActor) : NewActor
    的
    module
    (函数名是必需的——chain runner 通过该名称发现它)。
  • OldActor
    和
    NewActor
    都必须内联在文件中——不得导入项目 module。

Actor body: types only, no initializers

Actor body:仅声明类型,不使用初始化器

Stable vars are declared with types, no initial values. Transient let/var fields use initializers as usual.
This no-initializer rule applies to enhanced-migration projects (this skill's subject), where the migration chain owns initial values. In a plain project without the enhanced-migration chain, stable fields are initialized with inline values in the actor body as usual (e.g.
actor { let m = Map.empty<Nat, Text>(); }
).
motoko
actor {
  let tasks : Map.Map<Text, Task>;
  var nextId : Nat;

  transient var cache = List.empty<Text>();
};
Initial values come from the migration chain. When you introduce stable state for the first time, write a migration whose
OldActor = {}
and
NewActor
enumerates every stable field declared in
main.mo
. The migration body must produce a value for each. Missing fields surface as compatibility warnings and break subsequent upgrades.
If an example anywhere shows inline initializers like
let accessControlState = AccessControl.initState();
or
let users = Map.empty<Principal, User>();
directly in the actor body, it predates enhanced migration. Under enhanced migration that is a compile error (M0014, M0250). Treat such examples as state-shape hints only: copy the field name and type into your actor (without initializer), and move the initializer expression into the migration function's
NewActor
output
.
Stable vars 仅声明类型,不设置初始值。Transient let/var 字段照常使用初始化器。
此无初始化器规则仅适用于 enhanced-migration 项目(本 skill 的主题),其中初始值由 migration chain 管理。在没有 enhanced-migration chain 的普通项目中,stable 字段照常在 actor body 中使用内联值进行初始化(例如
actor { let m = Map.empty<Nat, Text>(); }
)。
motoko
actor {
  let tasks : Map.Map<Text, Task>;
  var nextId : Nat;

  transient var cache = List.empty<Text>();
};
初始值来自 migration chain。首次引入 stable 状态时,编写一份
OldActor = {}
的 migration,并让
NewActor
枚举
main.mo
中声明的每一个 stable 字段。Migration body 必须为每个字段生成一个值。缺失字段会触发兼容性警告,并破坏后续升级。
如果任何示例直接展示 actor body 中的内联初始化器,例如
let accessControlState = AccessControl.initState();
或
let users = Map.empty<Principal, User>();
,则该示例早于 enhanced migration。在 enhanced migration 下,这是编译错误(M0014、M0250)。请仅将这类示例视为状态结构提示:将字段名和类型复制到 actor 中(不带初始化器),并把初始化表达式移动到 migration function 的
NewActor
输出中
。

Stable-Compatible (definition)

Stable-compatible(定义)

Old signature is stable-compatible with new if, for every stable field
id : T
in the old signature:
  • The new signature has a stable field
    id : U
    such that T is a stable subtype of U (the old value can be used as the new field's initial value without loss of data).
  • The new signature may include additional fields not present in the old one (each supplied by a migration).
  • Matching fields may differ in mutability (
    var
    vs non-
    var
    ).
So: you can widen types (e.g.
Nat
to
Int
) and change mutability without an explicit migration. You cannot remove fields, rename them, or narrow types. Adding a stable field always requires a migration: inline initializers are not allowed, so the new field's initial value must come from a migration file's
NewActor
.
如果对于旧签名中的每个 stable 字段
id : T
,旧签名都与新签名 stable-compatible,则满足以下条件:
  • 新签名包含一个 stable 字段
    id : U
    ,并且 T 是 U 的 stable subtype(旧值可以在不丢失数据的情况下用作新字段的初始值)。
  • 新签名可以包含旧签名中不存在的额外字段(每个字段都由 migration 提供)。
  • 匹配的字段可以具有不同的可变性(
    var
    与非
    var
    )。
因此,可以拓宽类型(例如将
Nat
改为
Int
)并更改可变性,而无需显式 migration。不能移除字段、重命名或收窄类型。添加 stable 字段始终需要 migration:不允许使用内联初始化器,因此新字段的初始值必须来自 migration 文件的
NewActor
。

Patterns

模式

Add record field with default

使用默认值添加 record 字段

Use
record with newField = value
to add a field to every element:
motoko
// Add required field zipCode to each taxpayer
old.taxPayers.map<Nat, OldTaxPayer, NewTaxPayer>(
  func(_id, oldTaxPayer) { { oldTaxPayer with zipCode = "" } }
);
For a new optional field, set it to
null
:
motoko
{ task with var status = task.status; var assignee = null : ?Principal }
使用
record with newField = value
为每个元素添加字段:
motoko
// Add required field zipCode to each taxpayer
old.taxPayers.map<Nat, OldTaxPayer, NewTaxPayer>(
  func(_id, oldTaxPayer) { { oldTaxPayer with zipCode = "" } }
);
如果要添加新的可选字段,将其设为
null
:
motoko
{ task with var status = task.status; var assignee = null : ?Principal }

Add or extend variant type

添加或扩展 variant 类型

Adding a variant tag -- cast the old value to the new variant type:
motoko
var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired
Replacing a Bool with a variant:
motoko
var status = if (task.completed) { #completed } else { #pending };
添加 variant tag——将旧值转换为新的 variant 类型:
motoko
var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired
使用 variant 替换 Bool:
motoko
var status = if (task.completed) { #completed } else { #pending };

Map over a collection

遍历集合

Transform each value in a
Map
with
map<K, OldV, NewV>(func(key, oldVal) { ... })
:
motoko
let todos = old.todos.map<TaskID, OldTask, NewTask>(
  func(_, task) {
    {
      task with
      due = 0;
      var status = if (task.completed) { #completed } else { #pending };
    };
  }
);
{ var todos; var nextTaskId = old.nextTaskId };
使用
map<K, OldV, NewV>(func(key, oldVal) { ... })
转换
Map
中的每个值:
motoko
let todos = old.todos.map<TaskID, OldTask, NewTask>(
  func(_, task) {
    {
      task with
      due = 0;
      var status = if (task.completed) { #completed } else { #pending };
    };
  }
);
{ var todos; var nextTaskId = old.nextTaskId };

Add new top-level stable field (computed from old state)

添加新的顶层 stable 字段(根据旧状态计算)

Include the new field in the migration output and compute it from old fields:
motoko
let times = List.repeat<Time.Time>(0, old.messages.size());
{ var messages = old.messages; var times };
将新字段包含在 migration 输出中,并根据旧字段计算:
motoko
let times = List.repeat<Time.Time>(0, old.messages.size());
{ var messages = old.messages; var times };

Restructure: change shape of state

重构:更改状态结构

When the new state has a different structure, provide a transformation function from the old field type to the new one and implement it according to the application's migration logic. Build the new value in the migration from the old state and return a record that matches NewActor.
当新状态具有不同结构时,提供从旧字段类型到新类型的转换函数,并按照应用的 migration 逻辑实现它。根据旧状态构建新值,并返回与
NewActor
匹配的 record。

Change type of a field

更改字段类型

Rename/conceptual change -- e.g.
artist : Text
to
artists : Set.Set<Text>
:
motoko
{ oldPainting with artists = Set.singleton<Text>(oldPainting.artist) }
重命名或概念性变更——例如将
artist : Text
改为
artists : Set.Set<Text>
:
motoko
{ oldPainting with artists = Set.singleton<Text>(oldPainting.artist) }

Rename or change type of a single field

重命名或更改单个字段的类型

Input record uses old name/type, output record uses new name/type:
motoko
// src/backend/migrations/YYYYMMDD_HHMMSS.mo
import Int "mo:core/Int";

module {
  type OldActor = { var state : Int };
  type NewActor = { var newState : Float };

  public func migration(old : OldActor) : NewActor {
    { var newState = old.state.toFloat() };
  };
};
输入 record 使用旧名称和类型,输出 record 使用新名称和类型:
motoko
// src/backend/migrations/YYYYMMDD_HHMMSS.mo
import Int "mo:core/Int";

module {
  type OldActor = { var state : Int };
  type NewActor = { var newState : Float };

  public func migration(old : OldActor) : NewActor {
    { var newState = old.state.toFloat() };
  };
};

Drop a field intentionally

有意丢弃字段

Consume it in the migration input but do not include it in the output. Expect a compiler warning; ensure the loss is intentional.
在 migration 输入中消费该字段,但不要将其包含在输出中。预期会出现编译器警告;请确保数据丢失是有意为之。

Add a new field

添加新字段

Add the field to
main.mo
with type only (no initializer) AND add it to the next migration's
NewActor
with a value computed from old fields or a constant. The actor body cannot supply the initial value under enhanced migration.
在
main.mo
中仅以类型(无初始化器)添加该字段,同时在下一份 migration 的
NewActor
中加入该字段,其值由旧字段计算或使用常量。在 enhanced migration 下,actor body 无法提供初始值。

Migration-Time Semantics

Migration 执行时的语义

  • The migration function runs once at upgrade time, in the upgrade context. Values like
    Time.now()
    in the migration body are the time of the upgrade, not of each original record creation.
  • Do not use constants or magic values in migrations; derive defaults from the migration input or from well-defined application types.
  • Migration function 在升级时运行一次,运行于 upgrade context 中。Migration body 中的
    Time.now()
    等值表示升级时间,而不是每条原始记录的创建时间。
  • 不要在 migration 中使用常量或 magic values;应从 migration 输入或定义明确的应用类型中派生默认值。

Compatibility and Tooling

兼容性与工具

The upgrade safety check compares the new actor body against the last deployed stable signature: a
.most
file (an encoded snapshot of the stable signature — field names and types) referenced from
mops.toml
under
[canisters.<name>.check-stable]
. When that is configured,
mops check --fix
picks it up automatically. Hosted platforms typically wire this up for you and keep the previous
.most
alongside the project.
For the check to pass: the new migration's
OldActor
must match the previously deployed signature, and its
NewActor
must match (or be a stable supertype of) the new actor body.
To derive
OldActor
deterministically: your
OldActor
equals the
NewActor
of the file that precedes yours in
src/backend/migrations/
(lex-order), or
{}
if yours is the first file in the chain.
{}
applies only when the chain starts from an empty canister — a project converted from legacy persistence starts from its pre-conversion stable shape instead, and its existing first file already reflects that.
升级安全检查会将新 actor body 与最后部署的 stable signature 进行比较。后者是一个
.most
文件(stable signature 的编码快照,包含字段名称和类型),通过
mops.toml
中
[canisters.<name>.check-stable]
引用。完成此项配置后,
mops check --fix
会自动识别它。托管平台通常会代为配置,并保留项目中的上一份
.most
。
要通过检查,新 migration 的
OldActor
必须匹配先前部署的 signature,而
NewActor
必须匹配新 actor body(或为其 stable supertype)。
确定性地推导
OldActor
:你的
OldActor
应等于
src/backend/migrations/
中按字典序排列的前一个文件的
NewActor
;如果你的文件是迁移链中的第一个文件,则为
{}
。只有从空 canister 开始的迁移链才使用
{}
——从 legacy 持久化转换而来的项目从转换前的 stable shape 开始,其现有首个文件已经反映了这一点。

Checklist for Upgrades

升级检查清单

  • Decide: implicit (compatible change) vs explicit (migration file)
  • At most ONE pending migration file per build. Before creating a file, check
    src/backend/migrations/
    — if a migration is already pending, edit it instead of adding a second
  • If explicit: pick a bare UTC-timestamp filename (
    YYYYMMDD_HHMMSS.mo
    , no suffix) that sorts after every existing file; do not encode the change in the name
  • Set
    OldActor
    to the
    NewActor
    of the file that precedes yours in
    src/backend/migrations/
    (lex-order), or
    {}
    if yours is the first file in a project that started out with a chain. Never from current
    main.mo
    . Never the file's own
    NewActor
    .
  • When the directory is empty (init migration),
    NewActor
    must list every stable field declared in
    main.mo
    , with a value for each
  • Inline both
    OldActor
    (with old types) and
    NewActor
    (with new types) — no project imports
  • Implement
    public func migration(old : OldActor) : NewActor
  • Never modify or delete a migration that was already applied; edit (don't duplicate) a pending one
  • Do not use preupgrade/postupgrade or
    (with migration = ...)
    for data migration
  • Iterate on
    mops check --fix
    (fast) until it passes — it verifies compilation and upgrade safety
  • Run
    mops build
    ONCE at the end (slow) to compile the backend and produce the updated IDL bindings
  • 确定使用隐式迁移(兼容变更)还是显式迁移(migration 文件)
  • 每次构建最多只能有一个待应用 migration 文件。 创建文件前,检查
    src/backend/migrations/
    ——如果已有待应用 migration,请编辑它,而不是添加第二个
  • 如果使用显式迁移:选择一个仅含 UTC 时间戳的文件名(
    YYYYMMDD_HHMMSS.mo
    ,无后缀),并确保其排在所有现有文件之后;不要在名称中编码变更内容
  • 将
    OldActor
    设置为
    src/backend/migrations/
    中前一个文件(按字典序排列)的
    NewActor
    ;如果你的文件是最初以迁移链启动的项目中的第一个文件,则设置为
    {}
    。绝不能使用当前
    main.mo
    ,也不能使用该文件自身的
    NewActor
  • 当目录为空时(初始化 migration),
    NewActor
    必须列出
    main.mo
    中声明的每一个 stable 字段,并为每个字段提供值
  • 同时内联
    OldActor
    (使用旧类型)和
    NewActor
    (使用新类型)——不得导入项目 module
  • 实现
    public func migration(old : OldActor) : NewActor
  • 绝不修改或删除已经应用的 migration;编辑待应用 migration,而不是创建重复文件
  • 不要使用 preupgrade/postupgrade 或
    (with migration = ...)
    进行数据迁移
  • 反复运行
    mops check --fix
    (速度较快)直至通过——它会验证编译和升级安全性
  • 最后只运行一次
    mops build
    (速度较慢),以编译后端并生成更新后的 IDL bindings

Additional References

附加参考

  • Migration examples: See examples.md for minimal, self-contained examples (add field, map over collection, add optional field)
  • When something does not add up: Load
    troubleshooting-motoko-migrations
    for compatibility diagnostics you cannot explain, write failures on frozen files, projects converted from legacy persistence, and requests to remove the chain. Not needed on the normal path.
  • General Motoko development: Use
    writing-motoko
    for language fundamentals, core library reference, and architecture patterns
  • mops tooling: Load
    mops-cli
    for
    mops.toml
    configuration,
    mops check
    ,
    mops build
    , and toolchain setup
  • Motoko Docs: Data persistence
  • Motoko Docs: Compatibility
  • Migration 示例:请参阅 examples.md 中简洁且自包含的示例(添加字段、遍历集合、添加可选字段)
  • 当某些情况无法解释时:加载
    troubleshooting-motoko-migrations
    ,用于排查无法解释的兼容性诊断、冻结文件上的写入失败、从 legacy 持久化转换而来的项目,以及要求移除迁移链的场景。正常流程不需要使用它
  • Motoko 通用开发:使用
    writing-motoko
    了解语言基础、core library 参考和架构模式
  • mops 工具链:加载
    mops-cli
    以配置
    mops.toml
    、使用
    mops check
    、
    mops build
    和设置工具链
  • Motoko 文档:数据持久化
  • Motoko 文档:兼容性