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
21newtype_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 prop_oneof![Just(0u32), Just(u32::MAX), any::<u32>()]
52 .prop_map(Self::from)
53 .boxed()
54 }
55 }
56}
57
58#[derive(Debug)]
83pub struct SparseMastForest {
84 nodes: BTreeMap<MastNodeId, MastNode>,
86
87 digests: BTreeMap<MastNodeId, Word>,
91
92 roots: Vec<MastNodeId>,
94
95 advice_map: AdviceMap,
97}
98
99impl SparseMastForest {
100 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 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 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 pub fn nodes(&self) -> &BTreeMap<MastNodeId, MastNode> {
203 &self.nodes
204 }
205
206 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 pub fn procedure_roots(&self) -> &[MastNodeId] {
222 &self.roots
223 }
224
225 pub fn advice_map(&self) -> &AdviceMap {
230 &self.advice_map
231 }
232
233 pub(in crate::mast) fn digest_entries(&self) -> &BTreeMap<MastNodeId, Word> {
235 &self.digests
236 }
237
238 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
321fn 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum VisitKind {
419 FullVisit,
422 DigestOnly,
426}
427
428#[derive(Debug)]
439pub struct SparseMastForestBuilder {
440 source: Arc<MastForest>,
442
443 full_visits: BTreeSet<MastNodeId>,
446
447 digest_only_visits: BTreeSet<MastNodeId>,
451}
452
453impl SparseMastForestBuilder {
454 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 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 pub fn source(&self) -> &Arc<MastForest> {
480 &self.source
481 }
482
483 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}