Upgrades: Revise Saved Data on Purpose

Audience task and outcome

  • Task Add a saved revision number to a deployed app's root, keeping every existing score.
  • Observable outcome The viewer can make a data revision in four edits. They add a new version file, select it as current, write the converter, and declare the old version as a supported predecessor. They can test it natively and on PocketIC. After the upgrade the probe reports generation 2 and still returns 91 for key 7. A downgrade to the old build is refused.
  • Starting point Lesson 6 froze shipped version files and showed an unplanned contract change being refused.
  • Handoff Lesson 8 moves to a large app. Its modules use the same version folders.
  • Pacing Four minutes.

The worked example

The Root authoring probe is a Scores app like Quickstart with one difference. It can be built as V1 or as V2. In V1 the root saves nothing of its own and attaches Scores. In V2 the root saves a revision field, set to 2, and attaches the same Scores module. The lifecycle check installs V1, saves 7 → 91 and 8 → 92, and reads generation 1. A V2 build that does not declare V1 as its predecessor is refused. A V2 build whose restore callback fails after converting is rolled back to V1 with its values intact. The proper V2 build upgrades, reports generation 2, and returns both values. The V1 build is then refused as a downgrade. Root authoring probe · Root versions · Root wiring and native test · Lifecycle check

The probe selects V1 or V2 with a Cargo feature so one source tree can produce both images for the test. A real application simply moves forward. Its selector names the new version and its root attribute lists the predecessor, as in the upgrade guide. Convert within each owner · Contract admission

The story in one pass

Leave v1.rs locked and write v2.rs beside it. Point the selector at V2. Write the converter, which builds the new root data and moves the Scores child across untouched. Declare V1 as the supported predecessor and choose the conversion path at restore. Run the native test, then the PocketIC sequence with its refusals, its rollback, the successful upgrade and the refused downgrade.

Views and visual objects

Use the shared visual language and the ReleaseStrip from lesson 6. The root now has its own StateCard, empty in V1 and holding revision 2 in V2. Scores keeps its ModuleCard and its v1 badge throughout.

The new object is the Converter, a small labeled arrow between two version files in the AppTree. It has two inputs drawn as short stubs, data and children.

View Framing and anchor
versions Two EditorPane columns for root/memory/v1.rs and v2.rs, with the Converter between them and the root and Scores cards beneath.
wiring EditorPane for root/mod.rs, ReleaseStrip beneath.
native TestPanel with the native test, root and Scores cards at right.
sequence ReleaseStrip with a TestPanel on the lifecycle check, and a row of build cards v1, undeclared, trap, v2.

Scene new_version — Write V2 beside V1

Enters with The locked root/memory/v1.rs and the dashed v2.rs outline from lesson 6. The probe's Scores card shows 7 → 91 and 8 → 92.

Beat v1_stays — The shipped version is the starting point

View and focus versions, left pane.

Show src/root/memory/v1.rs lines 1 to 8.

pub type Data = ();
cdk_rsx_store::module_children! {
    pub struct Children {
        pub(in crate::root) scores: cdk_rsx_store::ChildSlot<crate::scores::memory::v1::Memory>,
    }
}
#[cdk_rsx_store::memory(owner = crate::root, children = Children)]
pub struct Memory;

Narration

This app is deployed with root memory version one. The root saves no fields, and it has one child, Scores. We want the root to save a revision number. Version one is shipped, so its file stays as it is.

Cue and animation On “root memory version one”, show the lock on v1.rs. On “saves no fields”, show the root's StateCard empty. On “a revision number”, show the request note root saves revision. On “stays as it is”, pulse the lock.

Leaves with Locked V1 and the request.

Beat write_v2 — A complete new declaration

View and focus versions, right pane.

Show src/root/memory/v2.rs lines 1 to 16. Point at revision, then at the scores slot.

#[derive(cdk_rsx_store::NyxusData)]
pub struct Data {
    pub(in crate::root) revision: u64,
}
impl Default for Data {
    fn default() -> Self {
        Self { revision: 2 }
    }
}
cdk_rsx_store::module_children! {
    pub struct Children {
        pub(in crate::root) scores: cdk_rsx_store::ChildSlot<crate::scores::memory::v1::Memory>,
    }
}
#[cdk_rsx_store::memory(owner = crate::root, children = Children)]
pub struct Memory;

Narration

Version two is a new file with the complete declaration. Data now has the revision field. The children are written out again, and the Scores slot still names Scores version one. The root changed. Scores did not, so its version number stays.

Cue and animation On “a new file”, slide v2.rs into the tree. On “the revision field”, band line 3 and show a V2 root StateCard preview with revision. On “still names Scores version one”, band scores::memory::v1::Memory in both panes and link them. On “its version number stays”, pulse the v1 badge on the Scores card.

Hold or transition Hold on the linked slots. Balloon reads versions belong to each module. Root v2 can attach Scores v1.

Leaves with Two version files side by side.

Beat select_v2 — Current now means V2

View and focus versions, with a small pane for root/memory/mod.rs.

Show src/root/memory/mod.rs lines 1 to 7. The film shows the two lines a moved-forward app keeps, and the note marks the feature gates as a fixture device.

pub mod v1;
pub mod v2;
pub use v2 as current;

Narration

The selector now exports version two as current. Both modules stay in the source. Service code keeps saying current and follows along. Version one remains for the converter to read.

Cue and animation On “version two as current”, move a current tag in the tree from v1.rs to v2.rs. On “Both modules stay”, pulse both files. On “for the converter to read”, light the Converter arrow's tail at v1.rs.

Leaves with current on v2.rs.

Scene converter — Say how V1 becomes V2

Enters with Both versions and the empty Converter arrow.

Beat write_converter — New data, same child

View and focus versions, centre pane on root/memory/mod.rs.

Show src/root/memory/mod.rs lines 10 to 26.

pub(super) fn upgrade(
    source: cdk_rsx_store::Actor<v1::Memory>,
) -> cdk_rsx_store::Result<cdk_rsx_store::Actor<v2::Memory>> {
    source.upgrade(
        &v1::KEY,
        &v2::KEY,
        |_, ()| Ok(v2::Data::default()),
        |upgrade, old, new| {
            let child = old
                .scores
                .take(upgrade.scope())?
                .ok_or(cdk_rsx_store::Error::NotInstalled)?;
            new.scores.attach(upgrade.scope(), child)?;
            Ok(())
        },
    )
}

Narration

The converter lives in the root's memory folder. It takes the version one root and returns the version two root. Its first closure receives the old data, which was empty, and returns the new data with revision two. Its second closure handles the children. It takes Scores out of the old slot and attaches it to the new one. The scores themselves are never touched.

Cue and animation On “takes the version one root”, band the signature. On “first closure”, band |_, ()| Ok(v2::Data::default()) and feed the data stub, producing revision 2 on the V2 root card. On “second closure”, band the children closure and feed the children stub. On “takes Scores out”, lift the whole Scores card from the V1 root. On “attaches it”, seat it under the V2 root with 7 → 91 and 8 → 92 unchanged.

Hold or transition Hold with Scores seated. Balloon on the children closure reads a converter reads only its own module's data and hands children over whole.

Leaves with A V2 root with revision 2 and the same Scores card.

Beat declare_previous — Tell the root which version it accepts

View and focus wiring.

Show The attribute form from the upgrade guide, labeled as the guide's sample. Then src/root/mod.rs lines 57 to 70 with the feature gates hidden.

#[cdk_rsx::root(
    state = App,
    init = install,
    restore = reopen,
    previous = [memory::v1::Memory]
)]
pub mod memory;
    fn open(store: &Store) -> Result<Self> {
        let actor = {
            use cdk_rsx_store::ModuleMemory;
            if store.root_contract()? == memory::v1::Memory::CONTRACT {
                memory::upgrade(store.open(&memory::v1::KEY)?)?
            } else {
                store.open(&Mem::KEY)?
            }
        };
        Self::bind(actor)
    }

Narration

Two more edits connect it. The root attribute lists version one under previous. That is the only older contract this build will accept. Then open, which restore calls, asks which root the canister saved. If it is version one, it runs the converter. Otherwise it opens version two directly. Either way it ends by binding the services.

Cue and animation On “under previous”, band previous = [memory::v1::Memory]. On “the only older contract”, show the ReleaseStrip accepting saved root v1 and root v2 badges and turning away a badge marked other. On “If it is version one”, band the if branch and run the Converter. On “opens version two directly”, band the else branch. On “binding the services”, band Self::bind(actor).

Leaves with A build that accepts V1 or V2 and always ends bound to V2.

Scene test_it — Native first, then the real upgrade

Enters with The finished revision.

Beat native_conversion — The conversion in a Rust test

View and focus native.

Show src/root/mod.rs, the test owner_conversion_preserves_the_existing_child, lines 184 to 199 in summary.

                Scores::bind(child).view(scope).put(7, 91)?;
                Ok(child.identity())
        let app = App::open(&store).unwrap();
        app.read(|view| {
            // …
            assert_eq!(after.identity(), before);
            assert_eq!(view.scores().get(7)?, Some(91));
            assert_eq!(view.generation()?, 2);

Narration

A native test covers the converter itself. It installs a version one root by hand, saves ninety-one under key seven, and calls open. Afterward the Scores module is the very same one, key seven still holds ninety-one, and the generation is two.

Cue and animation On “installs a version one root”, show a V1 root with Scores. On “saves ninety-one”, add 7 → 91. On “calls open”, run the Converter. On “the very same one”, pass the identity assertion with a tick on the Scores card. On “still holds ninety-one”, pass the second. On “the generation is two”, pass the third and show revision 2.

Leaves with Three passed assertions.

Beat refusals_and_rollback — What the real upgrade refuses

View and focus sequence.

Show tests/pocketic/root-authoring-lifecycle.mjs, the rejection loop and the late callback error step.

  await rejected('late callback error',/root rebind: IntentionalAfterSave[\s\S]*CanisterCalledTrap/,
    ()=>upgrade(id,artifacts['trap-after-save']));
  await assertOld();

Narration

On PocketIC the test starts from an installed version one with two values. A version two build that forgot to declare its predecessor is refused. Another build converts successfully and then fails in its restore callback. The whole upgrade is undone. The canister is version one again, with generation one and both values.

Cue and animation On “forgot to declare”, bring the undeclared build card to the strip and bounce it with root catalog rejected. On “converts successfully”, slide the trap build in, show revision 2 appear, then stamp restore failed. On “undone”, slide the v1 code card back and remove revision 2. On “both values”, pass assertOld with generation 1, 7 → 91, 8 → 92.

Hold or transition Hold on the restored V1. Balloon reads a failed upgrade is undone as a whole. The old program and its data are back.

Leaves with V1 running with both values.

Beat upgrade_and_no_return — Forward works, backward is refused

View and focus sequence.

Show The final steps of the lifecycle check.

  await upgrade(id,artifacts.v2);
  app=actor(id,artifacts.v2);
  // …
  await rejected('published target rejects downgrade',/root catalog rejected[\s\S]*CanisterCalledTrap/,
    ()=>upgrade(id,artifacts.v1));
  await assertNew();

Narration

The proper version two build upgrades. Generation is two, and keys seven and eight still hold their values. From here the old build is no longer accepted. The test tries to install version one again and it is refused. Later version two releases upgrade normally, and the app stays writable.

Cue and animation On “upgrades”, slide the v2 build in, run the Converter once, and show revision 2. On “still hold their values”, pulse 7 → 91 and 8 → 92. On “no longer accepted”, bounce the v1 build card. On “upgrade normally”, slide a second v2 card in with no converter run. On “stays writable”, add 9 → 93 in green.

Leaves with V2 running with revision 2 and three scores.

Beat limits — What a revision must fit inside

View and focus versions, with three short lines from the upgrade guide beneath.

Show Three paraphrased lines. The whole conversion runs inside one upgrade. No background or multi-step migration. Plan large data so unchanged parts can be moved, as Scores was.

Narration

One planning rule remains. The whole conversion runs inside the single upgrade. There is no background migration that continues afterward. So design a revision that fits, and move unchanged collections across whole, as this converter moved Scores, in place of rebuilding them row by row.

Cue and animation On “inside the single upgrade”, draw one bracket over the Converter labeled one upgrade. On “no background migration”, show a dashed second bracket struck through. On “move unchanged collections across whole”, replay the Scores card moving in one piece.

Leaves with The two version files, the converter and one bracket.

Try it

Verify Run the probe's native tests with its V2 feature from the newstack root. Testing

source tools/env.sh
cargo test --manifest-path tests/Cargo.toml --locked --offline \
  -p root-authoring-probe-canister --features v2

Expected app-level result. owner_conversion_preserves_the_existing_child passes, along with the probe's two other root tests.

Change, adapted exercise Write the same revision for a child module. In a copy of Quickstart, add scores/memory/v2.rs whose Data keeps scores: Map<u64, u32> and adds revision: u64. Write the data converter from the upgrade guide, which moves the map and sets the new field.

fn convert_data(_: &cdk_rsx_store::Upgrade<'_>, old: v1::Data)
    -> cdk_rsx_store::Result<v2::Data>
{
    Ok(v2::Data { scores: old.scores, revision: 0 })
}

The root's slot names an exact Scores version, so the root needs a new version too. Its converter takes the old Scores child, converts it with Upgrade::convert and this function, and attaches the result. Expected result in a native test is that a score saved under V1 reads back the same after opening as V2. This code is not in the checkout. The guide's sample above is quoted from the upgrade guide, and the probe shows only the root-level half. Convert within each owner

Source and review notes

Item shown Status
previous = [...] on #[cdk_rsx::root], Actor::upgrade, Upgrade::scope, Upgrade::convert, Store::root_contract, ModuleMemory::CONTRACT Shipped SDK API. Root upgrades
memory::upgrade, App::open, generation Written by the app.
Cargo features v2, undeclared-source, bad-policy, trap-after-save, the cfg_attr on the root attribute, and ROOT_POLICY Fixture devices that let one source tree build the accepted and the rejected images. A real app has no such gates.
forget_transient, runtime_snapshot and runtime.rs Probe-only methods for a separate SDK check. Keep them out of the film.
One-byte constructor limit INIT_LIMITS Probe-only demonstration of request_limits on the root attribute. Out of scope here.
  • The root attribute excerpt in declare_previous is the upgrade guide's sample. The probe's own attribute also carries error, arguments, policies and request_limits. Show the guide's form and say so on screen in the pane's tab.
  • The open excerpt drops the #[cfg(feature = "v2")] lines around the block. The Show field says so.
  • Rules to keep in the narration without showing how they are enforced. Only the current contract or an exactly declared predecessor is accepted. A converter reads its own data and delegates children. Conversion is synchronous, with no calls and no clocks. A failed upgrade is rolled back by the Internet Computer.
  • The upgrade guide asks authors to include startup, every conversion, any index rebuilding and validation when judging whether a revision fits the upgrade budget. The film reduces this to “design a revision that fits”. Leave the budget arithmetic to the guide. Single-upgrade migration policy
  • Hylix modules convert their records with the helpers named in the same guide section. The film does not cover them.
  • The memory series film 8 animates a migration at the storage level with a different fixture. Do not reuse its drawings here.