Skip to main content

foundry_evm/executors/fuzz/
frontier.rs

1use crate::inspectors::CmpOperands;
2use alloy_json_abi::Function;
3use alloy_primitives::{
4    Address, I256, U256,
5    map::{Entry, HashMap},
6};
7use evm2::interpreter::op as opcode;
8use foundry_common::fs;
9use foundry_evm_fuzz::{BasicTxDetails, FuzzRunMetadata};
10use serde::{Serialize, Serializer};
11use std::{
12    path::Path,
13    sync::Arc,
14    time::{SystemTime, UNIX_EPOCH},
15};
16
17const FRONTIER_SCHEMA: &str = "foundry:fuzz.branch-frontiers@v1";
18const STATEFUL_FRONTIER_SCHEMA: &str = "foundry:fuzz.branch-frontiers@v2";
19pub(super) const FRONTIER_FILE: &str = "branch-frontiers.json";
20
21#[derive(Debug, Serialize)]
22pub(super) struct FuzzBranchFrontierArtifact {
23    /// Stable artifact schema identifier for downstream symbolic consumers.
24    schema: &'static str,
25    /// Schema version for consumers that prefer numeric dispatch.
26    version: u32,
27    /// Unix timestamp, in seconds, when the artifact was written.
28    generated_at: u64,
29    /// Fuzz test signature that produced the frontier records.
30    test: String,
31    /// Configured maximum number of records retained for this test.
32    limit: usize,
33    /// Captured comparison frontiers.
34    frontiers: Vec<FuzzBranchFrontier>,
35}
36
37impl FuzzBranchFrontierArtifact {
38    pub(super) fn new(
39        func: &Function,
40        limit: usize,
41        mut frontiers: Vec<FuzzBranchFrontier>,
42    ) -> Self {
43        for (id, frontier) in frontiers.iter_mut().enumerate() {
44            frontier.id = id as u64;
45        }
46
47        Self {
48            schema: FRONTIER_SCHEMA,
49            version: 1,
50            generated_at: SystemTime::now()
51                .duration_since(UNIX_EPOCH)
52                .expect("time went backwards")
53                .as_secs(),
54            test: func.signature(),
55            limit,
56            frontiers,
57        }
58    }
59}
60
61#[derive(Debug, Serialize)]
62pub(in crate::executors) struct StatefulFuzzBranchFrontierArtifact {
63    /// Stable artifact schema identifier for downstream symbolic consumers.
64    schema: &'static str,
65    /// Schema version for consumers that prefer numeric dispatch.
66    version: u32,
67    /// Unix timestamp, in seconds, when the artifact was written.
68    generated_at: u64,
69    /// Invariant campaign anchor that produced the frontier records.
70    test: String,
71    /// Configured maximum number of records retained for this campaign.
72    limit: usize,
73    /// Deduplicated concrete transaction sequences referenced by frontier records.
74    #[serde(serialize_with = "serialize_sequences")]
75    sequences: Vec<StatefulFuzzSequence>,
76    /// Captured comparison frontiers.
77    frontiers: Vec<StatefulFuzzBranchFrontier>,
78}
79
80impl StatefulFuzzBranchFrontierArtifact {
81    pub(in crate::executors) fn new(
82        func: &Function,
83        limit: usize,
84        frontiers: Vec<FuzzBranchFrontier>,
85    ) -> Self {
86        let mut sequence_indexes = HashMap::<*const BasicTxDetails, usize>::default();
87        let mut sequences = Vec::<StatefulFuzzSequence>::new();
88        let mut records = Vec::with_capacity(frontiers.len());
89        for (id, frontier) in frontiers.into_iter().enumerate() {
90            let sequence_key = frontier.sequence.as_ptr();
91            let required_len = frontier.call_index + 1;
92            let sequence_index = match sequence_indexes.entry(sequence_key) {
93                Entry::Occupied(entry) => {
94                    let index = *entry.get();
95                    sequences[index].len = sequences[index].len.max(required_len);
96                    index
97                }
98                Entry::Vacant(entry) => {
99                    let index = sequences.len();
100                    entry.insert(index);
101                    sequences.push(StatefulFuzzSequence {
102                        calls: Arc::clone(&frontier.sequence),
103                        len: required_len,
104                    });
105                    index
106                }
107            };
108            records.push(StatefulFuzzBranchFrontier {
109                id: id as u64,
110                call_index: frontier.call_index,
111                sequence_index,
112                site: frontier.site,
113                operands: frontier.operands,
114            });
115        }
116
117        Self {
118            schema: STATEFUL_FRONTIER_SCHEMA,
119            version: 2,
120            generated_at: SystemTime::now()
121                .duration_since(UNIX_EPOCH)
122                .expect("time went backwards")
123                .as_secs(),
124            test: func.signature(),
125            limit,
126            sequences,
127            frontiers: records,
128        }
129    }
130}
131
132#[derive(Debug)]
133struct StatefulFuzzSequence {
134    calls: Arc<[BasicTxDetails]>,
135    len: usize,
136}
137
138/// A concrete sequence and the comparison reached by one of its calls.
139#[derive(Clone, Debug, Serialize)]
140pub struct FuzzBranchFrontier {
141    /// Unique record identifier.
142    id: u64,
143    /// Reproducible fuzz seed, if configured.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    seed: Option<U256>,
146    /// 1-based fuzz run number, if known.
147    #[serde(skip_serializing_if = "Option::is_none")]
148    run: Option<u32>,
149    /// Fuzz worker that produced the record, if known.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    worker: Option<u32>,
152    /// Whether this call also expanded coverage from the worker's current map. Only present when
153    /// edge coverage is collected (corpus, edge-coverage metrics, or sancov); omitted otherwise.
154    #[serde(skip_serializing_if = "Option::is_none")]
155    new_coverage: Option<bool>,
156    /// Index of the call in the recorded sequence. Stateless fuzzing records one call.
157    call_index: usize,
158    /// Concrete call sequence that reached the frontier.
159    #[serde(serialize_with = "serialize_sequence")]
160    sequence: Arc<[BasicTxDetails]>,
161    /// EVM comparison site to target symbolically.
162    site: FuzzBranchFrontierSite,
163    /// Concrete operands observed at the site.
164    operands: FuzzBranchFrontierOperands,
165}
166
167#[derive(Debug, Serialize)]
168struct StatefulFuzzBranchFrontier {
169    id: u64,
170    call_index: usize,
171    sequence_index: usize,
172    site: FuzzBranchFrontierSite,
173    operands: FuzzBranchFrontierOperands,
174}
175
176#[derive(Clone, Copy, Debug, Serialize)]
177struct FuzzBranchFrontierSite {
178    address: Address,
179    pc: usize,
180    opcode: u8,
181    opcode_name: &'static str,
182}
183
184#[derive(Clone, Copy, Debug, Serialize)]
185struct FuzzBranchFrontierOperands {
186    lhs: U256,
187    rhs: U256,
188    /// Result of evaluating the captured comparison with these concrete operands.
189    result: bool,
190    /// Absolute operand delta interpreted according to the comparison opcode's signedness.
191    operand_delta: U256,
192}
193
194#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
195struct FuzzBranchFrontierKey {
196    address: Address,
197    pc: usize,
198    opcode: u8,
199    result: bool,
200}
201
202impl FuzzBranchFrontierKey {
203    const fn new(cmp: &CmpOperands, result: bool) -> Self {
204        Self { address: cmp.address, pc: cmp.pc, opcode: cmp.opcode, result }
205    }
206}
207
208#[derive(Debug, Default)]
209pub(in crate::executors) struct FuzzFrontierRecorder {
210    limit: usize,
211    frontiers: Vec<FuzzBranchFrontier>,
212    indexes: HashMap<FuzzBranchFrontierKey, usize>,
213    prefer_shortest: bool,
214}
215
216impl FuzzFrontierRecorder {
217    pub(in crate::executors) fn new(limit: usize) -> Self {
218        Self { limit, frontiers: Vec::with_capacity(limit.min(32)), ..Default::default() }
219    }
220
221    /// Prefers short live prefixes so a returned seed leaves room for a continuation.
222    pub(in crate::executors) const fn prefer_shortest_prefix(&mut self) {
223        self.prefer_shortest = true;
224    }
225
226    pub(super) fn capture_call(
227        &mut self,
228        run: Option<&FuzzRunMetadata>,
229        sequence: &[BasicTxDetails],
230        call_index: usize,
231        cmp_values: &[CmpOperands],
232        new_coverage: Option<bool>,
233    ) {
234        if self.limit == 0 || cmp_values.is_empty() {
235            return;
236        }
237        debug_assert!(call_index < sequence.len());
238
239        let mut recorded_sequence = None;
240        self.capture_comparisons(
241            run,
242            sequence,
243            call_index,
244            cmp_values,
245            new_coverage,
246            &mut recorded_sequence,
247        );
248    }
249
250    pub(in crate::executors) fn capture_sequence(
251        &mut self,
252        sequence: &[BasicTxDetails],
253        cmp_sequence: &[Vec<CmpOperands>],
254    ) {
255        if self.limit == 0 || cmp_sequence.is_empty() {
256            return;
257        }
258        debug_assert!(sequence.len() >= cmp_sequence.len());
259        let sequence = &sequence[..cmp_sequence.len()];
260
261        let mut recorded_sequence = None;
262        for (call_index, cmp_values) in cmp_sequence.iter().enumerate() {
263            self.capture_comparisons(
264                None,
265                sequence,
266                call_index,
267                cmp_values,
268                None,
269                &mut recorded_sequence,
270            );
271        }
272    }
273
274    fn capture_comparisons(
275        &mut self,
276        run: Option<&FuzzRunMetadata>,
277        sequence: &[BasicTxDetails],
278        call_index: usize,
279        cmp_values: &[CmpOperands],
280        new_coverage: Option<bool>,
281        recorded_sequence: &mut Option<Arc<[BasicTxDetails]>>,
282    ) {
283        if cmp_values.is_empty() {
284            return;
285        }
286
287        let mut new_frontier = |cmp: &CmpOperands, result, operand_delta| {
288            let sequence = recorded_sequence.get_or_insert_with(|| Arc::from(sequence));
289            FuzzBranchFrontier::new(
290                run,
291                Arc::clone(sequence),
292                *cmp,
293                result,
294                operand_delta,
295                new_coverage,
296                call_index,
297            )
298        };
299
300        for cmp in cmp_values {
301            let Some(result) = comparison_result(cmp) else { continue };
302            let key = FuzzBranchFrontierKey::new(cmp, result);
303            let operand_delta = operand_delta(cmp);
304
305            match self.indexes.entry(key) {
306                Entry::Occupied(entry) => {
307                    let index = *entry.get();
308                    let previous = &self.frontiers[index];
309                    let replace = if self.prefer_shortest {
310                        (call_index, operand_delta)
311                            < (previous.call_index, previous.operands.operand_delta)
312                    } else {
313                        (operand_delta, call_index)
314                            < (previous.operands.operand_delta, previous.call_index)
315                    };
316                    if replace {
317                        self.frontiers[index] = new_frontier(cmp, result, operand_delta);
318                    }
319                }
320                Entry::Vacant(entry) => {
321                    if self.frontiers.len() < self.limit {
322                        entry.insert(self.frontiers.len());
323                        let frontier = new_frontier(cmp, result, operand_delta);
324                        self.frontiers.push(frontier);
325                    }
326                }
327            }
328        }
329    }
330
331    pub(in crate::executors) fn into_frontiers(self) -> Vec<FuzzBranchFrontier> {
332        self.frontiers
333    }
334}
335
336impl FuzzBranchFrontier {
337    /// Returns the sequence ending at the comparison's call.
338    pub fn sequence(&self) -> &[BasicTxDetails] {
339        &self.sequence[..=self.call_index]
340    }
341
342    /// Returns the comparison operands and their observed result.
343    pub const fn comparison(&self) -> (CmpOperands, bool) {
344        (
345            CmpOperands {
346                address: self.site.address,
347                pc: self.site.pc,
348                opcode: self.site.opcode,
349                op1: self.operands.lhs,
350                op2: self.operands.rhs,
351            },
352            self.operands.result,
353        )
354    }
355
356    const fn key(&self) -> FuzzBranchFrontierKey {
357        FuzzBranchFrontierKey {
358            address: self.site.address,
359            pc: self.site.pc,
360            opcode: self.site.opcode,
361            result: self.operands.result,
362        }
363    }
364
365    fn new(
366        run: Option<&FuzzRunMetadata>,
367        sequence: Arc<[BasicTxDetails]>,
368        cmp: CmpOperands,
369        result: bool,
370        operand_delta: U256,
371        new_coverage: Option<bool>,
372        call_index: usize,
373    ) -> Self {
374        Self {
375            id: 0,
376            seed: run.and_then(|run| run.seed),
377            run: run.and_then(|run| run.run),
378            worker: run.and_then(|run| run.worker),
379            new_coverage,
380            call_index,
381            sequence,
382            site: FuzzBranchFrontierSite {
383                address: cmp.address,
384                pc: cmp.pc,
385                opcode: cmp.opcode,
386                opcode_name: opcode_name(cmp.opcode),
387            },
388            operands: FuzzBranchFrontierOperands {
389                lhs: cmp.op1,
390                rhs: cmp.op2,
391                result,
392                operand_delta,
393            },
394        }
395    }
396}
397
398/// Merges per-worker frontier records into a single bounded, globally deduplicated set.
399///
400/// Each worker deduplicates its own records by comparison site key while keeping the smallest
401/// `operand_delta`, but workers run independently, so the same site can appear in several workers'
402/// records with different observed deltas. This applies the same key dedup and smallest-delta
403/// policy across all workers so the artifact keeps one globally closest record per site and does
404/// not spend `limit` on duplicates. Iteration continues after `limit` is reached because a later
405/// record may be a smaller-delta duplicate of an already retained key.
406pub(in crate::executors) fn merge_frontiers(
407    limit: usize,
408    frontiers: impl IntoIterator<Item = FuzzBranchFrontier>,
409) -> Vec<FuzzBranchFrontier> {
410    if limit == 0 {
411        return Vec::new();
412    }
413
414    let mut merged = Vec::<FuzzBranchFrontier>::with_capacity(limit.min(32));
415    let mut indexes = HashMap::<FuzzBranchFrontierKey, usize>::default();
416    for frontier in frontiers {
417        match indexes.entry(frontier.key()) {
418            Entry::Occupied(entry) => {
419                let index = *entry.get();
420                let previous = &merged[index];
421                if frontier.operands.operand_delta < previous.operands.operand_delta
422                    || (frontier.operands.operand_delta == previous.operands.operand_delta
423                        && frontier.call_index < previous.call_index)
424                {
425                    merged[index] = frontier;
426                }
427            }
428            Entry::Vacant(entry) => {
429                if merged.len() < limit {
430                    entry.insert(merged.len());
431                    merged.push(frontier);
432                }
433            }
434        }
435    }
436
437    merged
438}
439
440pub(in crate::executors) fn write_frontier_artifact(
441    dir: &Path,
442    artifact: &impl Serialize,
443) -> fs::Result<()> {
444    fs::create_dir_all(dir)?;
445    fs::write_json_file(&dir.join(FRONTIER_FILE), artifact)
446}
447
448fn serialize_sequence<S>(sequence: &Arc<[BasicTxDetails]>, serializer: S) -> Result<S::Ok, S::Error>
449where
450    S: Serializer,
451{
452    Serialize::serialize(sequence.as_ref(), serializer)
453}
454
455fn serialize_sequences<S>(
456    sequences: &[StatefulFuzzSequence],
457    serializer: S,
458) -> Result<S::Ok, S::Error>
459where
460    S: Serializer,
461{
462    serializer.collect_seq(sequences.iter().map(|sequence| &sequence.calls[..sequence.len]))
463}
464
465/// Returns the result of a comparison opcode, or `None` for operands logged from other opcodes,
466/// such as `SUB`, which symbolic branch targets cannot match.
467pub(in crate::executors) fn comparison_result(cmp: &CmpOperands) -> Option<bool> {
468    Some(match cmp.opcode {
469        opcode::EQ => cmp.op1 == cmp.op2,
470        opcode::LT => cmp.op1 < cmp.op2,
471        opcode::GT => cmp.op1 > cmp.op2,
472        opcode::SLT => I256::from_raw(cmp.op1) < I256::from_raw(cmp.op2),
473        opcode::SGT => I256::from_raw(cmp.op1) > I256::from_raw(cmp.op2),
474        opcode::ISZERO => cmp.op1.is_zero(),
475        _ => return None,
476    })
477}
478
479fn operand_delta(cmp: &CmpOperands) -> U256 {
480    match cmp.opcode {
481        opcode::SLT | opcode::SGT => signed_operand_delta(cmp.op1, cmp.op2),
482        _ => unsigned_operand_delta(cmp.op1, cmp.op2),
483    }
484}
485
486fn unsigned_operand_delta(left: U256, right: U256) -> U256 {
487    if left >= right { left - right } else { right - left }
488}
489
490fn signed_operand_delta(left: U256, right: U256) -> U256 {
491    let (left_negative, left_magnitude) = signed_magnitude(left);
492    let (right_negative, right_magnitude) = signed_magnitude(right);
493
494    if left_negative == right_negative {
495        unsigned_operand_delta(left_magnitude, right_magnitude)
496    } else {
497        left_magnitude + right_magnitude
498    }
499}
500
501fn signed_magnitude(value: U256) -> (bool, U256) {
502    let negative = I256::from_raw(value) < I256::ZERO;
503    let magnitude = if negative { U256::ZERO.wrapping_sub(value) } else { value };
504    (negative, magnitude)
505}
506
507const fn opcode_name(op: u8) -> &'static str {
508    match op {
509        opcode::EQ => "EQ",
510        opcode::LT => "LT",
511        opcode::GT => "GT",
512        opcode::SLT => "SLT",
513        opcode::SGT => "SGT",
514        opcode::ISZERO => "ISZERO",
515        _ => "UNKNOWN",
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use alloy_primitives::Bytes;
523    use foundry_evm_fuzz::CallDetails;
524
525    #[test]
526    fn stateless_frontier_preserves_concrete_transaction() {
527        let tx = BasicTxDetails {
528            warp: None,
529            roll: None,
530            sender: Address::with_last_byte(1),
531            call_details: CallDetails {
532                target: Address::with_last_byte(2),
533                calldata: Bytes::from_static(&[1, 2, 3, 4]),
534                value: Some(U256::from(7)),
535            },
536        };
537        let cmp = CmpOperands {
538            op1: U256::ZERO,
539            op2: U256::ONE,
540            pc: 1,
541            address: tx.call_details.target,
542            opcode: opcode::LT,
543        };
544        let mut recorder = FuzzFrontierRecorder::new(1);
545
546        recorder.capture_call(None, std::slice::from_ref(&tx), 0, &[cmp], Some(true));
547
548        let frontier = recorder.into_frontiers().pop().unwrap();
549        assert_eq!(frontier.sequence.len(), 1);
550        assert_eq!(frontier.call_index, 0);
551        let recorded = &frontier.sequence[0];
552        assert_eq!(recorded.sender, tx.sender);
553        assert_eq!(recorded.call_details.target, tx.call_details.target);
554        assert_eq!(recorded.call_details.calldata, tx.call_details.calldata);
555        assert_eq!(recorded.call_details.value, tx.call_details.value);
556    }
557
558    #[test]
559    fn operand_delta_uses_signed_distance_for_signed_comparisons() {
560        let unsigned = CmpOperands {
561            op1: U256::MAX,
562            op2: U256::ONE,
563            pc: 0,
564            address: Address::ZERO,
565            opcode: opcode::LT,
566        };
567        assert_eq!(operand_delta(&unsigned), U256::MAX - U256::ONE);
568
569        let signed = CmpOperands { opcode: opcode::SLT, ..unsigned };
570        assert_eq!(operand_delta(&signed), U256::from(2));
571    }
572
573    #[test]
574    fn signed_operand_delta_handles_full_int256_range() {
575        let min = I256::MIN.into_raw();
576        let max = I256::MAX.into_raw();
577
578        assert_eq!(signed_operand_delta(min, max), U256::MAX);
579    }
580
581    fn frontier(pc: usize, result: bool, operand_delta: u64) -> FuzzBranchFrontier {
582        frontier_at(Address::ZERO, pc, result, operand_delta)
583    }
584
585    fn frontier_at(
586        address: Address,
587        pc: usize,
588        result: bool,
589        operand_delta: u64,
590    ) -> FuzzBranchFrontier {
591        let cmp = CmpOperands { op1: U256::ZERO, op2: U256::ZERO, pc, address, opcode: opcode::LT };
592        FuzzBranchFrontier::new(
593            None,
594            Arc::from(Vec::<BasicTxDetails>::new().into_boxed_slice()),
595            cmp,
596            result,
597            U256::from(operand_delta),
598            None,
599            0,
600        )
601    }
602
603    #[test]
604    fn merge_frontiers_dedupes_across_workers_keeping_smallest_delta() {
605        let merged = merge_frontiers(
606            8,
607            [frontier(1, false, 30), frontier(1, false, 10), frontier(1, false, 20)],
608        );
609
610        assert_eq!(merged.len(), 1);
611        assert_eq!(merged[0].operands.operand_delta, U256::from(10));
612    }
613
614    #[test]
615    fn frontier_keeps_shortest_stateful_sequence_for_equal_delta() {
616        let tx = BasicTxDetails {
617            warp: None,
618            roll: None,
619            sender: Address::with_last_byte(1),
620            call_details: CallDetails {
621                target: Address::with_last_byte(2),
622                calldata: Bytes::from_static(&[1, 2, 3, 4]),
623                value: None,
624            },
625        };
626        let cmp = CmpOperands {
627            op1: U256::ONE,
628            op2: U256::from(2),
629            pc: 1,
630            address: tx.call_details.target,
631            opcode: opcode::LT,
632        };
633        let mut recorder = FuzzFrontierRecorder::new(1);
634
635        recorder.capture_call(None, &[tx.clone(), tx.clone()], 1, &[cmp], None);
636        recorder.capture_call(None, std::slice::from_ref(&tx), 0, &[cmp], None);
637
638        let frontier = recorder.into_frontiers().pop().unwrap();
639        assert_eq!(frontier.sequence.len(), 1);
640        assert_eq!(frontier.call_index, 0);
641    }
642
643    #[test]
644    fn stateful_artifact_stores_shared_sequence_once() {
645        let tx = BasicTxDetails {
646            warp: None,
647            roll: None,
648            sender: Address::with_last_byte(1),
649            call_details: CallDetails {
650                target: Address::with_last_byte(2),
651                calldata: Bytes::from_static(&[1, 2, 3, 4]),
652                value: None,
653            },
654        };
655        let first = CmpOperands {
656            op1: U256::ZERO,
657            op2: U256::ONE,
658            pc: 1,
659            address: tx.call_details.target,
660            opcode: opcode::LT,
661        };
662        let second = CmpOperands { pc: 2, ..first };
663        let mut recorder = FuzzFrontierRecorder::new(2);
664        recorder.capture_sequence(&[tx.clone(), tx], &[vec![first], vec![second]]);
665        let func: Function = serde_json::from_str(
666            r#"{"type":"function","name":"invariant_ok","inputs":[],"outputs":[],"stateMutability":"pure"}"#,
667        )
668        .unwrap();
669
670        let artifact = StatefulFuzzBranchFrontierArtifact::new(&func, 2, recorder.into_frontiers());
671
672        assert_eq!(artifact.sequences.len(), 1);
673        assert_eq!(artifact.sequences[0].len, 2);
674        assert_eq!(artifact.frontiers.len(), 2);
675        assert_eq!(artifact.frontiers[0].sequence_index, 0);
676        assert_eq!(artifact.frontiers[1].sequence_index, 0);
677        assert_eq!(artifact.frontiers[0].call_index, 0);
678        assert_eq!(artifact.frontiers[1].call_index, 1);
679    }
680
681    #[test]
682    fn merge_frontiers_keeps_records_with_distinct_result_keys() {
683        // Same site but different comparison result is a distinct key.
684        let merged = merge_frontiers(8, [frontier(1, false, 5), frontier(1, true, 5)]);
685
686        assert_eq!(merged.len(), 2);
687    }
688
689    #[test]
690    fn merge_frontiers_replaces_retained_key_after_limit_is_full() {
691        // The first two unique keys fill the limit; a later new key is dropped, but a later
692        // smaller-delta duplicate of an already retained key still replaces it.
693        let merged = merge_frontiers(
694            2,
695            [
696                frontier(1, false, 30),
697                frontier(2, false, 30),
698                frontier(3, false, 5),
699                frontier(1, false, 10),
700            ],
701        );
702
703        assert_eq!(merged.len(), 2);
704        let retained = merged.iter().find(|f| f.site.pc == 1).unwrap();
705        assert_eq!(retained.operands.operand_delta, U256::from(10));
706        assert!(merged.iter().all(|f| f.site.pc != 3));
707    }
708
709    #[test]
710    fn merge_frontiers_does_not_spend_limit_on_duplicates() {
711        // A duplicate of a retained key must not count against the limit, so a later distinct key
712        // still fits. This guards against counting processed records instead of unique keys.
713        let merged = merge_frontiers(
714            2,
715            [frontier(1, false, 30), frontier(1, false, 10), frontier(2, false, 5)],
716        );
717
718        assert_eq!(merged.len(), 2);
719        assert_eq!(
720            merged.iter().find(|f| f.site.pc == 1).unwrap().operands.operand_delta,
721            U256::from(10)
722        );
723        assert!(merged.iter().any(|f| f.site.pc == 2));
724    }
725
726    #[test]
727    fn merge_frontiers_distinguishes_by_address() {
728        // Same pc/opcode/result at different addresses are distinct sites.
729        let other = Address::with_last_byte(1);
730        let merged = merge_frontiers(
731            8,
732            [frontier_at(Address::ZERO, 1, false, 5), frontier_at(other, 1, false, 5)],
733        );
734
735        assert_eq!(merged.len(), 2);
736    }
737
738    #[test]
739    fn merge_frontiers_with_zero_limit_is_empty() {
740        assert!(merge_frontiers(0, [frontier(1, false, 1)]).is_empty());
741    }
742
743    #[test]
744    fn sub_comparisons_are_not_frontiers() {
745        let tx = BasicTxDetails {
746            warp: None,
747            roll: None,
748            sender: Address::ZERO,
749            call_details: CallDetails {
750                target: Address::ZERO,
751                calldata: Bytes::from_static(&[1, 2, 3, 4]),
752                value: None,
753            },
754        };
755        let cmp = CmpOperands {
756            op1: U256::ZERO,
757            op2: U256::ONE,
758            pc: 1,
759            address: Address::ZERO,
760            opcode: opcode::SUB,
761        };
762        let mut recorder = FuzzFrontierRecorder::new(1);
763
764        recorder.capture_call(None, std::slice::from_ref(&tx), 0, &[cmp], Some(true));
765
766        assert!(recorder.into_frontiers().is_empty());
767    }
768}