Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

stable-memory

БесплатноБез исполняемых скриптовНе проверен

Persist canister state across upgrades. Covers StableBTreeMap and MemoryManager in Rust, persistent actor in Motoko, and upgrade hook patterns. Use when…

jiayaoqijiaот jiayaoqijia★ 81 звезда на GitHub

Об этом скилле

Stable Memory & Canister Upgrades

What This Is

Stable memory is persistent storage on Internet Computer that survives canister upgrades. Whether ordinary variables survive depends on the language:

  • Rust -- heap data (thread_local! { RefCell<T> }, plain statics) is wiped on every upgrade. Any data you care about must live in stable memory, either through ic-stable-structures or by serializing it yourself in pre_upgrade/post_upgrade.
  • Motoko -- enhanced orthogonal persistence is on by default, so let and var in a persistent actor already survive upgrades with no stable keyword and no upgrade hooks. Only transient declarations are wiped.

Prerequisites

  • For Motoko: mops with core = "2.0.0" in mops.toml, and moc >= 1.7.0 (dot notation on Map/List needs it)
  • For Rust: ic-stable-structures = "0.7" in Cargo.toml

Canister IDs

No external canister dependencies. Stable memory is a local canister feature.

Mistakes That Break Your Build

  1. Using thread_local! { RefCell<T> } for user data (Rust) -- This is heap memory. It is wiped on every canister upgrade. All user data, balances, settings stored this way will vanish after icp deploy. Use StableBTreeMap instead.

  2. Forgetting #[post_upgrade] handler (Rust) -- Without a post_upgrade function, the canister may silently reset state or behave unexpectedly after upgrade. Always define both #[init] and #[post_upgrade].

  3. Using stable keyword in persistent actors (Motoko) -- In mo:core persistent actor, all let and var declarations are automatically stable. Writing stable let produces warning M0218 and stable var is redundant. Just use let and var.

  4. Confusing heap memory limits with stable memory limits (Rust) -- Heap (Wasm linear) memory is limited to 4GB for wasm32 and 6GB for wasm64. Stable memory can grow up to hundreds of GB (the subnet storage limit). The real danger: if you use pre_upgrade/post_upgrade hooks to serialize heap data to stable memory and deserialize it back, you are limited by the heap memory size AND by the instruction limit for upgrade hooks. Large datasets will trap during upgrade, bricking the canister. The solution is to use stable structures (StableBTreeMap, StableCell, etc.) that read/write directly to stable memory, bypassing the heap entirely. Use MemoryManager to partition stable memory into virtual memories so multiple structures can coexist without overwriting each other.

  5. Treating a rejected upgrade as data loss (Motoko) -- Enhanced orthogonal persistence checks the new program against the existing state and either accepts the upgrade or rejects it before it takes effect. A rejected upgrade is not data loss: the canister keeps running the previous version with its state intact, so you fix the code and redeploy.

    Which schema changes need a migration, and how to write one, are owned by migrating-motoko-actors (the mops-managed migration chain); load it for the rules and syntax. The one thing to know here is the common surprise: changing a record type that an existing persistent variable holds is an incompatible change and needs a migration, even for an optional added field, and regardless of where the record lives (a top-level var, a Map value, etc.). Whether adding a new stable field itself needs a migration depends on the project's setup — under the enhanced migration chain a stable field is declared type-only, so a new one needs a migration; a plain persistent actor with an initializer on the new field does not — which is exactly why the rules live in that skill rather than as a table here. An incompatible upgrade is rejected at runtime with RTS error: Memory-incompatible program upgrade (the old state stays intact — it is not data loss).

    Don't discover this at deploy time. Configure [canisters.<name>.check-stable] in mops.toml so mops check runs the stable-compatibility check against the previous version's .most (load mops-cli): it tells you at check time whether a change is compatible or needs a migration, instead of surfacing the RTS error on the upgrade call.

  6. Serializing large data in pre_upgrade (Rust) -- pre_upgrade has a fixed instruction limit. If you serialize a large HashMap to stable memory in pre_upgrade, it will hit the limit and trap, bricking the canister. Use StableBTreeMap which writes directly to stable memory and needs no serialization step.

  7. Mismatching the actor form and the --default-persistent-actors flag (Motoko) -- Both plain actor and persistent actor are correct; which one compiles depends on that compiler flag. Enabling it is the recommended setup, because it keeps the code less verbose:

    # mops.toml — recommended; see `mops-cli`
    [moc]
    args = ["--default-persistent-actors"]
    

    With the flag, every actor is persistent, so write plain actor { }; the persistent keyword still compiles but i

Полный SKILL.md на GitHub

Установить stable-memory в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

LICENSESOURCE.mdTRUST.auto.yaml

FAQ

Что делает скилл stable-memory?

Persist canister state across upgrades. Covers StableBTreeMap and MemoryManager in Rust, persistent actor in Motoko, and upgrade hook patterns. Use when dealing with canister upgrades, data persistence, data lost after upgrade, stable storage, StableBTreeMap, pre_upgrade traps, or heap vs stable memory. Do NOT use for inter-canister calls or access control — use multi-canister or canister-security instead.

Как установить скилл stable-memory?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл stable-memory запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить stable-memory с