Skip to main content

miden_core/mast/
sparse.rs

1use alloc::{
2    collections::{BTreeMap, BTreeSet},
3    string::ToString,
4    sync::Arc,
5    vec::Vec,
6};
7
8use miden_utils_indexing::newtype_id;
9
10use crate::{
11    Word,
12    advice::AdviceMap,
13    mast::{
14        ExecutableMastForest, MastForest, MastForestError, MastForestMergeSource,
15        MastForestRootMap, MastNode, MastNodeExt, MastNodeId, MixedMastForestMerger,
16    },
17    serde::DeserializationError,
18    utils::Idx,
19};
20
21// MAST FOREST ID
22// ================================================================================================
23
24// `MastForestId` is an opaque handle to a [`MastForest`] in some forest store such as an execution
25// trace replay's `mast_forest_store`. It is not a content-derived or stable identity for a forest,
26// and must not be compared or reused across stores or trace contexts. It is analogous to
27// `MastNodeId`, which is meaningful only within one forest's node store.
28newtype_id!(
29    #[cfg_attr(
30        all(feature = "arbitrary", test),
31        miden_test_serialization_macros::serialization_test
32    )]
33    pub struct MastForestId;
34);
35
36#[cfg(all(feature = "arbitrary", test))]
37use crate::serde::{Deserializable, Serializable};
38
39#[cfg(any(test, feature = "arbitrary"))]
40mod mast_forest_id_arbitrary {
41    use proptest::prelude::*;
42
43    use super::MastForestId;
44
45    impl Arbitrary for MastForestId {
46        type Parameters = ();
47        type Strategy = BoxedStrategy<Self>;
48
49        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
50            // Opaque u32 handle; edge-biased to the 0 and u32::MAX bounds.
51            prop_oneof![Just(0u32), Just(u32::MAX), any::<u32>()]
52                .prop_map(Self::from)
53                .boxed()
54        }
55    }
56}
57
58// SPARSE MAST FOREST
59// ================================================================================================
60
61/// A sparse replay view over a single source [`MastForest`]'s [`MastNodeId`] space, retaining only
62/// the nodes visited during execution.
63///
64/// Unlike [`MastForest`], which stores nodes contiguously in an `IndexVec`, a [`SparseMastForest`]
65/// uses a `BTreeMap` so that it can preserve the original [`MastNodeId`]s of the source forest
66/// while omitting nodes that were not visited. A [`SparseMastForest`] is not an independent forest
67/// shape: it shares its source forest's ID space, and is intended to back re-execution of the same
68/// program. Lookups by the original [`MastNodeId`] continue to resolve to the correct
69/// [`MastNode`]s.
70///
71/// In addition to the visited nodes, a [`SparseMastForest`] may also carry digest-only entries for
72/// nodes that were referenced during execution but never actually entered (e.g. the not-taken
73/// branch of a split, or the children of a join that only need to contribute their digests to the
74/// parent's trace row). These entries let trace generation read the digest without having to copy
75/// the full child node, and they make accidental entry into a pruned node a clean
76/// `get_node_by_id` miss rather than a partially-populated node.
77///
78/// Its serialized form is a version-local replay format. The default reader checks full-node
79/// hashes against available child digests. Digest-only entries and external nodes remain opaque:
80/// these checks do not prove membership in a source forest. The explicit trusted reader skips
81/// hash recomputation. This format must not be persisted across releases.
82#[derive(Debug)]
83pub struct SparseMastForest {
84    /// Subset of the original forest's nodes, keyed by their original [`MastNodeId`].
85    nodes: BTreeMap<MastNodeId, MastNode>,
86
87    /// Digests of nodes that were referenced (but not entered) during execution, keyed by their
88    /// original [`MastNodeId`]. Nodes present in [`Self::nodes`] are excluded from this map: a
89    /// full-node entry implicitly carries its own digest via [`MastNodeExt::digest`].
90    digests: BTreeMap<MastNodeId, Word>,
91
92    /// Roots of procedures defined within the original MAST forest.
93    roots: Vec<MastNodeId>,
94
95    /// Advice map to be loaded into the VM prior to executing procedures from this MAST forest.
96    advice_map: AdviceMap,
97}
98
99impl SparseMastForest {
100    /// Extracts the complete subgraphs reachable from selected procedure roots.
101    ///
102    /// Every selected root must be exported by `source`. Node IDs and child references remain in
103    /// the source forest's ID space, and repeated roots remain repeated in the result. All
104    /// reachable nodes are copied in full, including both split branches and call targets.
105    /// External and dynamic nodes are leaves. Advice data is not copied because sparse replay uses
106    /// `AdviceReplay`.
107    ///
108    /// This constructor assumes that `source` is valid. It does not rebuild node hashes or route
109    /// the nodes through a forest builder.
110    pub fn from_procedure_roots(
111        source: &MastForest,
112        roots: &[MastNodeId],
113    ) -> Result<Self, MastForestError> {
114        for &root in roots {
115            if !source.is_procedure_root(root) {
116                return Err(MastForestError::NotAProcedureRoot(root));
117            }
118        }
119
120        let mut nodes = BTreeMap::new();
121        let mut unvisited = roots.to_vec();
122        while let Some(node_id) = unvisited.pop() {
123            if nodes.contains_key(&node_id) {
124                continue;
125            }
126
127            let node = source.get_node_by_id(node_id).ok_or_else(|| {
128                MastForestError::NodeIdOverflow(node_id, source.num_nodes() as usize)
129            })?;
130            node.append_children_to(&mut unvisited);
131            nodes.insert(node_id, node.clone());
132        }
133
134        Ok(Self {
135            nodes,
136            digests: BTreeMap::new(),
137            roots: roots.to_vec(),
138            advice_map: AdviceMap::default(),
139        })
140    }
141
142    /// Merges dense and sparse forests into a sparse forest.
143    ///
144    /// Full nodes are deduplicated after remapping their children. Digest-only entries remain
145    /// opaque and are retained when no full node is available. Sparse replay forests cannot carry
146    /// advice data, so this returns an error if any input has a non-empty advice map.
147    pub fn merge<'forest, F>(
148        forests: impl IntoIterator<Item = F>,
149    ) -> Result<(Self, MastForestRootMap), MastForestError>
150    where
151        F: Into<MastForestMergeSource<'forest>>,
152    {
153        MixedMastForestMerger::merge_sparse(forests.into_iter().map(Into::into).collect())
154    }
155
156    pub(in crate::mast) fn from_merged_parts(
157        nodes: BTreeMap<MastNodeId, MastNode>,
158        digests: BTreeMap<MastNodeId, Word>,
159        roots: Vec<MastNodeId>,
160    ) -> Result<Self, MastForestError> {
161        let forest = Self {
162            nodes,
163            digests,
164            roots,
165            advice_map: AdviceMap::default(),
166        };
167        forest.validate()?;
168        Ok(forest)
169    }
170
171    /// Checks block invariants, child ordering, and full-node hashes.
172    ///
173    /// Digest-only entries and external nodes are opaque inputs to these checks. Their membership
174    /// in a particular source forest must be checked separately against that source.
175    pub fn validate(&self) -> Result<(), MastForestError> {
176        for (&node_id, node) in &self.nodes {
177            if let MastNode::Block(block) = node {
178                block
179                    .validate_batch_invariants()
180                    .map_err(|message| MastForestError::InvalidBatchPadding(node_id, message))?;
181            }
182            let computed = node.compute_digest(|child_id| {
183                if child_id >= node_id {
184                    return Err(MastForestError::ForwardReference(node_id, child_id));
185                }
186                self.get_digest_by_id(child_id)
187                    .ok_or_else(|| MastForestError::NodeIdOverflow(child_id, self.num_nodes()))
188            })?;
189            if computed != node.digest() {
190                return Err(MastForestError::HashMismatch {
191                    node_id,
192                    expected: node.digest(),
193                    computed,
194                });
195            }
196        }
197        Ok(())
198    }
199
200    /// Returns the underlying nodes of this sparse forest, keyed by their original
201    /// [`MastNodeId`].
202    pub fn nodes(&self) -> &BTreeMap<MastNodeId, MastNode> {
203        &self.nodes
204    }
205
206    /// Returns the minimum node count needed to cover all IDs retained in this sparse replay view.
207    ///
208    /// This is *not* the number of visited nodes and may be smaller than the source
209    /// [`MastForest`]'s node count when high source IDs were not needed during replay.
210    pub fn num_nodes(&self) -> usize {
211        self.nodes
212            .keys()
213            .chain(self.digests.keys())
214            .chain(self.roots.iter())
215            .map(|id| id.to_usize() + 1)
216            .max()
217            .unwrap_or(0)
218    }
219
220    /// Returns the roots of procedures defined within this sparse forest.
221    pub fn procedure_roots(&self) -> &[MastNodeId] {
222        &self.roots
223    }
224
225    /// Returns the empty advice map associated with this sparse forest.
226    ///
227    /// Sparse replay uses `AdviceReplay` for advice reads; this map remains empty to satisfy the
228    /// shared [`ExecutableMastForest`] interface.
229    pub fn advice_map(&self) -> &AdviceMap {
230        &self.advice_map
231    }
232
233    /// Returns the digest-only entries associated with this sparse forest.
234    pub(in crate::mast) fn digest_entries(&self) -> &BTreeMap<MastNodeId, Word> {
235        &self.digests
236    }
237
238    /// Builds a sparse forest from trusted replay parts.
239    pub(in crate::mast) fn from_serialized_parts(
240        nodes: Vec<(MastNodeId, MastNode)>,
241        digests: Vec<(MastNodeId, Word)>,
242        roots: Vec<MastNodeId>,
243        advice_map: AdviceMap,
244    ) -> Result<Self, DeserializationError> {
245        if !advice_map.is_empty() {
246            return Err(DeserializationError::InvalidValue(
247                "sparse MAST replay payload must not carry advice map entries".to_string(),
248            ));
249        }
250
251        let nodes = collect_unique_nodes(nodes)?;
252        let digests = collect_unique_digests(digests)?;
253
254        for &root in &roots {
255            validate_sparse_id(root, "procedure root")?;
256        }
257
258        for node_id in nodes.keys() {
259            if digests.contains_key(node_id) {
260                return Err(DeserializationError::InvalidValue(format!(
261                    "sparse full-node id {} overlaps a digest-only entry",
262                    node_id.0
263                )));
264            }
265        }
266
267        validate_full_node_child_digests(&nodes, &digests)?;
268
269        Ok(Self {
270            nodes,
271            digests,
272            roots,
273            advice_map: AdviceMap::default(),
274        })
275    }
276}
277
278fn validate_sparse_id(id: MastNodeId, label: &str) -> Result<(), DeserializationError> {
279    if id.to_usize() >= MastForest::MAX_NODES {
280        return Err(DeserializationError::InvalidValue(format!(
281            "{label} id {} exceeds maximum sparse MAST node id {}",
282            id.0,
283            MastForest::MAX_NODES - 1
284        )));
285    }
286    Ok(())
287}
288
289fn collect_unique_nodes(
290    nodes: Vec<(MastNodeId, MastNode)>,
291) -> Result<BTreeMap<MastNodeId, MastNode>, DeserializationError> {
292    let mut result = BTreeMap::new();
293    for (id, node) in nodes {
294        validate_sparse_id(id, "full node")?;
295        if result.insert(id, node).is_some() {
296            return Err(DeserializationError::InvalidValue(format!(
297                "duplicate sparse full-node id {}",
298                id.0
299            )));
300        }
301    }
302    Ok(result)
303}
304
305fn collect_unique_digests(
306    digests: Vec<(MastNodeId, Word)>,
307) -> Result<BTreeMap<MastNodeId, Word>, DeserializationError> {
308    let mut result = BTreeMap::new();
309    for (id, digest) in digests {
310        validate_sparse_id(id, "digest-only node")?;
311        if result.insert(id, digest).is_some() {
312            return Err(DeserializationError::InvalidValue(format!(
313                "duplicate sparse digest-only id {}",
314                id.0
315            )));
316        }
317    }
318    Ok(result)
319}
320
321/// Checks that every child of a retained full node is available as either a full node or a
322/// digest-only entry.
323fn validate_full_node_child_digests(
324    nodes: &BTreeMap<MastNodeId, MastNode>,
325    digests: &BTreeMap<MastNodeId, Word>,
326) -> Result<(), DeserializationError> {
327    for (&node_id, node) in nodes {
328        validate_sparse_id(node_id, "full node")?;
329
330        match node {
331            MastNode::Block(block) => {
332                block.validate_batch_invariants().map_err(|error_msg| {
333                    DeserializationError::InvalidValue(format!(
334                        "invalid sparse basic block {}: {error_msg}",
335                        node_id.0
336                    ))
337                })?;
338            },
339            MastNode::External(_) | MastNode::Dyn(_) => {},
340            MastNode::Join(join) => {
341                require_child_digest(node_id, join.first(), nodes, digests)?;
342                require_child_digest(node_id, join.second(), nodes, digests)?;
343            },
344            MastNode::Split(split) => {
345                require_child_digest(node_id, split.on_true(), nodes, digests)?;
346                require_child_digest(node_id, split.on_false(), nodes, digests)?;
347            },
348            MastNode::Loop(loop_node) => {
349                require_child_digest(node_id, loop_node.body(), nodes, digests)?;
350            },
351            MastNode::Call(call) => {
352                require_child_digest(node_id, call.callee(), nodes, digests)?;
353            },
354        }
355    }
356    Ok(())
357}
358
359fn require_child_digest(
360    parent_id: MastNodeId,
361    child_id: MastNodeId,
362    nodes: &BTreeMap<MastNodeId, MastNode>,
363    digests: &BTreeMap<MastNodeId, Word>,
364) -> Result<(), DeserializationError> {
365    validate_sparse_id(child_id, "child")?;
366    if child_id >= parent_id {
367        return Err(DeserializationError::InvalidValue(format!(
368            "sparse full node {} references non-preceding child {}",
369            parent_id.0, child_id.0
370        )));
371    }
372    if !nodes.contains_key(&child_id) && !digests.contains_key(&child_id) {
373        return Err(DeserializationError::InvalidValue(format!(
374            "sparse full node {} references child {} without a full node or digest-only entry",
375            parent_id.0, child_id.0
376        )));
377    }
378    Ok(())
379}
380
381impl ExecutableMastForest for SparseMastForest {
382    #[inline(always)]
383    fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
384        self.nodes.get(&node_id)
385    }
386
387    #[inline(always)]
388    fn get_digest_by_id(&self, node_id: MastNodeId) -> Option<Word> {
389        if let Some(node) = self.nodes.get(&node_id) {
390            return Some(node.digest());
391        }
392        self.digests.get(&node_id).copied()
393    }
394
395    #[inline(always)]
396    fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
397        // The `roots` list is copied wholesale from the source forest and may include roots that
398        // were never visited (and thus aren't present in `nodes`). Skip those gracefully rather
399        // than panicking via the `Index` impl.
400        self.roots.iter().find_map(|&root_id| {
401            let node = self.nodes.get(&root_id)?;
402            (node.digest() == digest).then_some(root_id)
403        })
404    }
405
406    #[inline(always)]
407    fn advice_map(&self) -> &AdviceMap {
408        &self.advice_map
409    }
410}
411
412// SPARSE MAST FOREST BUILDER
413// ================================================================================================
414
415/// Describes how a node referenced during execution should be represented in the resulting
416/// [`SparseMastForest`].
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum VisitKind {
419    /// The node was actually entered (or otherwise needs to be available in full at replay time).
420    /// The full [`MastNode`] is copied into [`SparseMastForest::nodes`].
421    FullVisit,
422    /// Only the node's digest is required at replay time (e.g. a child of a control-flow node
423    /// whose digest contributes to the parent's trace row, but which is itself never entered).
424    /// The digest is copied into the digest-only map; the full node is omitted.
425    DigestOnly,
426}
427
428/// Incrementally builds a [`SparseMastForest`] by collecting the [`MastNodeId`]s of nodes visited
429/// during execution of a single source [`MastForest`].
430///
431/// The builder retains a strong reference to the source forest so that it can copy out the visited
432/// nodes (and the source's roots, advice map, and debug info) at finalization time.
433///
434/// Each recorded id carries a [`VisitKind`] that controls whether the full node is copied or only
435/// its digest. If the same id is recorded as both a [`VisitKind::FullVisit`] and a
436/// [`VisitKind::DigestOnly`], the full-visit representation wins (the digest is recoverable from
437/// the full node).
438#[derive(Debug)]
439pub struct SparseMastForestBuilder {
440    /// The source forest whose nodes are being collected.
441    source: Arc<MastForest>,
442
443    /// IDs of nodes that were entered during execution. Their full [`MastNode`] is copied into the
444    /// finalized forest's `nodes` map.
445    full_visits: BTreeSet<MastNodeId>,
446
447    /// IDs of nodes that were only referenced (not entered) during execution. At finalization,
448    /// any id that also appears in [`Self::full_visits`] is excluded; the remainder contributes a
449    /// digest-only entry to the finalized forest.
450    digest_only_visits: BTreeSet<MastNodeId>,
451}
452
453impl SparseMastForestBuilder {
454    /// Creates a new builder for the given source forest.
455    pub fn new(source: Arc<MastForest>) -> Self {
456        Self {
457            source,
458            full_visits: BTreeSet::new(),
459            digest_only_visits: BTreeSet::new(),
460        }
461    }
462
463    /// Records a visit to the node with the provided id. Idempotent.
464    ///
465    /// If the same id is recorded both as [`VisitKind::FullVisit`] and as
466    /// [`VisitKind::DigestOnly`], the full-visit representation wins.
467    pub fn record_visit(&mut self, node_id: MastNodeId, kind: VisitKind) {
468        match kind {
469            VisitKind::FullVisit => {
470                self.full_visits.insert(node_id);
471            },
472            VisitKind::DigestOnly => {
473                self.digest_only_visits.insert(node_id);
474            },
475        }
476    }
477
478    /// Returns a strong reference to the source forest backing this builder.
479    pub fn source(&self) -> &Arc<MastForest> {
480        &self.source
481    }
482
483    /// Consumes the builder and produces a [`SparseMastForest`] containing only the visited nodes
484    /// from the source forest. The roots are cloned from the source in full. Advice data is not
485    /// copied because sparse replay uses `AdviceReplay`.
486    pub fn finalize(self) -> SparseMastForest {
487        let SparseMastForestBuilder { source, full_visits, digest_only_visits } = self;
488
489        let mut nodes = BTreeMap::new();
490        for node_id in &full_visits {
491            let node = source
492                .get_node_by_id(*node_id)
493                .expect("recorded full-visit id must exist in source forest");
494            nodes.insert(*node_id, node.clone());
495        }
496
497        let mut digests = BTreeMap::new();
498        for node_id in digest_only_visits {
499            if full_visits.contains(&node_id) {
500                continue;
501            }
502            let node = source
503                .get_node_by_id(node_id)
504                .expect("recorded digest-only id must exist in source forest");
505            digests.insert(node_id, node.digest());
506        }
507
508        SparseMastForest {
509            nodes,
510            digests,
511            roots: source.procedure_roots().to_vec(),
512            advice_map: AdviceMap::default(),
513        }
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use alloc::vec;
520
521    use super::*;
522    use crate::{
523        mast::{
524            BasicBlockNodeBuilder, CallNodeBuilder, DynNodeBuilder, ExternalNodeBuilder,
525            JoinNodeBuilder, LoopNodeBuilder, MastForestRead, SplitNodeBuilder,
526        },
527        operations::Operation,
528    };
529
530    #[test]
531    fn extraction_rejects_non_roots_and_handles_empty_selection() {
532        let mut source = MastForest::new();
533        let node = BasicBlockNodeBuilder::new(vec![Operation::Add])
534            .add_to_forest(&mut source)
535            .unwrap();
536
537        let empty = SparseMastForest::from_procedure_roots(&source, &[]).unwrap();
538        assert!(empty.nodes().is_empty());
539        assert!(empty.digest_entries().is_empty());
540        assert!(empty.procedure_roots().is_empty());
541        assert_eq!(empty.num_nodes(), 0);
542
543        assert_eq!(
544            SparseMastForest::from_procedure_roots(&source, &[node]).unwrap_err(),
545            MastForestError::NotAProcedureRoot(node)
546        );
547    }
548
549    #[test]
550    fn extraction_copies_the_complete_reachable_graph_once() {
551        let mut source = MastForest::new();
552        let shared = BasicBlockNodeBuilder::new(vec![Operation::Add])
553            .add_to_forest(&mut source)
554            .unwrap();
555        let other = BasicBlockNodeBuilder::new(vec![Operation::Mul])
556            .add_to_forest(&mut source)
557            .unwrap();
558        let split = SplitNodeBuilder::new([shared, other]).add_to_forest(&mut source).unwrap();
559        let call = CallNodeBuilder::new(split).add_to_forest(&mut source).unwrap();
560        let root = JoinNodeBuilder::new([call, shared]).add_to_forest(&mut source).unwrap();
561        source.make_root(root);
562
563        let sparse = SparseMastForest::from_procedure_roots(&source, &[root]).unwrap();
564
565        assert_eq!(sparse.procedure_roots(), &[root]);
566        assert_eq!(sparse.nodes().len(), 5);
567        assert!(sparse.digest_entries().is_empty());
568        for node_id in [shared, other, split, call, root] {
569            assert_eq!(sparse.get_node_by_id(node_id), source.get_node_by_id(node_id));
570        }
571        assert!(sparse.is_source_subset_of(&source));
572
573        let repeated = SparseMastForest::from_procedure_roots(&source, &[root, root]).unwrap();
574        assert_eq!(repeated.procedure_roots(), &[root, root]);
575        assert_eq!(repeated.nodes().len(), sparse.nodes().len());
576    }
577
578    #[test]
579    fn extraction_stops_at_external_and_dynamic_nodes() {
580        let mut source = MastForest::new();
581        let external =
582            ExternalNodeBuilder::new(Word::default()).add_to_forest(&mut source).unwrap();
583        let call = CallNodeBuilder::new(external).add_to_forest(&mut source).unwrap();
584        let dynamic = DynNodeBuilder::new_dyn().add_to_forest(&mut source).unwrap();
585        source.make_root(call);
586        source.make_root(dynamic);
587
588        let sparse = SparseMastForest::from_procedure_roots(&source, &[call, dynamic]).unwrap();
589
590        assert_eq!(sparse.nodes().len(), 3);
591        assert!(sparse.nodes().contains_key(&external));
592        assert!(sparse.nodes().contains_key(&call));
593        assert!(sparse.nodes().contains_key(&dynamic));
594    }
595
596    #[test]
597    fn extraction_follows_loop_bodies_and_their_descendants() {
598        let mut source = MastForest::new();
599        let left = BasicBlockNodeBuilder::new(vec![Operation::Add])
600            .add_to_forest(&mut source)
601            .unwrap();
602        let right = BasicBlockNodeBuilder::new(vec![Operation::Mul])
603            .add_to_forest(&mut source)
604            .unwrap();
605        let body = JoinNodeBuilder::new([left, right]).add_to_forest(&mut source).unwrap();
606        let root = LoopNodeBuilder::new(body).add_to_forest(&mut source).unwrap();
607        source.make_root(root);
608
609        let sparse = SparseMastForest::from_procedure_roots(&source, &[root]).unwrap();
610
611        assert_eq!(sparse.nodes().len(), 4);
612        for node_id in [left, right, body, root] {
613            assert_eq!(sparse.get_node_by_id(node_id), source.get_node_by_id(node_id));
614        }
615    }
616
617    #[test]
618    fn extraction_preserves_large_source_id_gaps() {
619        let mut source = MastForest::new();
620        for _ in 0..1_000 {
621            BasicBlockNodeBuilder::new(vec![Operation::Add])
622                .add_to_forest(&mut source)
623                .unwrap();
624        }
625        let root = BasicBlockNodeBuilder::new(vec![Operation::Mul])
626            .add_to_forest(&mut source)
627            .unwrap();
628        source.make_root(root);
629
630        let sparse = SparseMastForest::from_procedure_roots(&source, &[root]).unwrap();
631
632        assert_eq!(sparse.nodes().len(), 1);
633        assert_eq!(sparse.num_nodes(), root.to_usize() + 1);
634        assert_eq!(sparse.get_node_by_id(root), source.get_node_by_id(root));
635    }
636
637    #[test]
638    fn extraction_handles_deep_call_chains_iteratively() {
639        const DEPTH: usize = 16_384;
640
641        let mut source = MastForest::new();
642        let mut root = BasicBlockNodeBuilder::new(vec![Operation::Add])
643            .add_to_forest(&mut source)
644            .unwrap();
645        for _ in 0..DEPTH {
646            root = CallNodeBuilder::new(root).add_to_forest(&mut source).unwrap();
647        }
648        source.make_root(root);
649
650        let sparse = SparseMastForest::from_procedure_roots(&source, &[root]).unwrap();
651
652        assert_eq!(sparse.nodes().len(), DEPTH + 1);
653        assert_eq!(sparse.procedure_roots(), &[root]);
654    }
655}