Rechain: State and Recorded History
The Stack: reading order
These three lessons explain one application from local state changes to transport and durable workflows:
- Rechain: reducers, atomic dispatch, recorded history, archives and verified reads.
- Reactor: typed endpoints, batched delivery, scheduling, results and events.
- Takt: typed workflow graphs, decisions, parallel work, recovery and inspection.
The combined reference is these three files concatenated in that order.
Contents
- Rechain's role
- Follow one dispatch
- Reducers, selectors and thunks
- One runtime, independent chains
- Blocks, hashes and public reads
- Certification and reader trust
- Archives and recovery
- Replay, projections and debugging
- Bounded idempotency
- Listeners and the shared scheduler
- Persistence and operational checklist
- Sources
Rechain's role
Rechain organizes changes to one canister's business state. The application submits an action. Its reducers either prepare the change together or reject it. A recorded chain also preserves the accepted action in an ordered, hash-linked history.
The three libraries divide responsibility:
| Machine | Owns | Example |
|---|---|---|
| Rechain | Local business state transitions and optional recorded history | Debit Alice and credit Bob in one dispatch |
| Reactor | Scheduling and batched communication between participating canisters | Carry a transfer request and its eventual result |
| Takt | Persisted workflow progress and decisions across steps | Collect payment, deliver an NFT, then pay its seller |
one canister
Takt workflow step ──synchronous dispatch──> Rechain reducers + history
│
└──Reactor request──> another canister's registered endpoint
Takt's progress is separate from reducer-owned business state. Reactor's transport acknowledgement is separate from business success. Rechain supplies the local transition; it does not make the remote part of this diagram atomic.
Think of business state as named folders, each owned by one reducer. The balances reducer owns balances; an offers reducer owns listings. A selector reads one owner's state without exposing mutable storage. An optional thunk reads selectors, decides which action to dispatch and returns an application result. A commit function is the callback returned by an accepting reducer; executing it performs that reducer's writes.
These are application boundaries, not a magical restriction on all Motoko code. Keep memories private and follow the ownership conventions. Rechain cannot prevent an endpoint from modifying a mutable reference that the application improperly exposes.
Follow one dispatch
Suppose Alice and Bob are accounts in the same canister, and a balances reducer owns both. A transfer action says to move 5 tokens from Alice to Bob. The reducer checks Alice's available balance and prepares a callback that will subtract 5 and add 5. Preparing this callback changes nothing.
Other reducers registered on that chain receive the same action. Each may inspect its own state and return:
| Response | Meaning |
|---|---|
#Pass |
This reducer has no change for this action |
#Ok(commit) |
Accepted; execute this callback if the dispatch succeeds |
#Err(error) |
Reject the entire dispatch |
For a recorded chain, the implementation follows this order:
- Call reducers in registration order and collect their callbacks.
- Stop immediately if any reducer rejects; discard the callbacks.
- Encode the action and append its block within configured storage limits.
- Execute the prepared callbacks in registration order, passing the block ID.
- Advance the action counter, update or schedule certification, schedule archival if needed, and invoke the optional listener.
The append happens before the callbacks so a storage failure cannot leave the business change without its record. All of this is synchronous, with no await. Other messages cannot observe the interval between these operations. The lesson animation spreads them out to show their relationship; it is one local dispatch.
If Alice has only 3 tokens, the balances reducer returns an error. If a later reducer rejects, Alice and Bob still remain unchanged. If encoding or storage fails after every reducer accepts, no prepared business write runs. A successful action can also have only #Pass responses: recording an accepted action does not require a state mutation.
This atomic boundary is one dispatch. A sequence of dispatches is not automatically an all-or-nothing group: returning an error from the second does not undo the first. Independent chains and remote canisters are outside this guarantee. A sharded transfer needs a workflow and an explicit participant recovery contract.
Expected failures return typed errors. Traps are programming failures, subject to Motoko's message rollback behavior; they are not a normal rejection result. Validate fallible prerequisites before returning a commit, and keep commit callbacks and listeners bounded and nontrapping. Never invoke a prepared callback yourself. The example reducer tests deliberately discard prepared callbacks to check that preparation has no effect.
Reducers, selectors and thunks
Here is the essential reducer from the actual counter example, with its surrounding class omitted:
public func reducer(action : T.Action) : Rechain.ReducerResponse<T.Error> {
let #Add(amount) = action else return #Pass;
if (amount == 0) return #Err(#ZeroIncrement);
#Ok(func(_blockId) { memory.value += amount })
};
The last line returns a function. It does not increment memory.value until Rechain executes that function. A real balances reducer uses the same pattern: read and validate its owned accounts, then return the debit/credit writes in one callback.
During preparation, a reducer may read only the action, its own memory and immutable configuration. It must not mutate a cache, perform cleanup, read another reducer's state, read the clock, call another canister or schedule a timer. Capture authenticated caller identity and timestamps at the host boundary and put required external inputs in the action. Validate those inputs appropriately; accepting a user-supplied caller field is not authentication.
Selectors expose immutable values, records or arrays. The counter selector returns memory.value through get(). It does not return the memory shell, a mutable map or a write callback. A thunk may combine several selectors; one reducer must not use another reducer's selector to validate its own action. This keeps state ownership and replay rules understandable.
A thunk is an ordinary synchronous application function, not another Rechain execution engine. The native creation thunk performs this sequence:
create(name)
read this chain's next block ID
derive the object's DCID from canister principal + block ID
dispatch Create({id; name})
return {id; blockId; name} on success
No await or intervening dispatch occurs between reading that ID and using it. The action contains the derived ID; the reducer validates and stores it. Replay does not rerun the original thunk decision. The ordinary API and a registered Reactor endpoint can call this same thunk. Direct actions can bypass it.
The example's application mixin owns persistent memory shells and reconstructs transient reducers and selectors. Public code receives a facade exposing dispatch and read-only selectors. This arrangement makes the ownership rules concrete.
One runtime, independent chains
Construct one Rechain.Runtime per canister and share it among typed Rechain.Chain<A,E> handles. The runtime owns physical storage, the certification tree and archive fleet. A handle binds a numeric chain ID, unique name, action type, error type, encoder, reducers and settings.
This abbreviated composition fragment follows the basic example. Action, AppError, balances, memory and reactor stand for application-owned objects:
transient let runtime = Rechain.Runtime<system>({
xmem = memory; settings = null;
});
runtime.useScheduler<system>(reactor.scheduler);
transient let payments = Rechain.Chain<system, Action, AppError>({
runtime; id = 0; name = "payments"; description = "Payment actions";
encodePayload = func(action) { CandidX.encode(action) };
reducers = [balances.reducer];
settings = null;
});
// Inside an update/endpoint:
// payments.dispatch<system>(action)
Chain IDs are Nat8 values, 0–255. Each chain starts block numbering at zero and maintains its own parent hash. An unrelated audit chain therefore does not consume payment IDs. Equal action histories can have equal hashes across chains; certified paths bind the chain identity. Reconstruct handles with the same IDs after upgrade and preserve each ID's action meaning. Duplicate IDs or names are rejected during binding.
There are two useful operating modes:
| Setting | Behavior |
|---|---|
recordTransactions = true |
Commit accepted actions and store/certify their blocks; archival can be enabled separately |
recordTransactions = false |
Commit accepted actions and advance the local action counter, without encoding, logging or archiving them |
An unrecorded chain is useful for reducer-owned maintenance or ephemeral projections, but those changes cannot be recovered from its nonexistent action log. Its certified state is explicitly #Unrecorded. Its stats().lastIndex advances while get_blocks(...).log_length remains zero. Recording mode cannot change after the action counter becomes nonzero.
With recording enabled but archiveEnabled = false, history remains local until capacity is exhausted; this setting does not discard old history. See the multi-chain example for different retention policies sharing one runtime.
Blocks, hashes and public reads
The current wire block has exactly two fields:
public type Block = { payload : Blob; phash : ?Blob };
payload is the original canonical CandidX encoding of the action. phash is the preceding block's hash, absent at genesis. Block ID and chain ID travel in surrounding response fields. Rechain uses its own typed protocol; ICRC-3 is a design reference, not a claim that these endpoints implement the ICRC-3 wire interface.
The V2 hash format is fixed:
genesis: SHA256(UTF8("rc") || 0x00 || payload)
later: SHA256(UTF8("rc") || 0x01 || phash || payload)
A present parent hash must contain 32 bytes. The outer Candid encoding of a query response is not part of this hash. Verify the original payload bytes before decoding into an application type: decoding and re-encoding through an older, narrower schema can drop fields and change the bytes.
The public API supplies:
| Runtime call | Use |
|---|---|
get_blocks(ranges, chain) |
Read local blocks and redirects for archived ranges |
get_chain_info({from}, chain) |
Discover metadata, format, local bounds and paginated archive ranges |
get_tip_certificate(chain) |
Obtain proof of selected published tips |
get_format() |
Identify payload encoding/profile and block hash version |
stats(chain) / runtime_stats() |
Inspect per-chain and shared storage/maintenance state |
For ordinary runtime reads, null selects chain 0. For get_tip_certificate(null), it selects all configured chains. Unknown IDs return #Err(#UnknownChain(id)). Bound handles already know their ID and expose selected results directly.
Reads can return a bounded prefix. Resume from the first missing block ID and follow redirects with their chain ID intact. Archive discovery uses from/next_archive; pass the last returned principal as the next cursor until a following page is empty. Do not infer missing history from one short response.
Certification and reader trust
A hash chain detects edits relative to a trusted hash. An attacker can still invent an entirely different internally consistent chain unless the reader authenticates its anchor.
Rechain publishes a Merkle root in the canister's certified_data. Its witness proves these paths for a selected chain:
rechain / chains / <one-byte chain ID> / state
rechain / chains / <one-byte chain ID> / last_block_index
rechain / chains / <one-byte chain ID> / last_block_hash
The state distinguishes empty, unrecorded and nonempty recorded chains. A nonempty tip includes its index and hash. Thus the certified value is not simply the raw previous-hash field.
A client requiring authenticated history must verify the IC certificate for the intended canister and acceptable freshness, verify the witness against its certified root, check the selected chain's leaves, and verify the block hashes against that tip. A missing query certificate is represented by a successful result containing null; it is not a proof. Correct verification detects a middleman changing the verified history, without making claims about whether the application's business logic is correct.
The certification manager may defer publication during busy periods. The first deferred write sets a fixed one-second publication deadline; later writes do not keep moving it. Until publication, returned proofs and tip snapshots describe the older published tip consistently. A newly returned block can therefore be ahead of the certified tip. Freshness policy belongs to the reader.
The library's polling Reader validates payload canonicality, consecutive IDs and parent hashes. It does not verify IC certificates. A reader starting at an arbitrary nonzero block also needs a separately trusted anchor for authenticated history. Certificate verification is an additional client responsibility; certificate tests exercise real signatures, witnesses and tampering.
Archives and recovery
Archive canisters hold older blocks while the source keeps a recent local suffix. One runtime coordinator fills one active archive with batches from different chains; each chain keeps independent contiguous ranges and parent links. When that destination reaches its configured record or page capacity, the coordinator rotates to another archive, subject to fleet limits.
Retention can be triggered by record count, optional byte thresholds, record age or storage pressure. A coalescing delay lets nearby writes accumulate. Once cleanup starts, its target becomes an absolute persisted endpoint, so retries and upgrades continue the same bounded work. Quiet chains can still reach their age deadline without another dispatch.
The critical handoff is:
source retains blocks → archive receives batch → source validates ACK
→ source removes acknowledged prefix
Validation checks destination, chain, accepted count, contiguous endpoint and capacity bounds. A lost reply does not authorize source deletion. Retrying overlap compares the exact existing payload and parent hash. A partial #Full result can acknowledge a prefix; the source retains the rest and rotates the full destination. An empty archive unable to hold even the first block stops automatic retries rather than looping indefinitely.
runtime.clean_up(null) advances one fair bounded batch; clean_up(?id) selects a chain. Results distinguish moved work, idle, disabled, busy and errors. Failed calls or invalid acknowledgements preserve unconfirmed records and can suspend automatic retries until a later dispatch, explicit retry or reconstruction. Monitor this rather than assuming archival always catches up. A writable existing archive remains usable even when the fleet registry is full.
The protocol is implemented in ArchiveManager and the archive canister, with lost-reply and recovery tests. Host APIs must authorize archive administration. These native archive calls do not become Reactor batches merely because maintenance uses Reactor's scheduler.
Replay, projections and debugging
Recorded actions can rebuild a state projection when you have the correct starting state, complete ordered history and the corresponding reducer semantics/configuration. Replay the accepted actions, not original thunk decisions or remote side effects. A third party can build a different projection for analytics, inspect changes, decide what to do, and call the public API under its normal authorization rules.
The Reader binds persistent memory to one source canister and one chain. Reconstruction with a different binding is refused. It follows bounded archive redirects, sorts IDs, rejects conflicting duplicates and validates a contiguous prefix before typed decoding and application. It never advances over a gap.
Its application callback is:
onRead : <system>([Action], Nat) -> {
#Ok : Nat;
#Err : { accepted : Nat; error : E };
}
The second argument is the first block ID. The returned count acknowledges a leading prefix, including when a later application error occurs. #Ok(0) defers the whole batch. Apply only the prefix you acknowledge; reporting more accepted actions than supplied traps. The saved cursor and last hash advance exactly through the acknowledged prefix and survive upgrades. The Reader fixture demonstrates partial application and errors.
For debugging, compare an action and block ID with state before and after its replay. A recorded history contains accepted actions; rejected attempts need separate application or workflow diagnostics. Also distinguish business history from Takt execution history: a block says which local transition committed; the workflow explains which step requested it and what happened before or after.
Bounded idempotency
A caller may not know whether a transfer committed after a reply is lost. Blindly creating another transfer can double the effect. Rechain's optional Idempotency reducer recognizes retained retries and returns the original block ID.
Install it before reducers that validate mutable balances, ownership, approvals or reservations. Otherwise a valid retry may fail against the state changed by its first success. It uses separate persistent memory per chain and pure adapters to select:
- The authenticated caller and current host receipt timestamp.
- Original metadata:
memo,created_at_time,expireAt. - Deterministic identity bytes containing every field that defines the effect, including operation kind and normalized accounts.
The caller must save and reuse the original request, metadata and identity encoding. The host receipt timestamp changes on retry and is excluded from stable identity. Changing a recipient, amount, metadata or selected bytes identifies another operation. Preserve saved bytes or a frozen encoder across upgrades; a different ordinary-Candid type table can change identity bytes even for apparently equal values.
The current implementation's rules are deliberately bounded:
| Condition | Result |
|---|---|
| Retained duplicate within the creation window | Mapped #DuplicateOf(originalBlockId) application error; no new commit or block |
| Creation time in the future | #CreatedInFuture; no future-drift allowance |
| At or beyond creation time + 24 hours | #TooOld |
Fresh admission at/after expireAt |
#TransactionExpired |
| Memo without creation time | #CreatedAtTimeRequired |
| No metadata, or expiry-only metadata | No deduplication; each successful dispatch is a new effect |
A retained duplicate is reported even after expireAt: that deadline prevents new admission, not recognition of existing success. The default index cap is 100,000 entries. Successful commits reclaim at most 1,000 expired entries; rejected calls do not mutate cleanup state. Live entries are not evicted to admit new work. A capacity error prevents the business commit.
Rechain reports duplicates through ordinary reducer errors; it does not automatically turn them into API success. An application adapter can map a validated duplicate to its original successful block reference.
This is not a permanent receipt service. #TooOld, a missing dedup entry or an elapsed deadline by itself cannot prove an earlier attempt had no effect. A participant's #TransactionExpired can establish rejection only under its documented contract: the unchanged request remains within full duplicate-retention coverage, retained success is checked first, and the deadline prevents any later new effect. Reactor's envelope #Expired does not supply that participant proof. See Takt's Rechain adapter for that classification.
After an uncertain operation loses its safe replay window, retain the workflow obligation and reconcile against immutable blocks or authoritative participant state. Do not refresh its timestamp or refund merely because retry admission has expired. Takt's remote-effect rules explain that boundary.
Listeners and the shared scheduler
chain.listen(listener) binds one transient listener to a recorded chain. It runs synchronously after storage, all reducer commits, the next-ID update and recorded-tip handling. It can observe committed state and queue a notification. It does not run for rejection, storage failure or an idempotency duplicate.
The listener has no preparation phase or error return. It cannot reject dispatch because a downstream queue lacks capacity. Keep it bounded and nontrapping, compose multiple notifications inside that one listener, and rebind it after upgrade. Unrecorded chains refuse listeners. Reliable downstream delivery needs the Reactor event/queue contract, not the assumption that calling a listener proves remote completion. See the listener tests.
Attach Rechain and any Readers to the host's existing reactor.scheduler during composition, before asynchronous work starts. Certification uses Control scheduling; archive work and Reader polling use Maintenance scheduling. A host without Reactor transport may construct the scheduler directly. Do not create a competing scheduler just for Rechain when Takt and Reactor already share one.
Scheduling determines when maintenance runs. It does not turn dispatch into an async operation, alter reducer ownership or automatically batch native calls. Reactor's scheduling reference describes priorities and callback reservations.
Persistence and operational checklist
Persistent memory holds business state, history, chain counters/hashes, archive ranges and pending transfers. Runtime objects, caches, listeners and timer handles are reconstructed. Reclaimed stable-region pages can serve another chain, but the allocated region cannot shrink. Cache eviction removes cached copies, not recorded history.
Useful current defaults include a 1,000,000-byte payload cap, 1,000 cached blocks per chain, count-triggered archival at 1,000,000 local records down toward 500,000, a 30-second coalescing delay, and at most 1,000 records per archive transfer. Wire-byte and storage limits still constrain a batch. These are source-version defaults, not capacity or throughput promises; see settings.
Dispatch distinguishes application errors from library errors: #PayloadEncodingFailed, #TransactionTooLarge, #StorageFull and #StorageUnavailable appear under #Err(#Rechain(...)). Storage pressure may schedule cleanup even while the rejected action leaves business state unchanged.
Before relying on the machine:
- Keep each reducer's persisted schema self-contained and its memory private. Reconstruct handles consistently, using one runtime and scheduler.
- Test that preparing or discarding a callback changes nothing, and that a late reducer rejection or storage failure leaves every prepared write unapplied.
- Handle bounded reads, archive backlogs and capacity errors; protect administrative APIs.
- Choose which chains must be replayable. Keep action codecs, historical semantics and trusted anchors needed by those readers.
- Retain exact retry identities and evidence for outstanding workflows. Test duplicate handling after state changes and upgrades.
- Rebind listeners, and verify that restored maintenance deadlines and pending archive work continue correctly.
The current repository is a development V2 format with plugin-enabled compiler dependencies. It does not supply a single-chain V1-to-V2 migration. Version persisted schemas deliberately and plan upgrades around live requests and historical decoding; do not infer compatibility from these examples. In particular, the current idempotency fingerprint format replaced an earlier development format without a legacy path: unresolved old-format requests require reconciliation and a planned cutover, not clearing their index.
Sources
Researched against local Rechain commit e3e0f24e2f01, a development source snapshot. The links above and below point to the working source repositories and may later change; this reference is not a published compatibility guarantee.
| Reference | Best use |
|---|---|
| README, public implementation, types | API contracts, defaults and dispatch ordering |
| Conventions, basic example | Reducer ownership, selectors, thunks and application layout |
| Block, certification | Exact bytes and proof publication |
| Archive manager, Reader | Handoff, bounded reads and replay |
| Idempotency, fingerprint | Request identity, expiry and bounded evidence |
| Runtime memory, test guide | Persistence and regression evidence |
Continue with Reactor: Scheduling and Batched Communication, then Takt: Durable, Typed Workflows.