Skip to main content

miden_core/mast/merger/
mod.rs

1use alloc::{collections::BTreeMap, vec::Vec};
2
3mod mixed;
4pub use mixed::MastForestMergeSource;
5pub(crate) use mixed::MixedMastForestMerger;
6
7use crate::{
8    Word,
9    mast::{
10        DenseMastForestBuilder, MastForest, MastForestContributor, MastForestError, MastNode,
11        MastNodeBuilder, MastNodeId, MultiMastForestIteratorItem, MultiMastForestNodeIter,
12    },
13    utils::{DenseIdMap, IndexVec},
14};
15
16#[cfg(test)]
17mod tests;
18
19/// A type that allows merging [`MastForest`]s.
20///
21/// This functionality is exposed via [`MastForest::merge`]. See its documentation for more details.
22pub(crate) struct MastForestMerger {
23    mast_forest: DenseMastForestBuilder,
24    // Internal indices needed for efficient duplicate checking.
25    //
26    // These are always in-sync with the nodes in `mast_forest`, i.e. all nodes added to the
27    // `mast_forest` are also added to the indices.
28    node_id_by_hash: BTreeMap<Word, MastNodeId>,
29    hash_by_node_id: IndexVec<MastNodeId, Word>,
30    /// Mappings from previous `MastNodeId`s to their new ids.
31    ///
32    /// Any `MastNodeId` in `mast_forest` is present as the target of some mapping in this map.
33    node_id_mappings: Vec<DenseIdMap<MastNodeId, MastNodeId>>,
34}
35
36impl MastForestMerger {
37    /// Creates a new merger with an initially empty forest and merges all provided [`MastForest`]s
38    /// into it.
39    ///
40    /// # Normalizing Behavior
41    ///
42    /// This function performs normalization of the merged forest, which:
43    /// - Remaps all node IDs to maintain the invariant that child node IDs < parent node IDs
44    /// - Creates a clean, deduplicated forest structure
45    /// - Provides consistent node ordering regardless of input
46    ///
47    /// This normalization is idempotent, but it means that even for single-forest merges, the
48    /// resulting forest may have different node IDs and digests than the input. See assembly
49    /// test `issue_1644_single_forest_merge_identity` for detailed explanation of this
50    /// behavior.
51    pub(crate) fn merge<'forest>(
52        forests: impl IntoIterator<Item = &'forest MastForest>,
53    ) -> Result<(MastForest, MastForestRootMap), MastForestError> {
54        let forests = forests.into_iter().collect::<Vec<_>>();
55
56        let node_id_mappings =
57            forests.iter().map(|f| DenseIdMap::with_len(f.nodes().len())).collect();
58
59        let mut merger = Self {
60            node_id_by_hash: BTreeMap::new(),
61            hash_by_node_id: IndexVec::new(),
62            mast_forest: DenseMastForestBuilder::new(),
63            node_id_mappings,
64        };
65
66        merger.merge_inner(forests.clone())?;
67
68        let Self { mast_forest, node_id_mappings, .. } = merger;
69        let (mast_forest, final_id_remapping) = mast_forest.build_with_id_map()?;
70        let node_id_mappings =
71            Self::remap_finalized_node_ids(node_id_mappings, &final_id_remapping);
72
73        let root_maps = MastForestRootMap::from_node_id_map(node_id_mappings, forests);
74
75        Ok((mast_forest, root_maps))
76    }
77
78    /// Merges all `forests` into self.
79    ///
80    /// It does this in three steps:
81    ///
82    /// 1. Merge all advice maps, checking for key collisions.
83    /// 2. Merge all nodes of forests.
84    ///    - Node indices might move during merging, so the merger keeps a node id mapping as it
85    ///      merges nodes.
86    ///    - This is a depth-first traversal over all forests to ensure all children are processed
87    ///      before their parents. See the documentation of [`MultiMastForestNodeIter`] for details
88    ///      on this traversal.
89    ///    - Because all parents are processed after their children, we can use the node id mapping
90    ///      to remap all [`MastNodeId`]s of the children to their potentially new id in the merged
91    ///      forest.
92    ///    - If any external node is encountered during this traversal with a digest `foo` for which
93    ///      a `replacement` node exists in another forest with digest `foo`, then the external node
94    ///      will be replaced by that node. In particular, it means we do not want to add the
95    ///      external node to the merged forest, so it is never yielded from the iterator.
96    ///      - Assuming the simple case, where the `replacement` was not visited yet and is just a
97    ///        single node (not a tree), the iterator would first yield the `replacement` node which
98    ///        means it is going to be merged into the forest.
99    ///      - Next the iterator yields [`MultiMastForestIteratorItem::ExternalNodeReplacement`]
100    ///        which signals that an external node was replaced by another node. In this example,
101    ///        the `replacement_*` indices contained in that variant would point to the
102    ///        `replacement` node. Now we can simply add a mapping from the external node to the
103    ///        `replacement` node in our node id mapping which means all nodes that referenced the
104    ///        external node will point to the `replacement` instead.
105    /// 3. Finally, we merge all roots of all forests. Here we map the existing root indices to
106    ///    their potentially new indices in the merged forest and add them to the forest,
107    ///    deduplicating in the process, too.
108    fn merge_inner(&mut self, forests: Vec<&MastForest>) -> Result<(), MastForestError> {
109        for other_forest in forests.iter() {
110            self.merge_advice_map(other_forest)?;
111        }
112        let iterator = MultiMastForestNodeIter::new(forests.clone());
113        for item in iterator {
114            match item {
115                MultiMastForestIteratorItem::Node { forest_idx, node_id } => {
116                    let node = forests[forest_idx][node_id].clone();
117                    self.merge_node(forest_idx, node_id, node, &forests)?;
118                },
119                MultiMastForestIteratorItem::ExternalNodeReplacement {
120                    // forest index of the node which replaces the external node
121                    replacement_forest_idx,
122                    // ID of the node that replaces the external node
123                    replacement_mast_node_id,
124                    // forest index of the external node
125                    replaced_forest_idx,
126                    // ID of the external node
127                    replaced_mast_node_id,
128                } => {
129                    // The iterator is not aware of the merged forest, so the node indices it yields
130                    // are for the existing forests. That means we have to map the ID of the
131                    // replacement to its new location, since it was previously merged and its IDs
132                    // have very likely changed.
133                    let mapped_replacement = self.node_id_mappings[replacement_forest_idx]
134                        .get(replacement_mast_node_id)
135                        .expect("every merged node id should be mapped");
136
137                    // SAFETY: The iterator only yields valid forest indices, so it is safe to index
138                    // directly.
139                    self.node_id_mappings[replaced_forest_idx]
140                        .insert(replaced_mast_node_id, mapped_replacement);
141                },
142            }
143        }
144
145        for (forest_idx, forest) in forests.iter().enumerate() {
146            self.merge_roots(forest_idx, forest);
147        }
148
149        Ok(())
150    }
151
152    fn merge_advice_map(&mut self, other_forest: &MastForest) -> Result<(), MastForestError> {
153        self.mast_forest.merge_advice_map(other_forest.advice_map())
154    }
155
156    fn merge_node(
157        &mut self,
158        forest_idx: usize,
159        merging_id: MastNodeId,
160        node: MastNode,
161        original_forests: &[&MastForest],
162    ) -> Result<(), MastForestError> {
163        // We need to remap the node prior to computing the node fingerprint since child IDs may
164        // have changed in the merged forest.
165        //
166        // Remapping at this point is guaranteed to be "complete", meaning all IDs of children
167        // will be present in the node id mapping since the DFS iteration guarantees
168        // that all children of this `node` have been processed before this node and
169        // their indices have been added to the mappings.
170        let remapped_builder = self.build_with_remapped_children(
171            merging_id,
172            node,
173            original_forests[forest_idx],
174            &self.node_id_mappings[forest_idx],
175        )?;
176
177        let node_fingerprint =
178            remapped_builder.fingerprint_for_node(&self.mast_forest, &self.hash_by_node_id)?;
179
180        match self.lookup_node_by_fingerprint(&node_fingerprint) {
181            Some(matching_node_id) => {
182                // If a node with a matching fingerprint exists, then the merging node is a
183                // duplicate and we remap it to the existing node.
184                self.node_id_mappings[forest_idx].insert(merging_id, matching_node_id);
185            },
186            None => {
187                // If no node with a matching fingerprint exists, then the merging node is
188                // unique and we can add it to the merged forest using builders.
189                let new_node_id = self.mast_forest.push_node(remapped_builder)?;
190                self.node_id_mappings[forest_idx].insert(merging_id, new_node_id);
191
192                self.node_id_by_hash.insert(node_fingerprint, new_node_id);
193                let returned_id = self
194                    .hash_by_node_id
195                    .push(node_fingerprint)
196                    .map_err(|_| MastForestError::TooManyNodes)?;
197                debug_assert_eq!(
198                    returned_id, new_node_id,
199                    "hash_by_node_id push() should return the same node IDs as node_id_by_hash"
200                );
201            },
202        }
203
204        Ok(())
205    }
206
207    fn merge_roots(&mut self, forest_idx: usize, other_forest: &MastForest) {
208        for root_id in other_forest.roots.iter() {
209            // Map the previous root to its possibly new id.
210            let new_root = self.node_id_mappings[forest_idx]
211                .get(*root_id)
212                .expect("all node ids should have an entry");
213            // This takes O(n) where n is the number of roots in the merged forest every time to
214            // check if the root already exists. As the number of roots is relatively low generally,
215            // this should be okay.
216            self.mast_forest.mark_root(new_root);
217        }
218    }
219
220    // HELPERS
221    // ================================================================================================
222
223    /// Returns the ID of the node in the merged forest that matches the given
224    /// fingerprint, if any.
225    fn lookup_node_by_fingerprint(&self, fingerprint: &Word) -> Option<MastNodeId> {
226        self.node_id_by_hash.get(fingerprint).copied()
227    }
228
229    /// Builds a new node with remapped children using the provided mappings.
230    fn build_with_remapped_children(
231        &self,
232        merging_id: MastNodeId,
233        src: MastNode,
234        original_forest: &MastForest,
235        nmap: &DenseIdMap<MastNodeId, MastNodeId>,
236    ) -> Result<MastNodeBuilder, MastForestError> {
237        super::build_node_with_remapped_ids(merging_id, src, original_forest, nmap)
238    }
239
240    /// Remaps each source forest's node IDs from merger-local IDs to finalized dense IDs.
241    fn remap_finalized_node_ids(
242        mut node_id_mappings: Vec<DenseIdMap<MastNodeId, MastNodeId>>,
243        final_id_remapping: &DenseIdMap<MastNodeId, MastNodeId>,
244    ) -> Vec<DenseIdMap<MastNodeId, MastNodeId>> {
245        for node_id_mapping in &mut node_id_mappings {
246            for source_index in 0..node_id_mapping.len() {
247                let source_id = MastNodeId::new_unchecked(
248                    source_index.try_into().expect("source node index exceeds u32"),
249                );
250                if let Some(builder_id) = node_id_mapping.get(source_id) {
251                    let finalized_id = final_id_remapping
252                        .get(builder_id)
253                        .expect("every builder node id should map to a finalized node id");
254                    node_id_mapping.insert(source_id, finalized_id);
255                }
256            }
257        }
258
259        node_id_mappings
260    }
261}
262
263// MAST FOREST ROOT MAP
264// ================================================================================================
265
266/// A mapping for the new location of the roots of a [`MastForest`] after a merge.
267///
268/// It maps the roots ([`MastNodeId`]s) of a forest to their new [`MastNodeId`] in the merged
269/// forest. See [`MastForest::merge`] for more details.
270#[derive(Debug, Clone, Default, PartialEq, Eq)]
271pub struct MastForestRootMap {
272    node_maps: Vec<BTreeMap<MastNodeId, MastNodeId>>,
273    root_maps: Vec<BTreeMap<MastNodeId, MastNodeId>>,
274}
275
276impl MastForestRootMap {
277    pub(super) fn from_maps(
278        node_maps: Vec<BTreeMap<MastNodeId, MastNodeId>>,
279        root_maps: Vec<BTreeMap<MastNodeId, MastNodeId>>,
280    ) -> Self {
281        Self { node_maps, root_maps }
282    }
283
284    fn from_node_id_map(
285        id_map: Vec<DenseIdMap<MastNodeId, MastNodeId>>,
286        forests: Vec<&MastForest>,
287    ) -> Self {
288        let mut node_maps = vec![BTreeMap::new(); forests.len()];
289        let mut root_maps = vec![BTreeMap::new(); forests.len()];
290
291        for (forest_idx, forest) in forests.into_iter().enumerate() {
292            for (node_idx, _) in forest.nodes().iter().enumerate() {
293                let node_id = MastNodeId::new_unchecked(
294                    node_idx.try_into().expect("MastForest node index exceeds u32"),
295                );
296                if let Some(new_id) = id_map[forest_idx].get(node_id) {
297                    node_maps[forest_idx].insert(node_id, new_id);
298                }
299            }
300            for root in forest.procedure_roots() {
301                let new_id = id_map[forest_idx]
302                    .get(*root)
303                    .expect("every node id should be mapped to its new id");
304                root_maps[forest_idx].insert(*root, new_id);
305            }
306        }
307
308        Self { node_maps, root_maps }
309    }
310
311    /// Maps any node from the given input forest to its new location in the merged forest.
312    ///
313    /// This includes non-root nodes, which is required when remapping package-owned source/debug
314    /// graphs after [`MastForest::merge`].
315    pub fn map_node(&self, forest_index: usize, node: &MastNodeId) -> Option<MastNodeId> {
316        self.node_maps.get(forest_index).and_then(|map| map.get(node)).copied()
317    }
318
319    /// Maps the given root to its new location in the merged forest, if such a mapping exists.
320    ///
321    /// It is guaranteed that every root of the map's corresponding forest is contained in the map.
322    pub fn map_root(&self, forest_index: usize, root: &MastNodeId) -> Option<MastNodeId> {
323        self.root_maps.get(forest_index).and_then(|map| map.get(root)).copied()
324    }
325}