Dfinity official migrating motoko actors

From jiayaoqijia/cryptoskill · View interactive version

Dfinity official migrating motoko actors is an AI agent skill from the GitHub repository jiayaoqijia/cryptoskill. Motoko actor state migration and schema evolution using the mops-managed migration chain (a migrations/ directory of timestamped files). Use when upgrading canisters, changing actor field types, renaming or adding stable fields, deciding implicit vs explicit migration, or writing migration files — i

How to use this skill

Skill file

Motoko Actor Migrations

Expert guidance for migrating actor state across canister upgrades with orthogonal persistence.

Critical: Never use classical persistence or 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.

How stable state is initialized

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.

When to Use This Skill

Migration Folder Rules

Two Kinds of Migration

1. Implicit migration (no code)

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):

Require explicit migration:

2. Explicit migration (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:

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).

Authoring a migration

Pick a bare UTC-timestamp filename (YYYYMMDD_HHMMSS.mo, no suffix) that sorts after every existing entry, then write the module:

module {
  type OldActor = { /* old stable fields, inlined */ };
  type NewActor = { /* new stable fields */ };

  public func migration(old : OldActor) : NewActor {
    { /* produce new fields from old */ };
  };
};

Actor body: types only, no initializers

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>(); }).

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-Compatible (definition)

Old signature is stable-compatible with new if, for every stable field id : T in the old signature:

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.

Patterns

Add record field with default

Use record with newField = value to add a field to every element:

// 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:

{ task with var status = task.status; var assignee = null : ?Principal }

Add or extend variant type

Adding a variant tag -- cast the old value to the new variant type:

var status = bounty.status : NewTaskStatus // OldTaskStatus had #open;#claimed;#completed; New adds #expired

Replacing a Bool with a variant:

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) { ... }):

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)

Include the new field in the migration output and compute it from old fields:

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.

Change type of a field

Rename/conceptual change -- e.g. artist : Text to artists : Set.Set<Text>:

{ 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:

// 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.

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.

Migration-Time Semantics

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.

Checklist for Upgrades

Additional References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.