RRT Heavy16: A Ledger Command Recorded Once
Audience task and outcome
- Task Count work commands by kind and total their units. A retry of the same dated command within its replay window should return the original result.
- Observable outcome The viewer can find their way around a large app by its folders and write a Rechain reducer by implementing its two traits, a read-only
preparethat can refuse and acommitthat writes. In the ledger test, sending five commands twice produces five blocks in total,25units and the original block number for each repeat. - Starting point Lesson 3 put refusals before changes inside one method. Lesson 7 finished the single-module material.
- Handoff Lesson 9 runs these commands as steps of a workflow.
- Pacing Four and a half minutes.
The worked example
RRT Heavy16 is the SDK's large benchmark application. Its canister source is benches/rrt/canister. One canister holds its own modules, ledger, config, admissions and flows, beside three libraries, Rechain for recorded history, Reactor for delivery between canisters, and Takt for workflows. This film uses the ledger. A command has a kind, one of Open, Reserve, Deliver, Close or Audit, and a number of units. The ledger test dispatches one command of each kind with 5 units, then dispatches each again. Every repeat returns the block number of the original. The total is 25, each count is 1, and the chain's next index is 5. A command from the wrong caller returns Unauthorized, and one with 0 units returns InvalidUnits. RRT benchmark · Ledger · Ledger data V1 · Ledger test · Root
Rechain dispatches an action through synchronous reducers and keeps a bounded history. Its documented order is that every expected rejection finishes before the prepared plan is committed. Rechain · Reducer traits · Orchestration
A shorter reducer example is the Basic Rechain canister. It is a good second read after this film. Basic Rechain canister
The story in one pass
Open the Heavy16 tree and recognize the Shop's layout in it. Look at the root's children, some written by the app and some provided by libraries. Then build the ledger feature. Declare its data, write prepare, write commit, and dispatch a command through Rechain with a replay check in front. Send the same command twice and see one block. Send two bad commands and see typed refusals with nothing recorded.
Views and visual objects
Use the shared visual language. The Heavy16 AppTree shows lib.rs, api.rs, wire.rs, root/, ledger/, config/, admissions/, flows/ and workflows/. Keep these positions for lesson 9. Benchmark-only files metrics.rs, protocol.rs and ingress.rs are drawn dimmed with a small bench tag and are never opened.
The App frame holds ModuleCards in two tints. App modules, Ledger, Config, Admissions and Flows, use the usual tint. Library modules, Rechain, Replay, Reactor and Reactor runtime, use a quieter tint and a library tag. Their drawers stay closed. The Rechain card shows its history as the blue numbered blocks from the earlier films, each with only its padded index and action, such as 000 and Open(5). The Ledger's StateCard has rows counts and total.
| View | Framing and anchor |
|---|---|
heavy_tree |
Heavy16 AppTree at left, the Shop AppTree small beside it for comparison. |
heavy_app |
The App frame with all module cards. Anchor on Ledger and Rechain. |
ledger_code |
One or two EditorPane columns on ledger/ files, with Ledger and Rechain cards beneath. |
test |
TestPanel with ledger/tests.rs, Ledger StateCard and the block row. |
Scene read_large_app — The same shape, more modules
Enters with The Shop AppTree from earlier lessons.
Beat tree — Recognize the layout
View and focus heavy_tree.
Show The listing of benches/rrt/canister/src. Point at ledger/, then at ledger/memory/v1.rs, then at root/.
Narration
This is RRT Heavy16, a much larger application. Its layout is the one we know. Each feature has a folder with its service and a versioned memory folder. The root wires them together. Endpoints are in lib dot r s.
Cue and animation On “a much larger application”, grow the Heavy16 tree beside the small Shop tree. On “a folder with its service”, draw matching brackets on ledger/ and on the Shop's settings/. On “The root wires them together”, bracket both root/ folders. On “Endpoints”, bracket both lib.rs files.
Leaves with Two trees with three matching brackets.
Beat root_children — App modules and library modules
View and focus heavy_app, with a pane on root/memory/v1.rs.
Show src/root/memory/v1.rs lines 12 to 21.
cdk_rsx_store::module_children! {pub struct Children{
pub(in crate::root) reactor_runtime:ChildSlot<cdk_rsx_reactor::memory::v1::RuntimeMemory>,
pub(in crate::root) reactor:ChildSlot<cdk_rsx_reactor::memory::v1::ReactorMemory>,
pub(in crate::root) rechain:ChildSlot<cdk_rsx_rechain::memory::v1::Memory>,
pub(in crate::root) replay:ChildSlot<cdk_rsx_rechain::idempotency::memory::v1::Memory>,
pub(in crate::root) work:ChildSlot<crate::ledger::memory::v1::Memory>,
pub(in crate::root) config:ChildSlot<crate::config::memory::v1::Memory>,
pub(in crate::root) admissions:ChildSlot<crate::admissions::memory::v1::Memory>,
pub(in crate::root) flows:ChildSlot<crate::flows::memory::v1::Memory>,
}}
Narration
The root lists eight children. Four belong to the application, and the ledger's is called work. The other four come from libraries. Rechain keeps a recorded history, its replay module remembers recent commands, and Reactor delivers messages between canisters. A library module is attached just like your own, and you use it through its service.
Cue and animation On “Four belong to the application”, seat the Ledger, Config, Admissions and Flows cards. On “called work”, band the work line. On “come from libraries”, seat the four library cards in the quieter tint. On “attached just like your own”, band rechain:ChildSlot<…> beside work:ChildSlot<…>.
Leaves with A full App frame with eight cards.
Scene ledger_feature — Validate, then write
Enters with The App frame focused on Ledger and Rechain. The Ledger card is complete, with an empty StateCard.
Beat ledger_data — What the ledger saves
View and focus ledger_code, pane on ledger/memory/v1.rs.
Show Lines 4 to 12.
#[repr(C)]
#[derive(NyxusData)]
pub struct Data {
pub(in crate::ledger) owner: Principal,
pub(in crate::ledger) counts: [u64; 5],
pub(in crate::ledger) total: u64,
pub(in crate::ledger) has_last_caller: bool,
pub(in crate::ledger) last_caller: Principal,
}
Narration
The request is to count commands by kind and add up their units. The ledger's data has an owner, five counts, one for each kind, a total, and the last caller.
Cue and animation On “count commands by kind”, show the request note. On “five counts”, band counts and show counts 0 0 0 0 0 on the StateCard. On “a total”, band total and show total 0.
Leaves with A zeroed ledger.
Beat prepare — The read-only half
View and focus ledger_code, pane on ledger/mod.rs.
Show Lines 104 to 124 and 137 to 142, the Prepare implementation, with the kind-to-index lines elided.
impl<A: Access> Prepare<Envelope<'_>> for WorkView<'_, A> {
type Error = wire::BusinessError;
type Plan = Plan;
fn prepare(&self, e: &Envelope<'_>) -> Result<core::result::Result<Plan, Self::Error>> {
use wire::BusinessError as Error;
let state = self.state.read()?;
if e.action.caller != state.owner {
return Ok(Err(Error::Unauthorized));
}
// …
if !(1..=1_000_000).contains(&units) {
return Ok(Err(Error::InvalidUnits));
}
let Some(total) = state.total.checked_add(units) else {
return Ok(Err(Error::InvalidUnits));
};
// …
Ok(Ok(Plan {
counts,
total,
caller: e.action.caller,
}))
}
}
Narration
A Rechain reducer has two halves. Prepare is written for any access, so it can only read. It checks the caller against the owner and the units against a range, and it uses checked arithmetic. Each failure returns a typed business error. If everything passes it returns a plan, which holds the new counts and the new total. Nothing has been written.
Cue and animation On “it can only read”, band impl<A: Access> and self.state.read(). On “the caller against the owner”, band the first if. On “against a range”, band the range check. On “a typed business error”, show two neutral ReceiptCards, Unauthorized and InvalidUnits. On “returns a plan”, lift a small Plan chip showing counts 1 0 0 0 0 · total 5 above the Ledger card. On “Nothing has been written”, keep the StateCard at zero.
Leaves with A Plan chip hovering over an unchanged ledger.
Beat commit — The writing half
View and focus ledger_code.
Show Lines 144 to 153.
impl Commit<Envelope<'_>> for WorkView<'_, Scope<'_>> {
fn commit(&self, plan: Plan, _: u64, _: &CommitToken) -> Result<()> {
let mut state = self.state.write()?;
state.counts = plan.counts;
state.total = plan.total;
state.has_last_caller = true;
state.last_caller = plan.caller;
Ok(())
}
}
Narration
Commit exists only under a write scope. It takes the plan and stores it. It makes no decisions and has nothing to refuse. Rechain calls it after the action has been accepted and recorded.
Cue and animation On “only under a write scope”, band Scope<'_>. On “stores it”, drop the Plan chip into the drawer and change counts and total in green. On “nothing to refuse”, band the absence of any if with a quiet bracket over the body. On “accepted and recorded”, forge block 000 Open(5) in the Rechain card's row.
Hold or transition Hold with the block forged. Balloon across both impl headers reads prepare refuses, commit writes. This is the split from lesson 3, now enforced by two traits.
Leaves with counts 1 0 0 0 0, total 5, and block 000.
Beat dispatch — One call puts it together
View and focus ledger_code.
Show Lines 236 to 247 of Commands::dispatch, with the action-building lines above and the listener closure below elided.
let result = self
.commands
.chain
.view(self.access)
.dispatch::<Business, _>(
&envelope,
&self
.commands
.replay
.view(self.access)
.with(self.commands.work.view(self.access)),
now,
Narration
The ledger's Commands service ties it together. It asks Rechain to dispatch the action on the business chain. The reducer it passes is the work view wrapped by the replay module. Replay runs first and recognizes a command it has already seen.
Cue and animation On “asks Rechain to dispatch”, band .dispatch::<Business, _> and move a pill Open(5) into the Rechain card. On “the work view”, band self.commands.work.view(self.access) and link to the Ledger card. On “wrapped by the replay module”, band .replay.view(self.access).with( and place the Replay card as a gate in front of the Ledger card.
Leaves with The path Commands → Rechain → Replay → Ledger drawn once.
Scene prove_it — The ledger test
Enters with A fresh ledger and an empty block row.
Beat once — Five commands, sent twice
View and focus test.
Show src/ledger/tests.rs, the loop at the top of five_actions_replay_rejection_and_cleanup_preserve_owner_boundary, then the three assertions after it.
assert_eq!(
commands.dispatch(Principal::anonymous(), 100, command(kind).as_ref())?,
Ok((n as u64).into())
);
assert_eq!(
commands.dispatch(Principal::anonymous(), 1001, command(kind).as_ref())?,
Ok((n as u64).into())
);
assert_eq!(select.total()?, cdk_rsx::wire::Nat::from(25u8));
assert_eq!(commands.retained()?, cdk_rsx::wire::Nat::from(5u32));
Narration
The test sends one command of each kind with five units. Each returns its block number, zero through four. It sends the same dated commands again within the replay window. Keep the original creation time on a retry. Each repeat returns the same block number, and the total stays twenty-five.
Cue and animation On “one command of each kind”, send five pills and forge blocks 000 to 004, updating counts to 1 1 1 1 1 and total to 25. On “within the replay window”, send Open(5) again. On “original creation time”, highlight that field on the duplicated command. Return ReceiptCard Ok(0) pointing to block 000. Repeat quickly for the other four. On “the total stays twenty-five”, pulse the total and pass the assertions.
Leaves with Five blocks, counts 1 1 1 1 1, total 25.
Beat refused — Typed refusals, nothing recorded
View and focus test.
Show The next assertions in the same test.
Err(wire::DispatchError::App(wire::BusinessError::Unauthorized))
Err(wire::DispatchError::App(wire::BusinessError::InvalidUnits))
assert_eq!(chain.stats(0)?.unwrap().next_index, 5);
Narration
Two more commands are refused. One comes from a caller who is not the owner. The other asks for zero units. Each returns its typed error from prepare. The chain's next index is still five, so no block was spent on either.
Cue and animation On “not the owner”, send a pill from a different caller and return Unauthorized. On “zero units”, send Open(0) and return InvalidUnits. On “still five”, show an empty slot after block 004 labeled next 005 and pass the assertion. The block row stays stationary.
Leaves with Five blocks and two refusal receipts.
Beat read_side — Reading goes through selectors
View and focus heavy_app, with a pane on ledger/selectors.rs.
Show src/ledger/selectors.rs, the total and owner methods, and src/lib.rs lines 117 to 120, inside add_peer, for an endpoint that uses one.
pub fn total(&self) -> Result<cdk_rsx::wire::Nat> {
Ok(self.total_value()?.into())
}
root::with(|app| {
if cdk_rsx::api::msg_caller() != app.select().owner()? || peer == Principal::anonymous() {
return Ok(false);
}
Narration
Other code never reads the ledger's fields. It uses the ledger's selectors, small read-only methods such as total and owner. Endpoints call them through the root, just as the Shop's endpoints called tax.
Cue and animation On “the ledger's selectors”, add counts, total, owner and last_caller to the Ledger card's read group. On “Endpoints call them”, band app.select().owner() and send a read call to the card.
Leaves with The Heavy16 App frame with a working ledger. Lesson 9 sends it commands from a workflow.
Try it
Verify Run the ledger tests from the newstack root. RRT benchmark, native checks
source tools/env.sh
cargo test --manifest-path benches/rrt/Cargo.toml --locked --offline \
-p rrt-fourcans-canister ledger
Expected app-level result. five_actions_replay_rejection_and_cleanup_preserve_owner_boundary passes with the other ledger tests.
Change, adapted exercise Tighten a business rule and test it. In your copy, change the units range in prepare from 1..=1_000_000 to 1..=100_000. Add a test that dispatches a command with 100_001 units and asserts Err(DispatchError::App(BusinessError::InvalidUnits)), that select.total() is unchanged, and that the chain's next_index did not advance. Expected result is that your test passes and the existing tests still pass, since they use 5 units. This change is not in the checkout. It edits ledger/mod.rs only, so by lesson 6 it is a business-code change.
Source and review notes
| Item shown | Status |
|---|---|
cdk_rsx_rechain::{Prepare, Commit, CommitToken, Chain, ChainConfig}, View::dispatch, idempotency::Idempotency and its with |
Shipped Rechain API. Rechain |
Work, WorkView, Plan, Commands, Envelope, Selectors, convert, chains() |
Heavy16 application code. |
wire::Command, wire::BusinessError, wire::DispatchError |
Heavy16's own message types in wire.rs. |
Lines under #[cfg(feature = "tripwire-workload")], protocol.rs, ingress.rs |
Optional protocol variant of the benchmark. Hide these lines in every excerpt. |
config::should_reject, test_reject_next, endpoint telemetry, metrics.rs, page and instruction profiling |
Benchmark controls and measurement. Out of frame. |
root/admission.rs, the HotRoot static, the hand-written Root, RootView and Bindings, and the hand-written Work and WorkView service types |
Heavy16 writes by hand what the #[cdk_rsx::service] and #[cdk_rsx::root(state = App, …)] attributes provide. Developers use the attributes, as in lessons 1 and 2. Keep these types out of frame and do not explain them. Crop ledger excerpts to the Prepare and Commit implementations. |
- The Rechain README states the ordering guarantee used in
commit. Expected rejections finish before the plan is committed, and a failure after a saved change traps so the Internet Computer rolls back history and reducers together. The film shows the first half and does not show how Rechain stores or hashes blocks. - Blocks on screen show only their index and action, following the workspace block style.
- The repeat in the test arrives at time
1001. It passes the same caller and dated command. Rechain's idempotency API uses a 24-hour replay window for dated requests, refuses stale creation times and requires a creation time when a memo is present. Keep request construction and the retry deadline visible to the app author. The replay index and its maintenance stay off screen. Ledger test · Idempotency contract Commands::dispatchalso passes a closure that publishes a notice for Audit commands with a topic. It runs after commit inside the same call. Leave it elided and mention it in lesson 9 only if needed.- A second native test,
composed_root_rebind_preserves_history_replay_reducer_and_peer_stateinsrc/tests.rs, rebuilds the whole Heavy16 root over the same Store and checks that total, history and replay survive. Use it if the edit wants a rebuild beat like lessons 1 and 2. Whole-app test - Heavy16's internal package name is
rrt-fourcans-canister. Say “RRT Heavy16” in narration.