Removing of stable variables from canister

If I have a canister with 2 stable variable structures defined inside it, and want to remove one as it is no longer needed, how do i remove this stable structure without reinstalling the canister

Is your canister written in Motoko, Rust, or what?
Can you provide a code snippet of how those variables are declared?

I guess with this you mean “without running dfx canister install --mode reinstall to avoid losing data”, right?

1 Like

You can clear the data in that stable variable, but the pages it allocated remain part of the canister’s stable memory. They cannot be given back or reused by other stable variables of different types. The only way to truly reclaim (shrink) stable-memory usage is to reinstall the canister, which wipes all stable memory.

1 Like

I got the impression that after an upgrade, the stable memory restarts with its effective size.

In Rust? Yes and no. You can’t reallocate at runtime, but you can do it during an upgrade without reinstalling fully the canister, using a “hack” or “workaround”.

I used it in the last version of Juno. It was originally used by some foundation projects, notably Orbit.

It’s probably not recommended, so I’m sharing the following links FYI and with a “:warning: USE AT YOUR OWN RISK :warning:” disclaimer: the PR where I implemented it and the specific function for clearing which importantly must be called at a certain point if time of the post_upgrade.

2 Likes

In Motoko you’d use a migration function that explicitly drops the stable variable:

Upgrade from:

actor {
  stable var firstValue = 0;
  stable var secondValue = 0;
}

to:

(with migration = func ({firstValue : Nat}) : {} = {})
actor {
  stable var secondValue = 0;
}
1 Like