Skip to main content

foundry_evm/executors/invariant/
shrink.rs

1use crate::executors::{
2    EarlyExit, EvmError, Executor, RawCallResult, RawFailure,
3    campaign::{CampaignCallKind, apply_block_delay, execute_invariant_replay_tx},
4    invariant::{
5        IInvariantTest, call_after_invariant_function, call_invariant_function,
6        error::{handler_edge_fingerprint, snapshot_edge_fingerprint},
7        result::did_fail_on_assert,
8    },
9};
10use alloy_json_abi::Function;
11use alloy_primitives::{Address, B256, Bytes, I256, Selector, U256, map::HashSet};
12use alloy_sol_types::SolCall;
13use foundry_common::ContractsByAddress;
14use foundry_config::InvariantConfig;
15use foundry_evm_core::{constants::MAGIC_ASSUME, decode::RevertDecoder, evm::FoundryEvmNetwork};
16use foundry_evm_fuzz::{BaseCounterExample, BasicTxDetails, invariant::InvariantContract};
17use indicatif::ProgressBar;
18use proptest::bits::{BitSetLike, VarBitSet};
19use std::{borrow::Cow, cell::Cell, fmt::Write, hash::Hash, ops::Range, time::Instant};
20
21const LIVE_SHRINK_SEQUENCE_EDGE_CALLS: usize = 16;
22
23/// Shrinker for a call sequence failure.
24/// Iterates sequence call sequence top down and removes calls one by one.
25/// If the failure is still reproducible with removed call then moves to the next one.
26/// If the failure is not reproducible then restore removed call and moves to next one.
27#[derive(Debug)]
28pub struct SequenceShrink {
29    /// Length of call sequence to be shrunk.
30    call_sequence_len: usize,
31    /// Call ids contained in current shrunk sequence.
32    included_calls: VarBitSet,
33}
34
35impl SequenceShrink {
36    pub fn new(call_sequence_len: usize) -> Self {
37        Self { call_sequence_len, included_calls: VarBitSet::saturated(call_sequence_len) }
38    }
39
40    /// Return candidate shrink sequence to be tested, by removing ids from original sequence.
41    pub fn current(&self) -> impl Iterator<Item = usize> + '_ {
42        (0..self.call_sequence_len).filter(|&call_id| self.included_calls.test(call_id))
43    }
44
45    pub fn contains(&self, call_idx: usize) -> bool {
46        self.included_calls.test(call_idx)
47    }
48
49    pub fn included_count(&self) -> usize {
50        self.included_calls.count()
51    }
52
53    pub fn apply<T: Clone>(&self, calls: &[T]) -> Vec<T> {
54        self.current().map(|idx| calls[idx].clone()).collect()
55    }
56
57    pub fn apply_with_accumulated_delay<T, D, A>(
58        &self,
59        calls: &[T],
60        mut delay: D,
61        mut apply_delay: A,
62    ) -> Vec<T>
63    where
64        T: Clone,
65        D: FnMut(&T) -> (Option<U256>, Option<U256>),
66        A: FnMut(T, U256, U256) -> T,
67    {
68        let mut result = Vec::new();
69        let mut accumulated_warp = U256::ZERO;
70        let mut accumulated_roll = U256::ZERO;
71
72        for (idx, call) in calls.iter().enumerate() {
73            let (warp, roll) = delay(call);
74            accumulated_warp += warp.unwrap_or(U256::ZERO);
75            accumulated_roll += roll.unwrap_or(U256::ZERO);
76
77            if self.contains(idx) {
78                result.push(apply_delay(call.clone(), accumulated_warp, accumulated_roll));
79                accumulated_warp = U256::ZERO;
80                accumulated_roll = U256::ZERO;
81            }
82        }
83
84        result
85    }
86
87    fn remove(&mut self, call_idx: usize) {
88        self.included_calls.clear(call_idx);
89    }
90
91    fn restore(&mut self, call_idx: usize) {
92        self.included_calls.set(call_idx);
93    }
94
95    /// Advance to the next call index, wrapping around to 0 at the end.
96    const fn next_index(&self, call_idx: usize) -> usize {
97        if call_idx + 1 == self.call_sequence_len { 0 } else { call_idx + 1 }
98    }
99}
100
101/// How `run_shrink_loop` handles a predicate error.
102#[derive(Clone, Copy)]
103enum ShrinkErrorPolicy {
104    /// "Bug still present" — keep the call removed (legacy `shrink_sequence` behavior).
105    KeepRemoved,
106    /// "Bug gone" — restore the call. Used by handler shrink so a replay error never
107    /// produces a sequence that no longer reproduces the anchor.
108    RestoreRemoved,
109}
110
111/// Attempt counters collected while trying shrink candidates.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub struct ShrinkRunStats {
114    pub attempts: usize,
115    pub accepted: usize,
116}
117
118/// Shared shrink attempt driver.
119///
120/// Candidate generation stays with each shrinker; this type only centralizes limit enforcement
121/// and the "accept when the candidate still reproduces the bug" accounting.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub struct ShrinkRun {
124    max_attempts: usize,
125    /// When to stop trying candidates, for a run with a time budget.
126    deadline: Option<Instant>,
127    stats: ShrinkRunStats,
128}
129
130impl ShrinkRun {
131    pub const fn new(max_attempts: usize) -> Self {
132        Self { max_attempts, deadline: None, stats: ShrinkRunStats { attempts: 0, accepted: 0 } }
133    }
134
135    /// Also stops trying candidates at `deadline`, if set.
136    pub const fn with_deadline(mut self, deadline: Option<Instant>) -> Self {
137        self.deadline = deadline;
138        self
139    }
140
141    pub fn can_try(&self) -> bool {
142        self.stats.attempts < self.max_attempts && !deadline_passed(self.deadline)
143    }
144
145    pub const fn deadline(&self) -> Option<Instant> {
146        self.deadline
147    }
148
149    pub const fn remaining_attempts(&self) -> usize {
150        self.max_attempts - self.stats.attempts
151    }
152
153    pub const fn finish(self) -> ShrinkRunStats {
154        self.stats
155    }
156
157    pub fn try_candidate(&mut self, still_fails: impl FnOnce() -> bool) -> bool {
158        self.try_candidate_decision(|| Some(still_fails())).unwrap_or(false)
159    }
160
161    fn try_candidate_decision(&mut self, decide: impl FnOnce() -> Option<bool>) -> Option<bool> {
162        if !self.can_try() {
163            return None;
164        }
165
166        let accepted = decide()?;
167        self.stats.attempts += 1;
168        if accepted {
169            self.stats.accepted += 1;
170        }
171        Some(accepted)
172    }
173}
174
175/// Returns whether `deadline` is set and has passed.
176pub fn deadline_passed(deadline: Option<Instant>) -> bool {
177    deadline.is_some_and(|deadline| Instant::now() >= deadline)
178}
179
180/// Returns `executor`, or with a `deadline` a copy whose executions stop at it, for replaying
181/// shrink candidates that the deadline must not wait for.
182fn candidate_executor<'a, FEN: FoundryEvmNetwork>(
183    executor: &'a Executor<FEN>,
184    early_exit: &EarlyExit,
185    deadline: Option<Instant>,
186) -> Cow<'a, Executor<FEN>> {
187    let Some(deadline) = deadline else { return Cow::Borrowed(executor) };
188    let mut executor = executor.clone();
189    executor.inspector_mut().set_execution_deadline(early_exit.clone(), deadline);
190    Cow::Owned(executor)
191}
192
193/// Shared key set for shrinkers that need to skip duplicate concrete replays.
194#[derive(Clone, Debug)]
195pub struct ShrinkCandidateKeys<K> {
196    seen: HashSet<K>,
197}
198
199impl<K: Eq + Hash> ShrinkCandidateKeys<K> {
200    pub fn new(initial: K) -> Self {
201        Self { seen: HashSet::<_>::from_iter([initial]) }
202    }
203
204    pub fn insert(&mut self, key: K) -> bool {
205        self.seen.insert(key)
206    }
207}
208
209/// Options controlling how `check_sequence` evaluates a candidate call sequence.
210pub struct CheckSequenceOptions<'a> {
211    pub accumulate_warp_roll: bool,
212    pub fail_on_revert: bool,
213    pub expect_assertion_failure: bool,
214    pub call_after_invariant: bool,
215    pub rd: Option<&'a RevertDecoder>,
216}
217
218/// Concrete failure site observed while replaying a sequence through [`check_sequence`].
219#[derive(Clone, Copy, Debug, PartialEq, Eq)]
220pub enum CheckSequenceFailureSite {
221    SequenceCall { target: Address, selector: Selector, fingerprint: B256 },
222    Invariant { target: Address, selector: Selector, fingerprint: B256 },
223    AfterInvariant { target: Address, selector: Selector, fingerprint: B256 },
224}
225
226/// Outcome from replaying an invariant call sequence through [`check_sequence`].
227#[derive(Clone, Debug)]
228pub struct CheckSequenceOutcome {
229    pub success: bool,
230    pub replayed_entirely: bool,
231    pub reason: Option<String>,
232    pub calls_count: usize,
233    pub reverts: usize,
234    pub failure_site: Option<CheckSequenceFailureSite>,
235    /// Whether replay stopped on an assertion in a sequence call rather than a plain revert or
236    /// terminal invariant check.
237    pub sequence_assertion_failure: bool,
238    /// Innermost reverter for a sequence assertion, used to recognize legacy handler identities.
239    pub sequence_reverter: Option<Address>,
240    /// Observable outcome of the failing call, see [`RawCallResult::raw_failure`].
241    pub raw_failure: Option<RawFailure>,
242    /// Value-independent identity of the failing call, see [`RawCallResult::failure_identity`].
243    pub failure_identity: Option<B256>,
244}
245
246pub struct ShrunkSequence {
247    pub calls: Vec<BasicTxDetails>,
248    pub result: Option<CheckSequenceOutcome>,
249}
250
251/// Result of a strict handler-bug replay: anchor asserts, no earlier call asserts, and the
252/// recomputed edge fingerprint identifies which path the assertion took.
253#[derive(Clone, Debug, Default)]
254pub struct HandlerReplayOutcome {
255    pub anchor_asserted: bool,
256    /// Top-level fuzzed handler target used as the canonical failure identity.
257    pub handler_target: Address,
258    /// Innermost reverting frame, retained to recognize legacy persisted identities.
259    pub reverter: Address,
260    pub selector: Selector,
261    pub revert_reason: Option<String>,
262    /// Normalized via `handler_edge_fingerprint` so callers can compare directly.
263    pub anchor_fingerprint: B256,
264}
265
266/// Resets the progress bar before each shrink. `position = Some((i, N))` renders
267/// `[i/N] Shrink: <label>` for multi-invariant campaigns.
268pub fn reset_shrink_progress(
269    config: &InvariantConfig,
270    progress: Option<&ProgressBar>,
271    label: &str,
272    position: Option<(usize, usize)>,
273) -> String {
274    let message = match position {
275        Some((current, total)) if total > 1 => {
276            format!(" [{current}/{total}] Shrink: {label}")
277        }
278        _ => format!(" Shrink: {label}"),
279    };
280    if let Some(progress) = progress {
281        progress.set_length(config.shrink_run_limit as u64);
282        progress.reset();
283        progress.set_message(message.clone());
284    }
285    message
286}
287
288/// Live shrink progress display. The progress bar itself is owned by forge's test runner; this
289/// type only formats the transient message shown while invariant shrinking is active.
290pub(crate) struct ShrinkProgress<'a> {
291    progress: Option<&'a ProgressBar>,
292    message: String,
293    identified_contracts: Option<&'a ContractsByAddress>,
294    show_solidity: bool,
295}
296
297impl<'a> ShrinkProgress<'a> {
298    pub(crate) fn new(
299        config: &InvariantConfig,
300        progress: Option<&'a ProgressBar>,
301        label: &str,
302        position: Option<(usize, usize)>,
303        identified_contracts: Option<&'a ContractsByAddress>,
304        show_solidity: bool,
305    ) -> Self {
306        let message = reset_shrink_progress(config, progress, label, position);
307        Self { progress, message, identified_contracts, show_solidity }
308    }
309
310    fn inc(&self) {
311        if let Some(progress) = self.progress {
312            progress.inc(1);
313        }
314    }
315
316    fn update(
317        &self,
318        calls: &[BasicTxDetails],
319        shrinker: &SequenceShrink,
320        accumulate_warp_roll: bool,
321    ) {
322        let Some(progress) = self.progress else {
323            return;
324        };
325        if progress.is_hidden() {
326            return;
327        }
328
329        let sequence = build_shrunk_sequence(calls, shrinker, accumulate_warp_roll);
330        let message = format_shrink_progress_message(
331            &self.message,
332            &sequence,
333            self.identified_contracts,
334            self.show_solidity,
335        );
336        progress.set_message(message);
337    }
338}
339
340fn format_shrink_progress_message(
341    phase: &str,
342    sequence: &[BasicTxDetails],
343    identified_contracts: Option<&ContractsByAddress>,
344    show_solidity: bool,
345) -> String {
346    let mut message = String::with_capacity(phase.len() + sequence.len().min(32) * 96);
347    message.push_str(phase);
348    write!(message, "\n\t[Sequence] (shrunk: {})", sequence.len()).unwrap();
349
350    if sequence.len() <= LIVE_SHRINK_SEQUENCE_EDGE_CALLS * 2 {
351        for tx in sequence {
352            push_shrink_progress_call(&mut message, tx, identified_contracts, show_solidity);
353        }
354        return message;
355    }
356
357    for tx in &sequence[..LIVE_SHRINK_SEQUENCE_EDGE_CALLS] {
358        push_shrink_progress_call(&mut message, tx, identified_contracts, show_solidity);
359    }
360    writeln!(
361        message,
362        "\n\t\t... {} call(s) omitted ...",
363        sequence.len() - LIVE_SHRINK_SEQUENCE_EDGE_CALLS * 2
364    )
365    .unwrap();
366    for tx in &sequence[sequence.len() - LIVE_SHRINK_SEQUENCE_EDGE_CALLS..] {
367        push_shrink_progress_call(&mut message, tx, identified_contracts, show_solidity);
368    }
369    message
370}
371
372fn push_shrink_progress_call(
373    message: &mut String,
374    tx: &BasicTxDetails,
375    identified_contracts: Option<&ContractsByAddress>,
376    show_solidity: bool,
377) {
378    let empty_contracts;
379    let identified_contracts = if let Some(identified_contracts) = identified_contracts {
380        identified_contracts
381    } else {
382        empty_contracts = ContractsByAddress::default();
383        &empty_contracts
384    };
385
386    let call =
387        BaseCounterExample::from_invariant_call(tx, identified_contracts, None, show_solidity)
388            .to_string();
389    for line in call.lines() {
390        message.push('\n');
391        message.push_str(line);
392    }
393}
394
395/// Applies accumulated warp/roll to a call, returning a modified copy.
396fn apply_warp_roll(mut result: BasicTxDetails, warp: U256, roll: U256) -> BasicTxDetails {
397    if warp > U256::ZERO {
398        result.warp = Some(warp);
399    }
400    if roll > U256::ZERO {
401        result.roll = Some(roll);
402    }
403    result
404}
405
406/// Builds the final shrunk sequence from the shrinker state.
407///
408/// When `accumulate_warp_roll` is enabled, warp/roll from removed calls is folded into the next
409/// kept call so the final sequence remains reproducible.
410fn build_shrunk_sequence(
411    calls: &[BasicTxDetails],
412    shrinker: &SequenceShrink,
413    accumulate_warp_roll: bool,
414) -> Vec<BasicTxDetails> {
415    if !accumulate_warp_roll {
416        return shrinker.apply(calls);
417    }
418
419    shrinker.apply_with_accumulated_delay(calls, |call| (call.warp, call.roll), apply_warp_roll)
420}
421
422/// Shared sequence shrinker. Tries to drop each call; `predicate` decides whether the candidate
423/// should be accepted, rejected, or skipped without spending a replay attempt. It also receives
424/// the first index the candidate removes: every kept call before it is unchanged.
425///
426/// With `drop_blocks`, first tries to drop blocks of kept calls, halving the block size down to two
427/// calls, then drops single calls. Stops when every kept call was tried once since the last
428/// accepted removal: the sequence is then a fixpoint and further passes would replay the same
429/// rejected candidates.
430pub fn shrink_sequence_by_removing<P, S, A>(
431    calls_len: usize,
432    run: &mut ShrinkRun,
433    drop_blocks: bool,
434    mut should_stop: S,
435    mut on_attempt: A,
436    mut predicate: P,
437) -> SequenceShrink
438where
439    P: FnMut(&SequenceShrink, usize) -> Option<bool>,
440    S: FnMut() -> bool,
441    A: FnMut(),
442{
443    let mut shrinker = SequenceShrink::new(calls_len);
444
445    let mut chunk = if drop_blocks { calls_len / 2 } else { 0 };
446    while chunk >= 2 && run.can_try() && !should_stop() {
447        let kept = shrinker.current().collect::<Vec<_>>();
448        let mut accepted_block = false;
449        for block in kept.chunks(chunk) {
450            if !run.can_try() || should_stop() {
451                break;
452            }
453            for &call_idx in block {
454                shrinker.remove(call_idx);
455            }
456            let decision = run.try_candidate_decision(|| predicate(&shrinker, block[0]));
457            if decision.is_some() {
458                on_attempt();
459            }
460            if decision == Some(true) {
461                accepted_block = true;
462            } else {
463                for &call_idx in block {
464                    shrinker.restore(call_idx);
465                }
466            }
467        }
468        // The first levels cost a few attempts. Once a level has eight or more blocks and none
469        // can go, the needed calls are dense and single removals are the cheaper path.
470        if !accepted_block && kept.len() / chunk >= 8 {
471            break;
472        }
473        chunk /= 2;
474    }
475
476    let mut call_idx = 0;
477    // Kept calls tried without an accepted removal since the last change.
478    let mut unchanged_candidates = 0usize;
479
480    while run.can_try() {
481        if should_stop() {
482            break;
483        }
484        let included_count = shrinker.included_count();
485        if included_count == 0 || unchanged_candidates >= included_count {
486            break;
487        }
488
489        // Already-removed indices have nothing to drop.
490        if !shrinker.contains(call_idx) {
491            call_idx = shrinker.next_index(call_idx);
492            continue;
493        }
494
495        shrinker.remove(call_idx);
496
497        match run.try_candidate_decision(|| predicate(&shrinker, call_idx)) {
498            Some(true) => {
499                on_attempt();
500                unchanged_candidates = 0;
501                if shrinker.included_count() == 1 {
502                    break;
503                }
504            }
505            Some(false) => {
506                on_attempt();
507                shrinker.restore(call_idx);
508                unchanged_candidates += 1;
509            }
510            None => {
511                shrinker.restore(call_idx);
512                unchanged_candidates += 1;
513            }
514        }
515
516        call_idx = shrinker.next_index(call_idx);
517    }
518
519    shrinker
520}
521
522/// Shared shrink loop driver. Tries to drop each call; `predicate` returns whether the
523/// candidate still triggers the bug.
524#[expect(clippy::too_many_arguments)]
525fn run_shrink_loop<P>(
526    config: &InvariantConfig,
527    calls: &[BasicTxDetails],
528    progress: &ShrinkProgress<'_>,
529    accumulate_warp_roll: bool,
530    early_exit: &EarlyExit,
531    deadline: Option<Instant>,
532    error_policy: ShrinkErrorPolicy,
533    mut predicate: P,
534) -> SequenceShrink
535where
536    P: FnMut(&SequenceShrink, usize) -> eyre::Result<bool>,
537{
538    let mut run = ShrinkRun::new(config.shrink_run_limit as usize).with_deadline(deadline);
539    let initial = SequenceShrink::new(calls.len());
540    progress.update(calls, &initial, accumulate_warp_roll);
541
542    let shrinker = shrink_sequence_by_removing(
543        calls.len(),
544        &mut run,
545        true,
546        || early_exit.should_stop(),
547        || progress.inc(),
548        |shrinker, first_removed| {
549            progress.update(calls, shrinker, accumulate_warp_roll);
550            let decision = predicate(shrinker, first_removed);
551            // The deadline can cancel a candidate's execution, so a decision made after it is not
552            // trusted: the candidate is discarded and the last confirmed sequence stays.
553            if deadline_passed(deadline) {
554                return None;
555            }
556            match decision {
557                Ok(bug_still_present) => Some(bug_still_present),
558                Err(_) => Some(matches!(error_policy, ShrinkErrorPolicy::KeepRemoved)),
559            }
560        },
561    );
562    progress.update(calls, &shrinker, accumulate_warp_roll);
563    let stats = run.finish();
564    trace!(
565        target: "forge::test",
566        attempts = stats.attempts,
567        accepted = stats.accepted,
568        "shrink finished"
569    );
570    shrinker
571}
572
573#[expect(clippy::too_many_arguments)]
574pub(crate) fn shrink_sequence<FEN: FoundryEvmNetwork>(
575    config: &InvariantConfig,
576    invariant_contract: &InvariantContract<'_>,
577    target_invariant: &Function,
578    calls: &[BasicTxDetails],
579    expect_assertion_failure: bool,
580    executor: &Executor<FEN>,
581    rd: Option<&RevertDecoder>,
582    progress: &ShrinkProgress<'_>,
583    early_exit: &EarlyExit,
584    deadline: Option<Instant>,
585) -> eyre::Result<ShrunkSequence> {
586    trace!(target: "forge::test", "Shrinking sequence of {} calls.", calls.len());
587
588    let target_address = invariant_contract.address;
589    let calldata: Bytes = target_invariant.selector().into();
590    // With the budget spent, keep the recorded sequence without starting another replay.
591    let unshrunk = || ShrunkSequence { calls: calls.to_vec(), result: None };
592    if config.shrink_run_limit == 0 || deadline_passed(deadline) {
593        return Ok(unshrunk());
594    }
595    let candidates = candidate_executor(executor, early_exit, deadline);
596    // Special case test: the invariant is *unsatisfiable* - it took 0 calls to
597    // break the invariant -- consider emitting a warning.
598    let (_, success) = call_invariant_function(&candidates, target_address, calldata.clone())?;
599    // A deadline that passed during the check may have cancelled it.
600    if deadline_passed(deadline) {
601        return Ok(unshrunk());
602    }
603    if !success {
604        return Ok(ShrunkSequence { calls: vec![], result: None });
605    }
606
607    let accumulate_warp_roll = config.has_delay();
608    let mut sequence = Vec::with_capacity(calls.len());
609    let mut last_result = None;
610    let mut last_result_matches_shrinker = true;
611    let mut replay = PrefixReplay::new(
612        &candidates,
613        calls,
614        CheckSequencePolicy {
615            options: CheckSequenceOptions {
616                accumulate_warp_roll,
617                fail_on_revert: config.fail_on_revert,
618                expect_assertion_failure,
619                call_after_invariant: invariant_contract.call_after_invariant,
620                rd,
621            },
622            test_address: target_address,
623            calldata: calldata.clone(),
624            identify: None,
625            between_calls: Vec::new(),
626            checks_between_calls: false,
627        },
628    );
629    let shrinker = run_shrink_loop(
630        config,
631        calls,
632        progress,
633        accumulate_warp_roll,
634        early_exit,
635        deadline,
636        // Preserve legacy invariant-shrink behavior: errors during candidate evaluation
637        // do not roll back the removal.
638        ShrinkErrorPolicy::KeepRemoved,
639        |shrinker, first_removed| {
640            sequence.clear();
641            sequence.extend(shrinker.current());
642            let result = match replay.check(&sequence, first_removed) {
643                Ok(result) => result,
644                Err(err) => {
645                    last_result_matches_shrinker = false;
646                    return Err(err);
647                }
648            };
649            // Bug still present iff the invariant predicate did not pass. A result after the
650            // deadline may come from a cancelled replay, and `run_shrink_loop` discards it.
651            let bug_still_present = !result.success;
652            if bug_still_present && !deadline_passed(deadline) {
653                last_result = Some(result);
654                last_result_matches_shrinker = true;
655            }
656            Ok(bug_still_present)
657        },
658    );
659
660    let shrunk = build_shrunk_sequence(calls, &shrinker, accumulate_warp_roll);
661    let result = if last_result_matches_shrinker {
662        last_result
663    } else if deadline_passed(deadline) {
664        None
665    } else {
666        match check_sequence(
667            executor.clone(),
668            &shrunk,
669            &(0..shrunk.len()).collect::<Vec<_>>(),
670            target_address,
671            calldata,
672            CheckSequenceOptions {
673                accumulate_warp_roll: false,
674                fail_on_revert: config.fail_on_revert,
675                expect_assertion_failure,
676                call_after_invariant: invariant_contract.call_after_invariant,
677                rd,
678            },
679        ) {
680            Ok(result) => Some(result),
681            Err(err) => {
682                trace!(target: "forge::test", %err, "failed to recompute shrunk replay metrics");
683                None
684            }
685        }
686    };
687
688    Ok(ShrunkSequence { calls: shrunk, result })
689}
690
691/// Checks if the given call sequence breaks the invariant.
692///
693/// Used in shrinking phase for checking candidate sequences and in replay failures phase to test
694/// persisted failures.
695/// Returns the result of invariant check (and afterInvariant call if needed) and if sequence was
696/// entirely applied, plus the concrete failure site when replay fails.
697///
698/// When `options.accumulate_warp_roll` is enabled, warp/roll from removed calls is folded into the
699/// next kept call so the candidate sequence stays representable as a concrete counterexample.
700pub fn check_sequence<FEN: FoundryEvmNetwork>(
701    executor: Executor<FEN>,
702    calls: &[BasicTxDetails],
703    sequence: &[usize],
704    test_address: Address,
705    calldata: Bytes,
706    options: CheckSequenceOptions<'_>,
707) -> eyre::Result<CheckSequenceOutcome> {
708    let policy = CheckSequencePolicy {
709        options,
710        test_address,
711        calldata,
712        identify: None,
713        between_calls: Vec::new(),
714        checks_between_calls: false,
715    };
716    PrefixReplay::new(&executor, calls, policy).check(sequence, 0)
717}
718
719/// Replays the candidates of a failing sequence's minimizer, reusing the state after the calls a
720/// candidate shares with the previous one.
721///
722/// Every call skips cheatcodes with effects outside the EVM, as when recording failure identities,
723/// but recording them steps every instruction, so only the call that failed at the expected site
724/// records its identity and provenance: the last call for a sequence call, or the final checks.
725///
726/// The campaign also checks the invariants between calls, and those checks can have such effects
727/// as well. With `between_calls`, the replay runs these checks between calls, unless
728/// `checks_between_calls` is false, and before the final checks, unless the failure is at a
729/// sequence call, so that skipping their effects leaves the failure unidentified too.
730pub struct CandidateReplay<'a, FEN: FoundryEvmNetwork> {
731    replay: PrefixReplay<'a, FEN, CheckSequencePolicy<'a>>,
732    /// Whether the latest replay skipped a cheatcode with effects outside the EVM.
733    pub skipped_host_effects: bool,
734}
735
736impl<'a, FEN: FoundryEvmNetwork> CandidateReplay<'a, FEN> {
737    pub fn new(
738        executor: &'a mut Executor<FEN>,
739        test_address: Address,
740        calldata: Bytes,
741        options: CheckSequenceOptions<'a>,
742        site: CheckSequenceFailureSite,
743        between_calls: Vec<Bytes>,
744        checks_between_calls: bool,
745    ) -> Self {
746        executor.inspector_mut().collect_failure_identity(true);
747        executor.inspector_mut().pause_failure_identity(true);
748        let policy = CheckSequencePolicy {
749            options,
750            test_address,
751            calldata,
752            identify: Some(site),
753            between_calls,
754            checks_between_calls,
755        };
756        Self { replay: PrefixReplay::new(executor, &[], policy), skipped_host_effects: false }
757    }
758
759    /// Replays `calls` from the first call that differs from the previous candidate.
760    pub fn check(&mut self, calls: Vec<BasicTxDetails>) -> eyre::Result<CheckSequenceOutcome> {
761        let replay = &mut self.replay;
762        // The last call records its identity, so it never comes from the cached state.
763        let first_changed = replay
764            .calls
765            .iter()
766            .zip(&calls)
767            .take_while(|(a, b)| a == b)
768            .count()
769            .min(calls.len().saturating_sub(1));
770        replay.calls = Cow::Owned(calls);
771        let outcome = replay.check(&(0..replay.calls.len()).collect::<Vec<_>>(), first_changed);
772        // Copies of the executor share whether a replay skipped such an effect, which leaves later
773        // calls unidentified, so after one did, the next candidate starts over without it.
774        self.skipped_host_effects = replay.initial.inspector().take_skipped_host_effects();
775        if self.skipped_host_effects {
776            replay.reset();
777        }
778        outcome
779    }
780}
781
782/// Records the failure identity, paused by [`CandidateReplay::new`], and the provenance of the
783/// calls `executor` runs next.
784fn identify_failure<FEN: FoundryEvmNetwork>(executor: &mut Executor<FEN>) {
785    executor.inspector_mut().pause_failure_identity(false);
786    executor.inspector_mut().collect_failure_provenance(true);
787}
788
789/// Counters carried across the calls of one sequence replay.
790#[derive(Clone, Copy, Default)]
791struct ReplayCounters {
792    /// Warp and roll of removed calls, waiting for the next kept call.
793    warp: U256,
794    roll: U256,
795    calls_executed: usize,
796    reverts: usize,
797}
798
799/// What a sequence replay does with each kept call and with the final state.
800trait ReplayPolicy<FEN: FoundryEvmNetwork> {
801    type Outcome: Clone;
802
803    /// Whether warp/roll of removed calls is folded into the next kept call.
804    fn accumulate_warp_roll(&self) -> bool;
805
806    /// Prepares `executor` to run the kept call `idx` of `sequence`. An error stops the replay.
807    fn before_call(
808        &self,
809        _executor: &mut Executor<FEN>,
810        _sequence: &[usize],
811        _idx: usize,
812    ) -> eyre::Result<()> {
813        Ok(())
814    }
815
816    /// Classifies one replayed call of `sequence`. Returns the outcome when the call stops the
817    /// replay. The decision for a call that is not the last kept call must not depend on the
818    /// calls after it, because [`PrefixReplay`] reuses it for later candidates.
819    fn on_call(
820        &self,
821        calls: &[BasicTxDetails],
822        sequence: &[usize],
823        idx: usize,
824        call_result: RawCallResult<FEN>,
825        counters: &mut ReplayCounters,
826    ) -> Option<Self::Outcome>;
827
828    /// Builds the outcome once every kept call ran.
829    fn finish(
830        &self,
831        executor: &mut Executor<FEN>,
832        counters: &ReplayCounters,
833    ) -> eyre::Result<Self::Outcome>;
834}
835
836/// Replays the kept calls of `calls[range]` on `executor`. `kept` holds the kept indices inside
837/// the range in order. Returns the outcome of the call that stopped the replay, if any.
838fn replay_kept_calls<FEN: FoundryEvmNetwork, P: ReplayPolicy<FEN>>(
839    executor: &mut Executor<FEN>,
840    calls: &[BasicTxDetails],
841    sequence: &[usize],
842    kept: &[usize],
843    range: Range<usize>,
844    counters: &mut ReplayCounters,
845    policy: &P,
846) -> eyre::Result<Option<P::Outcome>> {
847    // Fast path: no warp/roll accumulation → iterate only kept indices (O(k)) and pass
848    // `&calls[idx]` directly to skip the per-call `BasicTxDetails` clone.
849    if !policy.accumulate_warp_roll() {
850        for &idx in kept {
851            policy.before_call(executor, sequence, idx)?;
852            let (_, call_result) = execute_invariant_replay_tx(executor, &calls[idx])?;
853            if let Some(outcome) = policy.on_call(calls, sequence, idx, call_result, counters) {
854                return Ok(Some(outcome));
855            }
856        }
857        return Ok(None);
858    }
859
860    // Accumulating path: must scan the full range so warp/roll from skipped txs lands on the
861    // next kept tx as a concrete delta.
862    let mut kept = kept.iter().peekable();
863    for idx in range {
864        let tx = &calls[idx];
865        counters.warp += tx.warp.unwrap_or(U256::ZERO);
866        counters.roll += tx.roll.unwrap_or(U256::ZERO);
867        if kept.peek() != Some(&&idx) {
868            continue;
869        }
870        kept.next();
871
872        let executed = apply_warp_roll(tx.clone(), counters.warp, counters.roll);
873        policy.before_call(executor, sequence, idx)?;
874        let (_, call_result) = execute_invariant_replay_tx(executor, &executed)?;
875        counters.warp = U256::ZERO;
876        counters.roll = U256::ZERO;
877        if let Some(outcome) = policy.on_call(calls, sequence, idx, call_result, counters) {
878            return Ok(Some(outcome));
879        }
880    }
881    Ok(None)
882}
883
884/// Replays the calls that a run of shrink candidates share.
885///
886/// Candidates arrive in index order and keep every call before their first removed index, so the
887/// state after those calls is the same for all of them. The cache executes the shared calls once,
888/// and a candidate replays only the calls from its first removed index on. A candidate that removes
889/// a call before the cached position starts again from the initial executor.
890struct PrefixReplay<'a, FEN: FoundryEvmNetwork, P: ReplayPolicy<FEN>> {
891    initial: &'a Executor<FEN>,
892    calls: Cow<'a, [BasicTxDetails]>,
893    policy: P,
894    executor: Executor<FEN>,
895    /// Calls before this index are replayed on `executor`.
896    position: usize,
897    counters: ReplayCounters,
898    /// Outcome of a replayed call that stopped the sequence; later calls never run.
899    stopped: Option<P::Outcome>,
900}
901
902impl<'a, FEN: FoundryEvmNetwork, P: ReplayPolicy<FEN>> PrefixReplay<'a, FEN, P> {
903    fn new(initial: &'a Executor<FEN>, calls: &'a [BasicTxDetails], policy: P) -> Self {
904        Self {
905            initial,
906            calls: Cow::Borrowed(calls),
907            policy,
908            executor: initial.clone(),
909            position: 0,
910            counters: ReplayCounters::default(),
911            stopped: None,
912        }
913    }
914
915    fn reset(&mut self) {
916        self.executor = self.initial.clone();
917        self.position = 0;
918        self.counters = ReplayCounters::default();
919        self.stopped = None;
920    }
921
922    /// Checks `sequence`, whose kept calls before `first_removed` match the previous candidate.
923    fn check(&mut self, sequence: &[usize], first_removed: usize) -> eyre::Result<P::Outcome> {
924        if first_removed < self.position {
925            self.reset();
926        }
927        // The last kept call can get a candidate-specific decision, so it is never shared.
928        let shared_end = sequence.last().map_or(0, |&last| first_removed.min(last));
929        if self.stopped.is_none() && self.position < shared_end {
930            let start = sequence.partition_point(|&idx| idx < self.position);
931            let end = sequence.partition_point(|&idx| idx < shared_end);
932            let advanced = replay_kept_calls(
933                &mut self.executor,
934                &self.calls,
935                sequence,
936                &sequence[start..end],
937                self.position..shared_end,
938                &mut self.counters,
939                &self.policy,
940            );
941            match advanced {
942                Ok(stopped) => {
943                    self.stopped = stopped;
944                    self.position = shared_end;
945                }
946                Err(err) => {
947                    // The cached state is partly advanced; the next candidate starts over.
948                    self.reset();
949                    return Err(err);
950                }
951            }
952        }
953        if let Some(outcome) = &self.stopped {
954            return Ok(outcome.clone());
955        }
956
957        let mut executor = self.executor.clone();
958        let mut counters = self.counters;
959        let rest = &sequence[sequence.partition_point(|&idx| idx < self.position)..];
960        if let Some(outcome) = replay_kept_calls(
961            &mut executor,
962            &self.calls,
963            sequence,
964            rest,
965            self.position..self.calls.len(),
966            &mut counters,
967            &self.policy,
968        )? {
969            return Ok(outcome);
970        }
971        self.policy.finish(&mut executor, &counters)
972    }
973}
974
975/// Replay policy of [`check_sequence`]: stops on a sequence call that fails, then checks the
976/// invariant.
977struct CheckSequencePolicy<'a> {
978    options: CheckSequenceOptions<'a>,
979    test_address: Address,
980    calldata: Bytes,
981    /// Site whose failing call records its failure identity and provenance, see
982    /// [`CandidateReplay`].
983    identify: Option<CheckSequenceFailureSite>,
984    /// Calldata of the invariant checks run between calls and before the final checks, see
985    /// [`CandidateReplay`].
986    between_calls: Vec<Bytes>,
987    /// Whether `between_calls` run between calls as well as before the final checks, as in a
988    /// campaign whose `check_interval` is not 0.
989    checks_between_calls: bool,
990}
991
992impl CheckSequencePolicy<'_> {
993    /// Runs the checks of `between_calls` on discarded copies of `executor`, except the checked
994    /// invariant itself before the final checks, which run it.
995    fn check_between_calls<FEN: FoundryEvmNetwork>(
996        &self,
997        executor: &Executor<FEN>,
998        before_final: bool,
999    ) -> eyre::Result<()> {
1000        for calldata in &self.between_calls {
1001            if before_final && *calldata == self.calldata {
1002                continue;
1003            }
1004            let (result, _) =
1005                call_invariant_function(executor, self.test_address, calldata.clone())?;
1006            // A cancelled check may not have reached its effects outside the EVM.
1007            if result.execution_cancelled {
1008                eyre::bail!("invariant check cancelled");
1009            }
1010        }
1011        Ok(())
1012    }
1013}
1014
1015impl<FEN: FoundryEvmNetwork> ReplayPolicy<FEN> for CheckSequencePolicy<'_> {
1016    type Outcome = CheckSequenceOutcome;
1017
1018    fn accumulate_warp_roll(&self) -> bool {
1019        self.options.accumulate_warp_roll
1020    }
1021
1022    fn before_call(
1023        &self,
1024        executor: &mut Executor<FEN>,
1025        sequence: &[usize],
1026        idx: usize,
1027    ) -> eyre::Result<()> {
1028        // The checks before the first call see the same state for every candidate, which the
1029        // campaign checked as well.
1030        if self.checks_between_calls && sequence.first() != Some(&idx) {
1031            self.check_between_calls(executor, false)?;
1032        }
1033        if matches!(self.identify, Some(CheckSequenceFailureSite::SequenceCall { .. }))
1034            && sequence.last() == Some(&idx)
1035        {
1036            identify_failure(executor);
1037        }
1038        Ok(())
1039    }
1040
1041    fn on_call(
1042        &self,
1043        calls: &[BasicTxDetails],
1044        _sequence: &[usize],
1045        idx: usize,
1046        call_result: RawCallResult<FEN>,
1047        counters: &mut ReplayCounters,
1048    ) -> Option<CheckSequenceOutcome> {
1049        let options = &self.options;
1050        counters.calls_executed += 1;
1051        // Ignore calls reverted with `MAGIC_ASSUME`. This is needed to handle failed
1052        // scenarios that are replayed with a modified version of test driver (that use
1053        // new `vm.assume` cheatcodes).
1054        if call_result.result.as_ref() == MAGIC_ASSUME {
1055            return None;
1056        }
1057        if call_result.reverted {
1058            counters.reverts += 1;
1059        }
1060        if did_fail_on_assert(&call_result, &call_result.state_changeset) {
1061            let call = &calls[idx];
1062            let target = call.call_details.target;
1063            let selector = selector_from_calldata(&call.call_details.calldata);
1064            let fingerprint =
1065                handler_edge_fingerprint(snapshot_edge_fingerprint(&call_result), target, selector);
1066            let sequence_reverter = call_result.reverter.or(Some(target));
1067            let site = CheckSequenceFailureSite::SequenceCall { target, selector, fingerprint };
1068            let (raw_failure, failure_identity) =
1069                (call_result.raw_failure(), call_result.failure_identity);
1070            return Some(CheckSequenceOutcome {
1071                success: false,
1072                replayed_entirely: false,
1073                reason: assertion_failure_reason(call_result, options.rd),
1074                calls_count: counters.calls_executed,
1075                reverts: counters.reverts,
1076                failure_site: Some(site),
1077                sequence_assertion_failure: true,
1078                sequence_reverter,
1079                raw_failure,
1080                failure_identity,
1081            });
1082        }
1083        if call_result.reverted && options.fail_on_revert {
1084            if options.expect_assertion_failure {
1085                return Some(CheckSequenceOutcome {
1086                    success: true,
1087                    replayed_entirely: false,
1088                    reason: None,
1089                    calls_count: counters.calls_executed,
1090                    reverts: counters.reverts,
1091                    failure_site: None,
1092                    sequence_assertion_failure: false,
1093                    sequence_reverter: None,
1094                    raw_failure: None,
1095                    failure_identity: None,
1096                });
1097            }
1098            let site = sequence_call_failure_site(&calls[idx], &call_result);
1099            let (raw_failure, failure_identity) =
1100                (call_result.raw_failure(), call_result.failure_identity);
1101            return Some(CheckSequenceOutcome {
1102                success: false,
1103                replayed_entirely: false,
1104                reason: call_failure_reason(call_result, options.rd),
1105                calls_count: counters.calls_executed,
1106                reverts: counters.reverts,
1107                failure_site: Some(site),
1108                sequence_assertion_failure: false,
1109                sequence_reverter: None,
1110                raw_failure,
1111                failure_identity,
1112            });
1113        }
1114        None
1115    }
1116
1117    fn finish(
1118        &self,
1119        executor: &mut Executor<FEN>,
1120        counters: &ReplayCounters,
1121    ) -> eyre::Result<CheckSequenceOutcome> {
1122        match self.identify {
1123            // The checks after the failing call only skip effects outside the EVM. A replay that
1124            // reaches them did not fail at that call, so it is rejected without the checks between
1125            // calls.
1126            Some(CheckSequenceFailureSite::SequenceCall { .. }) => {
1127                executor.inspector_mut().pause_failure_identity(true);
1128                executor.inspector_mut().collect_failure_provenance(false);
1129            }
1130            Some(_) => {
1131                self.check_between_calls(executor, true)?;
1132                identify_failure(executor);
1133            }
1134            None => {}
1135        }
1136        // Unlike optimization mode we intentionally do not apply trailing warp/roll before the
1137        // invariant call: those delays would not be representable in the final shrunk sequence.
1138        finish_sequence_check(
1139            executor,
1140            self.test_address,
1141            self.calldata.clone(),
1142            &self.options,
1143            counters,
1144        )
1145    }
1146}
1147
1148fn finish_sequence_check<FEN: FoundryEvmNetwork>(
1149    executor: &Executor<FEN>,
1150    test_address: Address,
1151    calldata: Bytes,
1152    options: &CheckSequenceOptions<'_>,
1153    counters: &ReplayCounters,
1154) -> eyre::Result<CheckSequenceOutcome> {
1155    let outcome =
1156        |success, reason, failure_site, raw_failure, failure_identity| CheckSequenceOutcome {
1157            success,
1158            replayed_entirely: true,
1159            reason,
1160            calls_count: counters.calls_executed,
1161            reverts: counters.reverts,
1162            failure_site,
1163            sequence_assertion_failure: false,
1164            sequence_reverter: None,
1165            raw_failure,
1166            failure_identity,
1167        };
1168    let handle_terminal_failure =
1169        |call_result: RawCallResult<FEN>, site_kind: TerminalFailureSite| {
1170            let should_ignore_failure = options.expect_assertion_failure
1171                && !executor.has_global_failure(&call_result.state_changeset)
1172                && !did_fail_on_assert(&call_result, &call_result.state_changeset);
1173
1174            if should_ignore_failure {
1175                return outcome(true, None, None, None, None);
1176            }
1177
1178            let site = terminal_failure_site(site_kind, test_address, &calldata, &call_result);
1179            let (raw_failure, failure_identity) =
1180                (call_result.raw_failure(), call_result.failure_identity);
1181            // Terminal calls follow the live rule: a revert after a caught assertion wins.
1182            let reason = call_failure_reason(call_result, options.rd).or_else(|| {
1183                options.expect_assertion_failure.then(|| "assertion failed".to_string())
1184            });
1185
1186            outcome(false, reason, Some(site), raw_failure, failure_identity)
1187        };
1188
1189    let (invariant_result, mut success) =
1190        call_invariant_function(executor, test_address, calldata.clone())?;
1191    if !success {
1192        return Ok(handle_terminal_failure(invariant_result, TerminalFailureSite::Invariant));
1193    }
1194
1195    // Check after invariant result if invariant is success and `afterInvariant` function is
1196    // declared.
1197    if success && options.call_after_invariant {
1198        let (after_invariant_result, after_invariant_success) =
1199            call_after_invariant_function(executor, test_address)?;
1200        success = after_invariant_success;
1201        if !success {
1202            return Ok(handle_terminal_failure(
1203                after_invariant_result,
1204                TerminalFailureSite::AfterInvariant,
1205            ));
1206        }
1207    }
1208
1209    Ok(outcome(success, None, None, None, None))
1210}
1211
1212#[derive(Clone, Copy)]
1213pub(super) enum TerminalFailureSite {
1214    Invariant,
1215    AfterInvariant,
1216}
1217
1218pub(super) fn sequence_call_failure_site<FEN: FoundryEvmNetwork>(
1219    call: &BasicTxDetails,
1220    call_result: &RawCallResult<FEN>,
1221) -> CheckSequenceFailureSite {
1222    let target = call_result.reverter.unwrap_or(call.call_details.target);
1223    let selector = selector_from_calldata(&call.call_details.calldata);
1224    let fingerprint =
1225        handler_edge_fingerprint(snapshot_edge_fingerprint(call_result), target, selector);
1226    CheckSequenceFailureSite::SequenceCall { target, selector, fingerprint }
1227}
1228
1229pub(super) fn terminal_failure_site<FEN: FoundryEvmNetwork>(
1230    kind: TerminalFailureSite,
1231    target: Address,
1232    calldata: &Bytes,
1233    call_result: &RawCallResult<FEN>,
1234) -> CheckSequenceFailureSite {
1235    let target = call_result.reverter.unwrap_or(target);
1236    let selector = match kind {
1237        TerminalFailureSite::Invariant => selector_from_calldata(calldata),
1238        TerminalFailureSite::AfterInvariant => {
1239            Selector::from(IInvariantTest::afterInvariantCall::SELECTOR)
1240        }
1241    };
1242    let fingerprint =
1243        handler_edge_fingerprint(snapshot_edge_fingerprint(call_result), target, selector);
1244    match kind {
1245        TerminalFailureSite::Invariant => {
1246            CheckSequenceFailureSite::Invariant { target, selector, fingerprint }
1247        }
1248        TerminalFailureSite::AfterInvariant => {
1249            CheckSequenceFailureSite::AfterInvariant { target, selector, fingerprint }
1250        }
1251    }
1252}
1253
1254fn selector_from_calldata(calldata: &Bytes) -> Selector {
1255    calldata.get(..4).map(Selector::from_slice).unwrap_or_default()
1256}
1257
1258fn call_failure_reason<FEN: FoundryEvmNetwork>(
1259    mut call_result: RawCallResult<FEN>,
1260    rd: Option<&RevertDecoder>,
1261) -> Option<String> {
1262    // A caught `vm.assert*` failure only explains a call that did not revert.
1263    let failed_assertion = call_result.failed_assertion.take().filter(|_| !call_result.reverted);
1264    match call_result.into_evm_error(rd) {
1265        EvmError::Execution(err) => Some(failed_assertion.unwrap_or(err.reason)),
1266        _ => None,
1267    }
1268}
1269
1270fn assertion_failure_reason<FEN: FoundryEvmNetwork>(
1271    mut call_result: RawCallResult<FEN>,
1272    rd: Option<&RevertDecoder>,
1273) -> Option<String> {
1274    if let Some(message) = call_result.failed_assertion.take() {
1275        return Some(message);
1276    }
1277    call_failure_reason(call_result, rd).or_else(|| Some("assertion failed".to_string()))
1278}
1279
1280/// Shrinks an optimization witness while preserving the best value seen during replay.
1281/// Warp and roll of removed calls move to the next kept call.
1282/// Returns the shrunk sequence and its value, which can exceed `target_value`.
1283#[expect(clippy::too_many_arguments)]
1284pub(crate) fn shrink_sequence_value<FEN: FoundryEvmNetwork>(
1285    config: &InvariantConfig,
1286    invariant_contract: &InvariantContract<'_>,
1287    target_invariant: &Function,
1288    calls: &[BasicTxDetails],
1289    executor: &Executor<FEN>,
1290    target_value: I256,
1291    targets: &[Address],
1292    progress: &ShrinkProgress<'_>,
1293    early_exit: &EarlyExit,
1294    deadline: Option<Instant>,
1295) -> eyre::Result<(Vec<BasicTxDetails>, I256)> {
1296    trace!(target: "forge::test", "Shrinking optimization sequence of {} calls for target value {}.", calls.len(), target_value);
1297
1298    let target_address = invariant_contract.address;
1299    let calldata: Bytes = target_invariant.selector().into();
1300
1301    // With the budget spent, keep the recorded witness and score without another replay.
1302    if deadline_passed(deadline) {
1303        return Ok((calls.to_vec(), target_value));
1304    }
1305    let candidates = candidate_executor(executor, early_exit, deadline);
1306
1307    // Candidates replay only up to their last kept call: the returned witness drops the delays of
1308    // removed trailing calls, so its value must not count them.
1309    // Campaigns score only after a call, so an empty witness must match the target exactly.
1310    let empty_value = check_sequence_value(
1311        candidates.clone().into_owned(),
1312        &[],
1313        &[],
1314        target_address,
1315        calldata.clone(),
1316        config.fail_on_revert,
1317        targets,
1318    );
1319    // A deadline that passed during the check may have cancelled it.
1320    if deadline_passed(deadline) {
1321        return Ok((calls.to_vec(), target_value));
1322    }
1323    if empty_value? == Some(target_value) {
1324        return Ok((vec![], target_value));
1325    }
1326
1327    let replay_failed = Cell::new(false);
1328    let mut replay_error = None;
1329    let mut best = target_value;
1330    let mut run = ShrinkRun::new(config.shrink_run_limit as usize).with_deadline(deadline);
1331    let initial = SequenceShrink::new(calls.len());
1332    progress.update(calls, &initial, true);
1333    let mut sequence = Vec::with_capacity(calls.len());
1334
1335    let shrinker = shrink_sequence_by_removing(
1336        calls.len(),
1337        &mut run,
1338        // Dropping a block whose calls cancel out keeps the score but can discard a call that
1339        // raises it once a single removal drops the call that lowered it.
1340        false,
1341        || early_exit.should_stop() || replay_failed.get(),
1342        || progress.inc(),
1343        |shrinker, _| {
1344            progress.update(calls, shrinker, true);
1345            sequence.clear();
1346            sequence.extend(shrinker.current());
1347            if sequence.is_empty() {
1348                return Some(false);
1349            }
1350            let value = check_sequence_value(
1351                candidates.clone().into_owned(),
1352                &calls[..=sequence[sequence.len() - 1]],
1353                &sequence,
1354                target_address,
1355                calldata.clone(),
1356                config.fail_on_revert,
1357                targets,
1358            );
1359            // A replay after the deadline may have been cancelled, so it is discarded.
1360            if deadline_passed(deadline) {
1361                return None;
1362            }
1363            match value {
1364                Ok(Some(value)) if value >= best => {
1365                    best = value;
1366                    Some(true)
1367                }
1368                Ok(_) => Some(false),
1369                Err(err) => {
1370                    replay_error = Some(err);
1371                    replay_failed.set(true);
1372                    None
1373                }
1374            }
1375        },
1376    );
1377    progress.update(calls, &shrinker, true);
1378    if let Some(err) = replay_error {
1379        return Err(err);
1380    }
1381
1382    Ok((build_shrunk_sequence(calls, &shrinker, true), best))
1383}
1384
1385/// Replays a handler-bug sequence and returns whether the anchor still asserts on the same
1386/// path. Rejects sequences with a pre-anchor assertion (would be a different bug).
1387pub fn replay_handler_failure_sequence<FEN: FoundryEvmNetwork>(
1388    executor: Executor<FEN>,
1389    calls: &[BasicTxDetails],
1390    sequence: &[usize],
1391    accumulate_warp_roll: bool,
1392    rd: Option<&RevertDecoder>,
1393) -> eyre::Result<HandlerReplayOutcome> {
1394    let policy = HandlerReplayPolicy { accumulate_warp_roll, rd };
1395    PrefixReplay::new(&executor, calls, policy).check(sequence, 0)
1396}
1397
1398/// Replay policy of [`replay_handler_failure_sequence`]: stops on the anchor, the last kept call,
1399/// or on an earlier assertion.
1400struct HandlerReplayPolicy<'a> {
1401    accumulate_warp_roll: bool,
1402    rd: Option<&'a RevertDecoder>,
1403}
1404
1405impl<FEN: FoundryEvmNetwork> ReplayPolicy<FEN> for HandlerReplayPolicy<'_> {
1406    type Outcome = HandlerReplayOutcome;
1407
1408    fn accumulate_warp_roll(&self) -> bool {
1409        self.accumulate_warp_roll
1410    }
1411
1412    fn on_call(
1413        &self,
1414        calls: &[BasicTxDetails],
1415        sequence: &[usize],
1416        idx: usize,
1417        call_result: RawCallResult<FEN>,
1418        _counters: &mut ReplayCounters,
1419    ) -> Option<HandlerReplayOutcome> {
1420        // Rejected calls cannot reproduce a handler bug, even if an assertion failed
1421        // before the assumption. Match the live campaign and ordinary sequence replay.
1422        if call_result.result.as_ref() == MAGIC_ASSUME {
1423            return None;
1424        }
1425        let asserted = did_fail_on_assert(&call_result, &call_result.state_changeset);
1426        if sequence.last() == Some(&idx) {
1427            let snapshot = snapshot_edge_fingerprint(&call_result);
1428            let anchor = &calls[idx];
1429            // Handler failures are identified by the top-level fuzzed call. The innermost
1430            // reverter can instead be a nested callee or the cheatcode address.
1431            let handler_target = anchor.call_details.target;
1432            let reverter = call_result.reverter.unwrap_or(handler_target);
1433            let selector = selector_from_calldata(&anchor.call_details.calldata);
1434            let fingerprint = handler_edge_fingerprint(snapshot, handler_target, selector);
1435            let reason =
1436                if asserted { assertion_failure_reason(call_result, self.rd) } else { None };
1437            return Some(HandlerReplayOutcome {
1438                anchor_asserted: asserted,
1439                handler_target,
1440                reverter,
1441                selector,
1442                revert_reason: reason,
1443                anchor_fingerprint: fingerprint,
1444            });
1445        }
1446        // Pre-anchor assertion = different bug; reject.
1447        asserted.then(HandlerReplayOutcome::default)
1448    }
1449
1450    fn finish(
1451        &self,
1452        _executor: &mut Executor<FEN>,
1453        _counters: &ReplayCounters,
1454    ) -> eyre::Result<HandlerReplayOutcome> {
1455        Ok(HandlerReplayOutcome::default())
1456    }
1457}
1458
1459/// Shrinks a handler-bug sequence to the shortest prefix that still asserts on the anchor
1460/// AND keeps the same edge fingerprint (so we don't change bug identity).
1461pub(crate) fn shrink_handler_sequence<FEN: FoundryEvmNetwork>(
1462    config: &InvariantConfig,
1463    calls: &[BasicTxDetails],
1464    expected_fingerprint: B256,
1465    executor: &Executor<FEN>,
1466    progress: &ShrinkProgress<'_>,
1467    early_exit: &EarlyExit,
1468    deadline: Option<Instant>,
1469) -> eyre::Result<Vec<BasicTxDetails>> {
1470    if calls.is_empty() {
1471        return Ok(vec![]);
1472    }
1473    trace!(target: "forge::test", "Shrinking handler sequence of {} calls.", calls.len());
1474    let accumulate_warp_roll = config.has_delay();
1475    let mut sequence = Vec::with_capacity(calls.len());
1476    let candidates = candidate_executor(executor, early_exit, deadline);
1477    let mut replay = PrefixReplay::new(
1478        &candidates,
1479        calls,
1480        HandlerReplayPolicy { accumulate_warp_roll, rd: None },
1481    );
1482    let shrinker = run_shrink_loop(
1483        config,
1484        calls,
1485        progress,
1486        accumulate_warp_roll,
1487        early_exit,
1488        deadline,
1489        ShrinkErrorPolicy::RestoreRemoved,
1490        |shrinker, first_removed| {
1491            sequence.clear();
1492            sequence.extend(shrinker.current());
1493            let outcome = replay.check(&sequence, first_removed)?;
1494            Ok(outcome.anchor_asserted && outcome.anchor_fingerprint == expected_fingerprint)
1495        },
1496    );
1497
1498    if shrinker.included_count() == calls.len() {
1499        return Ok(calls.to_vec());
1500    }
1501    let shrunk = build_shrunk_sequence(calls, &shrinker, accumulate_warp_roll);
1502    // Every removal the shrinker kept was confirmed before the deadline, so once it passed the
1503    // shrunk sequence is kept without starting the verifying replay, which would not be cancelled
1504    // before its first poll.
1505    if deadline_passed(deadline) {
1506        return Ok(shrunk);
1507    }
1508
1509    // Verify shrunk repro; fall back to original on any failure, unless the deadline cancelled the
1510    // verification.
1511    sequence.clear();
1512    sequence.extend(shrinker.current());
1513    let verified = handler_sequence_still_triggers_bug(
1514        candidates.as_ref().clone(),
1515        calls,
1516        &sequence,
1517        accumulate_warp_roll,
1518        expected_fingerprint,
1519    )
1520    .unwrap_or(false);
1521    if verified || deadline_passed(deadline) { Ok(shrunk) } else { Ok(calls.to_vec()) }
1522}
1523
1524/// Shrink predicate: anchor asserts on the same path as the originally recorded bug.
1525fn handler_sequence_still_triggers_bug<FEN: FoundryEvmNetwork>(
1526    executor: Executor<FEN>,
1527    calls: &[BasicTxDetails],
1528    sequence: &[usize],
1529    accumulate_warp_roll: bool,
1530    expected_fingerprint: B256,
1531) -> eyre::Result<bool> {
1532    let outcome =
1533        replay_handler_failure_sequence(executor, calls, sequence, accumulate_warp_roll, None)?;
1534    Ok(outcome.anchor_asserted && outcome.anchor_fingerprint == expected_fingerprint)
1535}
1536
1537/// Executes a call sequence and returns the optimization value (int256) from the invariant
1538/// function. Used during shrinking for optimization mode.
1539///
1540/// Returns `None` if the invariant call fails or doesn't return a valid int256, or if the campaign
1541/// would not have scored the sequence or would have failed the test: a kept call is rejected by
1542/// `vm.assume`, fails an assertion, or fails its handler gate with `fail_on_revert`, or the last
1543/// kept call fails its handler gate.
1544/// Unlike `check_sequence`, this applies warp/roll from ALL calls (including removed ones).
1545///
1546/// `targets` are the campaign's fuzz targets, whose `failed()` the handler gate checks under legacy
1547/// assertions.
1548pub fn check_sequence_value<FEN: FoundryEvmNetwork>(
1549    mut executor: Executor<FEN>,
1550    calls: &[BasicTxDetails],
1551    sequence: &[usize],
1552    test_address: Address,
1553    calldata: Bytes,
1554    fail_on_revert: bool,
1555    targets: &[Address],
1556) -> eyre::Result<Option<I256>> {
1557    let mut accumulated_warp = U256::ZERO;
1558    let mut accumulated_roll = U256::ZERO;
1559    let mut seq_iter = sequence.iter().peekable();
1560    let mut last_call_scored = true;
1561    // Contracts created during a run also become targets; include the ones the sequence calls.
1562    let mut gate_targets = Vec::new();
1563    if executor.legacy_assertions() {
1564        gate_targets.extend_from_slice(targets);
1565        for tx in calls {
1566            if !gate_targets.contains(&tx.call_details.target) {
1567                gate_targets.push(tx.call_details.target);
1568            }
1569        }
1570    }
1571
1572    for (idx, tx) in calls.iter().enumerate() {
1573        accumulated_warp += tx.warp.unwrap_or(U256::ZERO);
1574        accumulated_roll += tx.roll.unwrap_or(U256::ZERO);
1575
1576        if seq_iter.peek() == Some(&&idx) {
1577            seq_iter.next();
1578
1579            let tx_with_accumulated =
1580                apply_warp_roll(tx.clone(), accumulated_warp, accumulated_roll);
1581            let (kind, call_result) =
1582                execute_invariant_replay_tx(&mut executor, &tx_with_accumulated)?;
1583            // Campaigns sample the score only after a call that passes the handler gate.
1584            last_call_scored =
1585                handlers_succeeded(&executor, test_address, &gate_targets, &call_result);
1586            // Campaigns drop rejected calls. A failed gate stops them under `fail_on_revert`, and
1587            // an assertion failure, even a caught one that passes the gate, is a handler bug that
1588            // fails the test in any configuration.
1589            if kind == CampaignCallKind::AssumptionRejected
1590                || did_fail_on_assert(&call_result, &call_result.state_changeset)
1591                || (!last_call_scored && fail_on_revert)
1592            {
1593                return Ok(None);
1594            }
1595
1596            accumulated_warp = U256::ZERO;
1597            accumulated_roll = U256::ZERO;
1598        }
1599    }
1600    if !last_call_scored {
1601        return Ok(None);
1602    }
1603
1604    // Apply any remaining accumulated warp/roll before calling invariant.
1605    apply_block_delay(&mut executor, accumulated_warp, accumulated_roll);
1606
1607    let (inv_result, success) = call_invariant_function(&executor, test_address, calldata)?;
1608
1609    if success
1610        && inv_result.result.len() >= 32
1611        && let Some(value) = I256::try_from_be_slice(&inv_result.result[..32])
1612    {
1613        return Ok(Some(value));
1614    }
1615
1616    Ok(None)
1617}
1618
1619/// Mirrors the campaign's handler gate, which checks `failed()` on every target, and not the test
1620/// contract, under legacy assertions.
1621fn handlers_succeeded<FEN: FoundryEvmNetwork>(
1622    executor: &Executor<FEN>,
1623    test_address: Address,
1624    targets: &[Address],
1625    call_result: &RawCallResult<FEN>,
1626) -> bool {
1627    if call_result.reverted {
1628        return false;
1629    }
1630    let changeset = &call_result.state_changeset;
1631    if !executor.legacy_assertions() {
1632        return executor.is_success_handler_gate(test_address, false, Cow::Borrowed(changeset));
1633    }
1634    targets
1635        .iter()
1636        .all(|&address| executor.is_success_handler_gate(address, false, Cow::Borrowed(changeset)))
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641    use super::*;
1642    use crate::executors::ExecutorBuilder;
1643    use alloy_primitives::hex;
1644    use alloy_sol_types::{Revert, SolError};
1645    use evm2::bytecode::Bytecode;
1646    use foundry_cheatcodes::{CheatsConfig, Vm};
1647    use foundry_evm_core::{constants::CHEATCODE_ADDRESS, evm::EthEvmNetwork};
1648    use foundry_evm_fuzz::CallDetails;
1649    use std::sync::Arc;
1650
1651    fn tx(warp: Option<u64>, roll: Option<u64>) -> BasicTxDetails {
1652        BasicTxDetails {
1653            warp: warp.map(U256::from),
1654            roll: roll.map(U256::from),
1655            sender: Address::ZERO,
1656            call_details: CallDetails {
1657                target: Address::ZERO,
1658                calldata: Bytes::new(),
1659                value: None,
1660            },
1661        }
1662    }
1663
1664    fn tx_with_calldata(byte: u8) -> BasicTxDetails {
1665        BasicTxDetails {
1666            warp: None,
1667            roll: None,
1668            sender: Address::ZERO,
1669            call_details: CallDetails {
1670                target: Address::ZERO,
1671                calldata: Bytes::from(vec![byte]),
1672                value: None,
1673            },
1674        }
1675    }
1676
1677    #[test]
1678    fn build_shrunk_sequence_accumulates_removed_delay_into_next_kept_call() {
1679        let calls = vec![tx(Some(3), Some(5)), tx(Some(7), Some(11)), tx(Some(13), Some(17))];
1680        let mut shrinker = SequenceShrink::new(calls.len());
1681        shrinker.remove(0);
1682
1683        let shrunk = build_shrunk_sequence(&calls, &shrinker, true);
1684
1685        assert_eq!(shrunk.len(), 2);
1686        assert_eq!(shrunk[0].warp, Some(U256::from(10)));
1687        assert_eq!(shrunk[0].roll, Some(U256::from(16)));
1688        assert_eq!(shrunk[1].warp, Some(U256::from(13)));
1689        assert_eq!(shrunk[1].roll, Some(U256::from(17)));
1690    }
1691
1692    #[test]
1693    fn build_shrunk_sequence_does_not_move_trailing_delay_backward() {
1694        let calls = vec![tx(Some(3), Some(5)), tx(Some(7), Some(11))];
1695        let mut shrinker = SequenceShrink::new(calls.len());
1696        shrinker.remove(1);
1697
1698        let shrunk = build_shrunk_sequence(&calls, &shrinker, true);
1699
1700        assert_eq!(shrunk.len(), 1);
1701        assert_eq!(shrunk[0].warp, Some(U256::from(3)));
1702        assert_eq!(shrunk[0].roll, Some(U256::from(5)));
1703    }
1704
1705    #[test]
1706    fn check_sequence_value_applies_trailing_delay_before_invariant() {
1707        let mut executor = crate::executors::test_executor(
1708            ExecutorBuilder::<EthEvmNetwork>::default()
1709                .inspectors(|stack| stack.cheatcodes(Arc::new(CheatsConfig::default())))
1710                .gas_limit(1 << 24),
1711            Default::default(),
1712        );
1713        // Returns `(block.number << 128) + block.timestamp`.
1714        let test_address = Address::repeat_byte(0x11);
1715        let code = hex!("4360801b420160005260206000f3");
1716        executor.set_code(test_address, Bytecode::new_raw(Bytes::from(code))).unwrap();
1717        let block_value =
1718            |timestamp: U256, number: U256| I256::from_raw((number << 128) + timestamp);
1719        let calls = [tx(Some(3), Some(5)), tx(Some(7), Some(11))];
1720        let block = executor.evm_env().block;
1721
1722        // Removed calls still contribute their delays to the invariant check, whether the
1723        // cheatcode block mirrors the environment, is unset, or overrides it.
1724        let delayed =
1725            Some(block_value(block.timestamp + U256::from(10), block.number + U256::from(16)));
1726        let mut cheatcode_block = block;
1727        cheatcode_block.timestamp = U256::from(1000);
1728        cheatcode_block.number = U256::from(2000);
1729        let cases = [
1730            (&[0][..], None, delayed),
1731            (&[], None, delayed),
1732            (&[], Some(None), delayed),
1733            (
1734                &[],
1735                Some(Some(cheatcode_block)),
1736                Some(block_value(U256::from(1010), U256::from(2016))),
1737            ),
1738        ];
1739        for (sequence, cheatcode_block, expected) in cases {
1740            let mut executor = executor.clone();
1741            if let Some(block) = cheatcode_block {
1742                executor.inspector_mut().cheatcodes.as_mut().unwrap().block = block;
1743            }
1744            let value = check_sequence_value(
1745                executor,
1746                &calls,
1747                sequence,
1748                test_address,
1749                Bytes::new(),
1750                false,
1751                &[],
1752            )
1753            .unwrap();
1754            assert_eq!(value, expected);
1755        }
1756    }
1757
1758    #[test]
1759    fn shrink_run_counts_attempts_and_accepts() {
1760        let mut run = ShrinkRun::new(2);
1761
1762        assert_eq!(run.remaining_attempts(), 2);
1763        assert!(!run.try_candidate(|| false));
1764        assert!(run.try_candidate(|| true));
1765
1766        let mut called_after_limit = false;
1767        assert!(!run.try_candidate(|| {
1768            called_after_limit = true;
1769            true
1770        }));
1771
1772        assert!(!called_after_limit);
1773        let stats = run.finish();
1774        assert_eq!(stats.attempts, 2);
1775        assert_eq!(stats.accepted, 1);
1776    }
1777
1778    #[test]
1779    fn shrink_candidate_keys_skip_duplicates() {
1780        let mut candidates = ShrinkCandidateKeys::new("initial");
1781
1782        assert!(!candidates.insert("initial"));
1783        assert!(candidates.insert("first"));
1784        assert!(!candidates.insert("first"));
1785        assert!(candidates.insert("second"));
1786    }
1787
1788    #[test]
1789    fn shrink_loop_keep_removed_treats_candidate_error_as_still_failing() {
1790        let config = InvariantConfig { shrink_run_limit: 1, ..Default::default() };
1791        let early_exit = EarlyExit::new(false);
1792        let calls = vec![tx(None, None), tx(None, None)];
1793        let progress = ShrinkProgress::new(&config, None, "test", None, None, false);
1794
1795        let shrinker = run_shrink_loop(
1796            &config,
1797            &calls,
1798            &progress,
1799            false,
1800            &early_exit,
1801            None,
1802            ShrinkErrorPolicy::KeepRemoved,
1803            |_, _| Err(eyre::eyre!("candidate replay failed")),
1804        );
1805
1806        assert_eq!(shrinker.current().collect::<Vec<_>>(), vec![1]);
1807    }
1808
1809    #[test]
1810    fn shrink_loop_stops_at_deadline() {
1811        let calls = vec![tx(None, None); 4];
1812        let early_exit = EarlyExit::new(false);
1813        let config = InvariantConfig::default();
1814        let attempts = |deadline| {
1815            let progress = ShrinkProgress::new(&config, None, "test", None, None, false);
1816            let mut attempts = 0;
1817            run_shrink_loop(
1818                &config,
1819                &calls,
1820                &progress,
1821                false,
1822                &early_exit,
1823                deadline,
1824                ShrinkErrorPolicy::RestoreRemoved,
1825                |_, _| {
1826                    attempts += 1;
1827                    Ok(false)
1828                },
1829            );
1830            attempts
1831        };
1832
1833        assert!(attempts(None) > 0);
1834        // A passed deadline stops shrinking however many attempts `shrink_run_limit` leaves.
1835        assert_eq!(attempts(Some(Instant::now())), 0);
1836    }
1837
1838    #[test]
1839    fn shrink_loop_discards_candidate_finished_after_deadline() {
1840        let config = InvariantConfig::default();
1841        let early_exit = EarlyExit::new(false);
1842        let calls = vec![tx(None, None); 4];
1843        let progress = ShrinkProgress::new(&config, None, "test", None, None, false);
1844        let deadline = Instant::now() + std::time::Duration::from_millis(50);
1845
1846        // Under `KeepRemoved` an error would accept the removal, like a cancelled replay can.
1847        let shrinker = run_shrink_loop(
1848            &config,
1849            &calls,
1850            &progress,
1851            false,
1852            &early_exit,
1853            Some(deadline),
1854            ShrinkErrorPolicy::KeepRemoved,
1855            |_, _| {
1856                std::thread::sleep(std::time::Duration::from_millis(100));
1857                Err(eyre::eyre!("cancelled replay"))
1858            },
1859        );
1860
1861        assert_eq!(shrinker.current().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
1862    }
1863
1864    #[test]
1865    fn candidate_executor_cancels_execution_at_deadline() {
1866        let mut executor = crate::executors::test_executor(
1867            ExecutorBuilder::<EthEvmNetwork>::default().gas_limit(1 << 24),
1868            Default::default(),
1869        );
1870        let target = Address::repeat_byte(0x11);
1871        // JUMPDEST; PUSH1 0; JUMP loops until gas runs out.
1872        executor
1873            .set_code(target, Bytecode::new_raw(Bytes::from_static(&[0x5b, 0x60, 0x00, 0x56])))
1874            .unwrap();
1875        let early_exit = EarlyExit::new(false);
1876
1877        let candidates = candidate_executor(&executor, &early_exit, Some(Instant::now()));
1878        let result = candidates
1879            .call_raw(foundry_evm_core::constants::CALLER, target, Bytes::new(), U256::ZERO)
1880            .unwrap();
1881        assert!(result.execution_cancelled);
1882
1883        // Without a deadline candidates run on the executor itself, uncancelled.
1884        let candidates = candidate_executor(&executor, &early_exit, None);
1885        assert!(matches!(candidates, Cow::Borrowed(_)));
1886    }
1887
1888    #[test]
1889    fn handler_shrink_keeps_candidate_confirmed_before_deadline() {
1890        let mut executor = crate::executors::test_executor(
1891            ExecutorBuilder::<EthEvmNetwork>::default()
1892                .inspectors(|stack| stack.cheatcodes(Arc::new(CheatsConfig::default())))
1893                .gas_limit(1 << 24),
1894            Default::default(),
1895        );
1896        let handler = Address::repeat_byte(0x11);
1897        // Empty calldata is a no-op. Otherwise the calldata is forwarded to the cheatcode address
1898        // when it is 36 bytes long (`vm.sleep`) or slot zero is set, and a 36-byte call then sets
1899        // slot zero.
1900        let mut code =
1901            hex!("3615604557366024146000541715604557366000600037600060003660006000").to_vec();
1902        code.push(0x73);
1903        code.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
1904        code.extend_from_slice(&hex!("5af150366024141560455760016000555b00"));
1905        executor.set_code(handler, Bytecode::new_raw(code.into())).unwrap();
1906        let call = |calldata: Vec<u8>| {
1907            let mut call = tx(None, None);
1908            call.call_details.target = handler;
1909            call.call_details.calldata = calldata.into();
1910            call
1911        };
1912        let sleep = std::time::Duration::from_millis(500);
1913        let noop = call(vec![]);
1914        // A call to the cheatcode address itself runs `vm.sleep` before any cancellation poll.
1915        let mut pause =
1916            call(Vm::sleepCall { duration: U256::from(sleep.as_millis()) }.abi_encode());
1917        pause.call_details.target = CHEATCODE_ADDRESS;
1918        let arm = call(Vm::sleepCall { duration: U256::ZERO }.abi_encode());
1919        let boom = call(Vm::assertTrue_1Call { condition: false, err: "boom".into() }.abi_encode());
1920        let mut calls = vec![noop; 9];
1921        calls[4] = pause;
1922        calls[5] = arm;
1923        calls[8] = boom;
1924        let all = (0..calls.len()).collect::<Vec<_>>();
1925        let full =
1926            replay_handler_failure_sequence(executor.clone(), &calls, &all, false, None).unwrap();
1927        assert!(full.anchor_asserted);
1928
1929        // Dropping the first four calls replays one sleep and is confirmed before the deadline. A
1930        // later candidate replays the sleep again and crosses the deadline.
1931        let config = InvariantConfig::default();
1932        let progress = ShrinkProgress::new(&config, None, "test", None, None, false);
1933        let start = Instant::now();
1934        let shrunk = shrink_handler_sequence(
1935            &config,
1936            &calls,
1937            full.anchor_fingerprint,
1938            &executor,
1939            &progress,
1940            &EarlyExit::new(false),
1941            Some(start + 2 * sleep),
1942        )
1943        .unwrap();
1944        assert_eq!(shrunk, calls[4..]);
1945        // A verifying replay after the deadline would sleep again.
1946        assert!(start.elapsed() < 2 * sleep + sleep / 2);
1947    }
1948
1949    #[test]
1950    fn sequence_shrinker_skips_duplicate_candidates_without_spending_attempts() {
1951        let mut run = ShrinkRun::new(2);
1952        let mut seen = Vec::new();
1953
1954        let shrinker = shrink_sequence_by_removing(
1955            2,
1956            &mut run,
1957            true,
1958            || false,
1959            || {},
1960            |shrinker, _| {
1961                let candidate = shrinker.current().collect::<Vec<_>>();
1962                if seen.contains(&candidate) {
1963                    None
1964                } else {
1965                    seen.push(candidate);
1966                    Some(false)
1967                }
1968            },
1969        );
1970
1971        assert_eq!(shrinker.current().collect::<Vec<_>>(), vec![0, 1]);
1972        let stats = run.finish();
1973        assert_eq!(stats.attempts, 2);
1974        assert_eq!(stats.accepted, 0);
1975    }
1976
1977    #[test]
1978    fn sequence_shrinker_reports_first_removed_index() {
1979        let mut run = ShrinkRun::new(100);
1980        let mut accepted = (0..6).collect::<Vec<_>>();
1981        let mut candidates = Vec::new();
1982
1983        shrink_sequence_by_removing(
1984            6,
1985            &mut run,
1986            true,
1987            || false,
1988            || {},
1989            |shrinker, first_removed| {
1990                let candidate = shrinker.current().collect::<Vec<_>>();
1991                let removed = accepted.iter().copied().filter(|idx| !candidate.contains(idx));
1992                assert_eq!(removed.min(), Some(first_removed));
1993                assert!(
1994                    accepted
1995                        .iter()
1996                        .take_while(|&&idx| idx < first_removed)
1997                        .all(|idx| candidate.contains(idx))
1998                );
1999                candidates.push(candidate.clone());
2000                // Keep calls 1 and 4: block and single candidates both report the first removed
2001                // call.
2002                let still_fails = candidate.contains(&1) && candidate.contains(&4);
2003                if still_fails {
2004                    accepted = candidate;
2005                }
2006                Some(still_fails)
2007            },
2008        );
2009
2010        assert_eq!(accepted, vec![1, 4]);
2011        assert!(candidates.len() > 2);
2012    }
2013
2014    #[test]
2015    fn shrink_progress_message_renders_current_sequence() {
2016        let calls = vec![tx_with_calldata(1), tx_with_calldata(2)];
2017
2018        let message =
2019            format_shrink_progress_message(" Shrink: invariant_live", &calls, None, false);
2020
2021        assert!(message.contains(" Shrink: invariant_live"));
2022        assert!(message.contains("[Sequence] (shrunk: 2)"));
2023        assert!(message.contains("calldata=0x01 args=[]"));
2024        assert!(message.contains("calldata=0x02 args=[]"));
2025    }
2026
2027    #[test]
2028    fn shrink_progress_message_omits_middle_of_large_sequence() {
2029        let calls = (0..(LIVE_SHRINK_SEQUENCE_EDGE_CALLS * 2 + 3))
2030            .map(|idx| tx_with_calldata(idx as u8))
2031            .collect::<Vec<_>>();
2032
2033        let message =
2034            format_shrink_progress_message(" Shrink: invariant_live", &calls, None, false);
2035
2036        assert!(message.contains("[Sequence] (shrunk: 35)"));
2037        assert!(message.contains("... 3 call(s) omitted ..."));
2038        assert_eq!(message.matches("sender=").count(), LIVE_SHRINK_SEQUENCE_EDGE_CALLS * 2);
2039        assert!(message.contains("calldata=0x00 args=[]"));
2040        assert!(message.contains("calldata=0x22 args=[]"));
2041    }
2042
2043    #[test]
2044    fn handler_replay_rejects_assumption_after_caught_assertion() {
2045        let mut executor = crate::executors::test_executor(
2046            ExecutorBuilder::<EthEvmNetwork>::default()
2047                .inspectors(|stack| stack.cheatcodes(Arc::new(CheatsConfig::default())))
2048                .gas_limit(1 << 24),
2049            Default::default(),
2050        );
2051        let handler = Address::repeat_byte(0x11);
2052        let assertion =
2053            Vm::assertTrue_1Call { condition: false, err: "custom reason".into() }.abi_encode();
2054        let assumption = Vm::assumeCall { condition: false }.abi_encode();
2055        // Four-byte calldata prepares slot zero. Otherwise, catch the assertion revert, assume
2056        // slot zero is set, and bubble the assumption's return data. The anchor's EVM path is
2057        // identical whether assume accepts or rejects; only the native cheatcode result differs.
2058        let mut code = hex!("366004146000573660006000376000600060").to_vec();
2059        code.push(assertion.len() as u8);
2060        code.extend_from_slice(&hex!("6000600073"));
2061        code.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
2062        code.extend_from_slice(&hex!("5af15060005460"));
2063        code.push((assertion.len() + 4) as u8);
2064        code.extend_from_slice(&hex!("526000600060"));
2065        code.push(assumption.len() as u8);
2066        code.push(0x60);
2067        code.push(assertion.len() as u8);
2068        code.extend_from_slice(&hex!("600073"));
2069        code.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
2070        code.extend_from_slice(&hex!("5af1503d600060003e3d6000fd"));
2071        code[5] = code.len() as u8;
2072        code.extend_from_slice(&hex!("5b600160005500"));
2073        executor.set_code(handler, Bytecode::new_raw(code.into())).unwrap();
2074        let mut calldata = assertion;
2075        calldata.extend_from_slice(&assumption);
2076        let mut call = tx(None, None);
2077        call.call_details.target = handler;
2078        call.call_details.calldata = calldata.into();
2079        let mut prepare = call.clone();
2080        prepare.call_details.calldata = Bytes::from_static(&[1, 2, 3, 4]);
2081        let calls = [prepare, call];
2082
2083        let (kind, result) = execute_invariant_replay_tx(&mut executor.clone(), &calls[1]).unwrap();
2084        assert_eq!(kind, CampaignCallKind::AssumptionRejected);
2085        assert!(result.failed_assertion.is_some());
2086        let full = replay_handler_failure_sequence(executor.clone(), &calls, &[0, 1], false, None)
2087            .unwrap();
2088        assert!(full.anchor_asserted);
2089        let replay =
2090            replay_handler_failure_sequence(executor.clone(), &calls, &[1], false, None).unwrap();
2091
2092        let config = InvariantConfig::default();
2093        let progress = ShrinkProgress::new(&config, None, "test", None, None, false);
2094        let shrunk = shrink_handler_sequence(
2095            &config,
2096            &calls,
2097            full.anchor_fingerprint,
2098            &executor,
2099            &progress,
2100            &EarlyExit::new(false),
2101            None,
2102        )
2103        .unwrap();
2104        assert_eq!(shrunk, calls);
2105        assert!(!replay.anchor_asserted);
2106    }
2107
2108    #[test]
2109    fn terminal_replay_reports_revert_after_caught_assertion() {
2110        let mut executor = crate::executors::test_executor(
2111            ExecutorBuilder::<EthEvmNetwork>::default()
2112                .inspectors(|stack| stack.cheatcodes(Arc::new(CheatsConfig::default())))
2113                .gas_limit(1 << 24),
2114            Default::default(),
2115        );
2116        let test_address = Address::repeat_byte(0x11);
2117        let assertion =
2118            Vm::assertTrue_1Call { condition: false, err: "assert message".into() }.abi_encode();
2119        let revert = Revert::from("revert message").abi_encode();
2120        let (a, r) = (assertion.len() as u16, revert.len() as u16);
2121        // Calls the assertion and ignores its result, then reverts with another reason. Both
2122        // payloads are appended after the 59-byte code.
2123        let mut code = vec![0x61];
2124        code.extend_from_slice(&a.to_be_bytes());
2125        code.extend_from_slice(&hex!("61003b6000396000600061"));
2126        code.extend_from_slice(&a.to_be_bytes());
2127        code.extend_from_slice(&hex!("6000600073"));
2128        code.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
2129        code.extend_from_slice(&hex!("5af15061"));
2130        code.extend_from_slice(&r.to_be_bytes());
2131        code.push(0x61);
2132        code.extend_from_slice(&(59 + a).to_be_bytes());
2133        code.extend_from_slice(&hex!("60003961"));
2134        code.extend_from_slice(&r.to_be_bytes());
2135        code.extend_from_slice(&hex!("6000fd"));
2136        assert_eq!(code.len(), 59);
2137        code.extend_from_slice(&assertion);
2138        code.extend_from_slice(&revert);
2139        executor.set_code(test_address, Bytecode::new_raw(code.into())).unwrap();
2140
2141        let rd = RevertDecoder::new();
2142        let outcome = check_sequence(
2143            executor,
2144            &[],
2145            &[],
2146            test_address,
2147            Bytes::new(),
2148            CheckSequenceOptions {
2149                accumulate_warp_roll: false,
2150                fail_on_revert: true,
2151                expect_assertion_failure: true,
2152                call_after_invariant: false,
2153                rd: Some(&rd),
2154            },
2155        )
2156        .unwrap();
2157        assert!(!outcome.success);
2158        assert_eq!(outcome.reason.as_deref(), Some("revert message"));
2159    }
2160}