stable-memory
БесплатноБез исполняемых скриптовНе проверенPersist canister state across upgrades. Covers StableBTreeMap and MemoryManager in Rust, persistent actor in Motoko, and upgrade hook patterns. Use when…
от 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> }, plainstatics) is wiped on every upgrade. Any data you care about must live in stable memory, either throughic-stable-structuresor by serializing it yourself inpre_upgrade/post_upgrade. - Motoko -- enhanced orthogonal persistence is on by default, so
letandvarin apersistent actoralready survive upgrades with nostablekeyword and no upgrade hooks. Onlytransientdeclarations are wiped.
Prerequisites
- For Motoko: mops with
core = "2.0.0"in mops.toml, andmoc >= 1.7.0(dot notation onMap/Listneeds 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
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 aftericp deploy. UseStableBTreeMapinstead.Forgetting
#[post_upgrade]handler (Rust) -- Without apost_upgradefunction, the canister may silently reset state or behave unexpectedly after upgrade. Always define both#[init]and#[post_upgrade].Using
stablekeyword in persistent actors (Motoko) -- In mo:corepersistent actor, allletandvardeclarations are automatically stable. Writingstable letproduces warning M0218 andstable varis redundant. Just useletandvar.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_upgradehooks 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. UseMemoryManagerto partition stable memory into virtual memories so multiple structures can coexist without overwriting each other.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-levelvar, aMapvalue, 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 plainpersistent actorwith 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 withRTS 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]inmops.tomlsomops checkruns the stable-compatibility check against the previous version's.most(loadmops-cli): it tells you at check time whether a change is compatible or needs a migration, instead of surfacing theRTS erroron the upgrade call.Serializing large data in pre_upgrade (Rust) --
pre_upgradehas 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. UseStableBTreeMapwhich writes directly to stable memory and needs no serialization step.Mismatching the actor form and the
--default-persistent-actorsflag (Motoko) -- Both plainactorandpersistent actorare 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 { }; thepersistentkeyword still compiles but i
Установить stable-memory в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic