Skip to main content

foundry_evm/executors/fuzz/
mod.rs

1use crate::executors::{
2    DURATION_BETWEEN_METRICS_REPORT, EarlyExit, Executor, FuzzTestTimer, RawCallResult, RawFailure,
3    campaign::{CampaignCallKind, CampaignControl, CampaignEvent, FuzzCampaign, FuzzCampaignMode},
4    corpus::{
5        CorpusSyncCoordinator, GlobalCorpusMetrics, ReplayTarget, StatelessReplayTarget,
6        WorkerCorpus,
7    },
8    should_ignore_revert, worker_seed,
9};
10use alloy_dyn_abi::JsonAbiExt;
11use alloy_json_abi::Function;
12use alloy_primitives::{
13    Address, Bytes, Log, U256,
14    map::{AddressHashMap, HashMap},
15};
16use eyre::Result;
17use foundry_common::{sh_eprintln, sh_warn};
18use foundry_config::FuzzConfig;
19use foundry_evm_core::{
20    Breakpoints,
21    constants::MAGIC_ASSUME,
22    decode::{RevertDecoder, SkipReason},
23    evm::FoundryEvmNetwork,
24};
25use foundry_evm_coverage::HitMaps;
26use foundry_evm_fuzz::{
27    BaseCounterExample, BasicTxDetails, CallDetails, CounterExample, FuzzCase, FuzzError,
28    FuzzFixtures, FuzzRunMetadata, FuzzTestResult,
29    strategies::{EvmFuzzState, TxGenerator},
30};
31use foundry_evm_traces::SparsedTraceArena;
32use indicatif::ProgressBar;
33use proptest::test_runner::{RngAlgorithm, TestCaseError, TestRng, TestRunner};
34use rayon::iter::{IntoParallelIterator, ParallelIterator};
35use serde_json::json;
36use std::{
37    path::PathBuf,
38    sync::{
39        Arc,
40        atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
41    },
42    time::{Instant, SystemTime, UNIX_EPOCH},
43};
44
45mod frontier;
46mod types;
47pub use frontier::FuzzBranchFrontier;
48use frontier::FuzzBranchFrontierArtifact;
49pub(super) use frontier::{
50    FuzzFrontierRecorder, StatefulFuzzBranchFrontierArtifact, comparison_result, merge_frontiers,
51    write_frontier_artifact,
52};
53pub use types::{CaseOutcome, CounterExampleOutcome, FuzzOutcome};
54
55/// Corpus syncs across workers every `SYNC_INTERVAL` runs.
56const SYNC_INTERVAL: u32 = 1000;
57
58/// Minimum number of runs per worker.
59/// This is mainly to reduce the overall number of rayon jobs.
60const MIN_RUNS_PER_WORKER: u32 = 64;
61
62/// A transaction and the run metadata needed to replay it.
63type ReplayCase = (BasicTxDetails, Option<FuzzRunMetadata>);
64
65struct WorkerState<FEN: FoundryEvmNetwork> {
66    /// Worker identifier
67    id: usize,
68    /// Gas usage for all cases this worker ran
69    gas_by_case: Vec<(u64, u64)>,
70    /// Counterexample if this worker found one
71    counterexample: Option<(BasicTxDetails, RawCallResult<FEN>)>,
72    /// Traces collected by this worker
73    ///
74    /// Stores up to `max_traces_to_collect` which is `config.gas_report_samples / num_workers`
75    traces: Vec<SparsedTraceArena>,
76    /// Runtime bytecodes for the last collected trace.
77    debug_bytecodes: AddressHashMap<Bytes>,
78    /// Last breakpoints from this worker
79    breakpoints: Option<Breakpoints>,
80    /// The input of the last collected trace and the run that generated it.
81    last_case: Option<ReplayCase>,
82    /// Coverage collected by this worker
83    coverage: Option<HitMaps>,
84    /// Logs from all cases this worker ran
85    logs: Vec<Log>,
86    /// Deprecated cheatcodes seen by this worker
87    deprecated_cheatcodes: HashMap<&'static str, Option<&'static str>>,
88    /// Number of runs this worker completed
89    runs: u32,
90    /// Failure reason if this worker failed
91    failure: Option<TestCaseError>,
92    /// Fuzz run metadata that produced the failure.
93    failure_run: Option<FuzzRunMetadata>,
94    /// Failed corpus replays
95    failed_corpus_replays: usize,
96    /// Branch frontiers captured for symbolic follow-up.
97    frontiers: Vec<FuzzBranchFrontier>,
98}
99
100impl<FEN: FoundryEvmNetwork> WorkerState<FEN> {
101    fn new(worker_id: usize) -> Self {
102        Self {
103            id: worker_id,
104            gas_by_case: Vec::new(),
105            counterexample: None,
106            traces: Vec::new(),
107            debug_bytecodes: HashMap::default(),
108            breakpoints: None,
109            last_case: None,
110            coverage: None,
111            logs: Vec::new(),
112            deprecated_cheatcodes: HashMap::default(),
113            runs: 0,
114            failure: None,
115            failure_run: None,
116            failed_corpus_replays: 0,
117            frontiers: Vec::new(),
118        }
119    }
120}
121
122/// Shared state for coordinating parallel fuzz workers
123struct SharedFuzzState {
124    state: EvmFuzzState,
125    /// Total runs across workers
126    total_runs: Arc<AtomicU32>,
127    /// The first failure of the campaign, see [`Self::failure_order`].
128    ///
129    /// Each worker draws its inputs from its own seed stream, so the worker that fails first in
130    /// time depends on thread scheduling. The campaign reports the failure that is first in this
131    /// order instead, which only depends on the seed and on the number of workers.
132    first_failure: AtomicU64,
133    /// Total rejects across workers
134    total_rejects: Arc<AtomicU32>,
135    /// Fuzz timer
136    timer: FuzzTestTimer,
137    /// Whether a worker stopped because the timer expired.
138    timed_out: AtomicBool,
139    /// Global corpus metrics
140    global_corpus_metrics: GlobalCorpusMetrics,
141
142    /// Global test suite early exit.
143    global_early_exit: EarlyExit,
144}
145
146impl SharedFuzzState {
147    fn new(state: EvmFuzzState, timeout: Option<u32>, early_exit: EarlyExit) -> Self {
148        Self {
149            state,
150            total_runs: Arc::new(AtomicU32::new(0)),
151            first_failure: AtomicU64::new(u64::MAX),
152            total_rejects: Arc::new(AtomicU32::new(0)),
153            timer: FuzzTestTimer::new(timeout),
154            timed_out: AtomicBool::new(false),
155            global_corpus_metrics: GlobalCorpusMetrics::default(),
156            global_early_exit: early_exit,
157        }
158    }
159
160    /// Increments the number of runs and returns the new value.
161    fn increment_runs(&self) -> u32 {
162        self.total_runs.fetch_add(1, Ordering::Relaxed) + 1
163    }
164
165    /// Increments and returns the new value of the number of rejected tests.
166    fn increment_rejects(&self) -> u32 {
167        self.total_rejects.fetch_add(1, Ordering::Relaxed) + 1
168    }
169
170    /// Returns `true` if the worker should continue after its first `runs` runs.
171    ///
172    /// A worker stops when a recorded failure is ordered before its next run: no failure that
173    /// the worker can still find replaces the recorded one.
174    fn should_continue(&self, worker_id: usize, runs: u32) -> bool {
175        if self.global_early_exit.should_stop()
176            || self.first_failure.load(Ordering::Relaxed) < Self::failure_order(worker_id, runs)
177        {
178            return false;
179        }
180        if self.timer.is_timed_out() {
181            self.timed_out.store(true, Ordering::Relaxed);
182            return false;
183        }
184        true
185    }
186
187    /// Returns `true` if fail-fast or Ctrl-C stopped the campaign before its timeout or
188    /// `planned_runs`.
189    fn interrupted(&self, planned_runs: u32) -> bool {
190        self.global_early_exit.should_stop()
191            && !self.timed_out.load(Ordering::Relaxed)
192            && self.total_runs.load(Ordering::Relaxed) < planned_runs
193    }
194
195    /// Records that the worker failed after its first `runs` runs.
196    fn record_failure(&self, worker_id: usize, runs: u32) {
197        self.first_failure.fetch_min(Self::failure_order(worker_id, runs), Ordering::Relaxed);
198    }
199
200    /// Returns the worker that found the first failure and the number of runs that the worker
201    /// completed before the failure.
202    fn first_failure(&self) -> Option<(usize, u32)> {
203        let order = self.first_failure.load(Ordering::Relaxed);
204        (order != u64::MAX).then_some((order as u32 as usize, (order >> 32) as u32))
205    }
206
207    /// Orders failures by the number of runs that the worker completed before the failure, then
208    /// by worker ID. This is the order in which one thread finds the failures when it runs the
209    /// workers in turn, one run at a time.
210    const fn failure_order(worker_id: usize, runs: u32) -> u64 {
211        (runs as u64) << 32 | worker_id as u64
212    }
213}
214
215/// Minimizes the calldata of a failing counterexample.
216///
217/// The second argument replays candidate calldata and returns whether it still fails the same
218/// way. Returns the minimized calldata when it differs from the counterexample's.
219pub type CounterexampleMinimizer<'a> =
220    &'a dyn Fn(&BaseCounterExample, &mut dyn FnMut(&Bytes) -> bool) -> Option<Bytes>;
221
222/// Wrapper around an [`Executor`] which provides fuzzing support using [`proptest`].
223///
224/// After instantiation, calling `fuzz` will proceed to hammer the deployed smart contract with
225/// inputs, until it finds a counterexample. The provided [`TestRunner`] contains all the
226/// configuration which can be overridden via [environment variables](proptest::test_runner::Config)
227pub struct FuzzedExecutor<FEN: FoundryEvmNetwork> {
228    /// The EVM executor.
229    executor_f: Executor<FEN>,
230    /// The fuzzer
231    runner: TestRunner,
232    /// The account that calls tests.
233    sender: Address,
234    /// The fuzz configuration.
235    config: FuzzConfig,
236    /// The persisted counterexample to be replayed, if any.
237    persisted_failure: Option<BaseCounterExample>,
238    /// An existing corpus to replay before persisting into the configured corpus directory.
239    corpus_replay_dir: Option<PathBuf>,
240    /// The number of parallel workers.
241    num_workers: usize,
242}
243
244impl<FEN: FoundryEvmNetwork> FuzzedExecutor<FEN> {
245    /// Instantiates a fuzzed executor given a testrunner
246    pub fn new(
247        executor: Executor<FEN>,
248        runner: TestRunner,
249        sender: Address,
250        config: FuzzConfig,
251        persisted_failure: Option<BaseCounterExample>,
252        corpus_replay_dir: Option<PathBuf>,
253    ) -> Self {
254        let run_limit = if config.run.is_some() { 1 } else { config.runs };
255        let max_workers = if run_limit == 0 {
256            0
257        } else if config.run.is_some() {
258            1
259        } else {
260            Ord::max(1, run_limit / MIN_RUNS_PER_WORKER)
261        };
262        let num_workers = Ord::min(rayon::current_num_threads(), max_workers as usize);
263        Self {
264            executor_f: executor,
265            runner,
266            sender,
267            config,
268            persisted_failure,
269            corpus_replay_dir,
270            num_workers,
271        }
272    }
273
274    /// Fuzzes the provided function, assuming it is available at the contract at `address`
275    ///
276    /// Returns a list of all the consumed gas and calldata of every fuzz case.
277    #[allow(clippy::too_many_arguments)]
278    pub fn fuzz(
279        &mut self,
280        func: &Function,
281        fuzz_fixtures: &FuzzFixtures,
282        state: EvmFuzzState,
283        address: Address,
284        rd: &RevertDecoder,
285        progress: Option<&ProgressBar>,
286        early_exit: &EarlyExit,
287        tokio_handle: &tokio::runtime::Handle,
288        minimize: Option<CounterexampleMinimizer<'_>>,
289    ) -> Result<FuzzTestResult> {
290        let shared_state = SharedFuzzState::new(state, self.config.timeout, early_exit.clone());
291        // Every run would append its steps to the shared step table, so the campaign runs without
292        // the debug recorder and the shown case runs again with it.
293        let recorder = self.executor_f.inspector_mut().debug_recorder.take();
294        // Minimization replays the counterexample and needs to know whether it failed where the
295        // campaign did.
296        if minimize.is_some() {
297            self.executor_f.inspector_mut().collect_failure_provenance(true);
298        }
299
300        let worker_ids = self.worker_ids();
301        debug!(n = worker_ids.len(), "spawning workers");
302        let final_sync = (worker_ids.len() > 1 && self.config.corpus.corpus_dir.is_some())
303            .then(|| CorpusSyncCoordinator::new(worker_ids.len()));
304        let run_worker = |worker_id| {
305            let _guard = tokio_handle.enter();
306            let _guard = info_span!("fuzz_worker", id = worker_id).entered();
307            let timer = Instant::now();
308            let r = self.run_worker(
309                worker_id,
310                func,
311                fuzz_fixtures,
312                address,
313                rd,
314                &shared_state,
315                progress,
316                final_sync.as_ref(),
317            );
318            if r.is_err()
319                && let Some(final_sync) = &final_sync
320            {
321                final_sync.abort();
322            }
323            debug!("finished in {:?}", timer.elapsed());
324            r
325        };
326        let workers = if let Some(final_sync) = &final_sync {
327            // Corpus-syncing workers block until every peer reaches the barrier, so each needs its
328            // own thread: on the rayon pool a waiting job can hold the thread a peer needs.
329            final_sync.run_workers(
330                worker_ids
331                    .into_iter()
332                    .map(|worker_id| (std::thread::Builder::new(), move || run_worker(worker_id))),
333            )
334        } else {
335            worker_ids.into_par_iter().map(run_worker).collect::<Result<Vec<_>>>()
336        };
337
338        let (mut result, mut shown_case, campaign_failure) =
339            self.aggregate_results(workers?, func, &shared_state);
340        if let Some(minimize) = minimize
341            && let Some(campaign_failure) = campaign_failure
342        {
343            self.executor_f.inspector_mut().collect_failure_identity(true);
344            self.minimize_counterexample(
345                &mut result,
346                &mut shown_case,
347                &campaign_failure,
348                func,
349                address,
350                rd,
351                &shared_state,
352                minimize,
353            );
354            self.executor_f.inspector_mut().collect_failure_identity(false);
355        }
356        self.executor_f.inspector_mut().collect_failure_provenance(false);
357        self.executor_f.inspector_mut().debug_recorder = recorder;
358        if self.executor_f.inspector().debug_recorder.is_some()
359            && let Some(case) = shown_case
360        {
361            self.record_case(&mut result, address, case)?;
362        }
363        Ok(result)
364    }
365
366    /// Runs `case` again and replaces the shown trace of `result` with the one it records, along
367    /// with its bytecodes and breakpoints.
368    fn record_case(
369        &mut self,
370        result: &mut FuzzTestResult,
371        address: Address,
372        (tx, run): ReplayCase,
373    ) -> Result<()> {
374        let (_, call, success) = self.replay_case(address, tx, run.as_ref())?;
375        // State outside the EVM, such as files or environment variables, can change the outcome.
376        if success != result.success {
377            let _ = sh_warn!(
378                "the debugged fuzz case {} when run again, unlike in the campaign, so the debugger \
379                 may show a different path",
380                if success { "passed" } else { "failed" }
381            );
382        }
383        result.traces = call.traces;
384        result.debug_bytecodes = call.debug_bytecodes;
385        result.breakpoints = call.cheatcodes.map(|cheats| cheats.breakpoints.clone());
386        Ok(())
387    }
388
389    /// Runs `tx` against `address` as the campaign ran the fuzz `run`, returning the resolved
390    /// transaction, the call, and whether the test passed.
391    fn replay_case(
392        &mut self,
393        address: Address,
394        mut tx: BasicTxDetails,
395        run: Option<&FuzzRunMetadata>,
396    ) -> Result<(BasicTxDetails, RawCallResult<FEN>, bool)> {
397        if let Some(cheats) = self.executor_f.inspector_mut().cheatcodes.as_mut()
398            && let Some(run) = run
399            && let Some(seed) = run.seed.or(self.config.seed)
400        {
401            let worker = run.worker.unwrap_or(0) as usize;
402            cheats.core.set_seed(Self::fuzz_run_seed(seed, worker, run.run.unwrap_or(1)));
403        }
404        tx.sender = self.sender;
405        tx.call_details.target = address;
406        tx.warp = None;
407        tx.roll = None;
408        self.resolve_stateless_tx_with_executor(&self.executor_f, &mut tx)?;
409        let mut call = self.executor_f.call_raw(
410            tx.sender,
411            tx.call_details.target,
412            tx.call_details.calldata.clone(),
413            tx.call_details.value.unwrap_or_default(),
414        )?;
415        let success = should_ignore_revert(
416            self.config.fail_on_revert,
417            address,
418            call.reverter,
419            self.executor_f.inspector().extra_cheatcode_addresses(),
420        ) || self.executor_f.is_raw_call_mut_success(address, &mut call);
421        Ok((tx, call, success))
422    }
423
424    /// Replaces the counterexample of a failed `result` with a minimized one that fails the same
425    /// way, see [`RawCallResult::failure_identity`]. Keeps the counterexample when the failure
426    /// cannot be identified, a replay errors, the test is stopped, or replaying it does not
427    /// reproduce the campaign's failure, see [`RawCallResult::raw_failure`].
428    ///
429    /// Expects failure identities and provenances to be collected.
430    #[expect(clippy::too_many_arguments)]
431    fn minimize_counterexample(
432        &mut self,
433        result: &mut FuzzTestResult,
434        shown_case: &mut Option<ReplayCase>,
435        campaign_failure: &RawFailure,
436        func: &Function,
437        address: Address,
438        rd: &RevertDecoder,
439        shared_state: &SharedFuzzState,
440        minimize: CounterexampleMinimizer<'_>,
441    ) {
442        // Replays stop on Ctrl-C or fail-fast, and at the test's deadline.
443        let stopped =
444            || shared_state.global_early_exit.should_stop() || shared_state.timer.is_timed_out();
445        if result.success || result.skipped || stopped() {
446            return;
447        }
448        let (Some(CounterExample::Single(counterexample)), Some((tx, run))) =
449            (&result.counterexample, shown_case.clone())
450        else {
451            return;
452        };
453        // External state can change the outcome of the same calldata. Only identify the failure
454        // when replaying it reproduces the campaign's, from the same sites.
455        let Ok((_, original, false)) = self.replay_case(address, tx.clone(), run.as_ref()) else {
456            return;
457        };
458        let Some(expected) = original.failure_identity.filter(|_| {
459            original.raw_failure().as_ref() == Some(campaign_failure)
460                && !original.has_state_snapshot_failure
461        }) else {
462            return;
463        };
464        let fails_same_way = |call: &RawCallResult<FEN>, success: bool| {
465            !success
466                && call.result.as_ref() != MAGIC_ASSUME
467                && call.skip_reason().is_none()
468                && call.reverter == original.reverter
469                && call.failure_identity == Some(expected)
470        };
471        // The minimized calldata is the last accepted candidate's, so its replay is reused.
472        let mut accepted = None;
473        let mut still_fails = |calldata: &Bytes| {
474            if stopped() {
475                return false;
476            }
477            let mut candidate = tx.clone();
478            candidate.call_details.calldata = calldata.clone();
479            // Each candidate runs alone, so host effects skipped by earlier ones do not affect it.
480            self.executor_f.inspector_mut().collect_failure_identity(true);
481            let Ok((candidate, call, success)) = self.replay_case(address, candidate, run.as_ref())
482            else {
483                return false;
484            };
485            let fails = fails_same_way(&call, success);
486            if fails {
487                accepted = Some((candidate, call));
488            }
489            fails
490        };
491        let Some(calldata) = minimize(counterexample, &mut still_fails).filter(|_| !stopped())
492        else {
493            return;
494        };
495        let Some((minimized, call)) =
496            accepted.filter(|(minimized, _)| minimized.call_details.calldata == calldata)
497        else {
498            return;
499        };
500
501        let fuzz = counterexample.fuzz;
502        let args = minimized
503            .call_details
504            .calldata
505            .get(4..)
506            .map_or_else(Vec::new, |data| func.abi_decode_input(data).unwrap_or_default());
507        result.reason =
508            rd.maybe_decode(&call.result, call.exit_reason).filter(|reason| !reason.is_empty());
509        result.labels.clone_from(&call.labels);
510        result.traces.clone_from(&call.traces);
511        result.debug_bytecodes.clone_from(&call.debug_bytecodes);
512        result.breakpoints = call.cheatcodes.as_ref().map(|cheats| cheats.breakpoints.clone());
513        result.fork_block_number = call.fork_block_number;
514        if !self.config.show_logs {
515            result.logs.clone_from(&call.logs);
516        }
517        result.counterexample = Some(CounterExample::Single(
518            BaseCounterExample::from_fuzz_tx(&minimized, args, call.traces)
519                .with_fuzz_metadata(fuzz),
520        ));
521        *shown_case = Some((minimized, run));
522    }
523
524    /// Replays the persisted single-call counterexample exactly once.
525    ///
526    /// Unlike [`Self::fuzz`], this never falls through to generated inputs if the persisted
527    /// calldata now succeeds or is rejected by `vm.assume`.
528    pub fn replay_persisted_failure(
529        &mut self,
530        func: &Function,
531        address: Address,
532        rd: &RevertDecoder,
533    ) -> Result<FuzzTestResult> {
534        let Some(failure) = self.persisted_failure.as_ref() else {
535            return Ok(FuzzTestResult {
536                skipped: true,
537                reason: Some("no persisted fuzz failure to replay".to_string()),
538                ..Default::default()
539            });
540        };
541
542        let seed = failure.fuzz.seed.or(self.config.seed);
543        if let Some(cheats) = self.executor_f.inspector_mut().cheatcodes.as_mut()
544            && let Some(seed) = seed
545        {
546            let run = failure.fuzz.run.unwrap_or(1);
547            let worker = failure.fuzz.worker.unwrap_or(0) as usize;
548            cheats.core.set_seed(Self::fuzz_run_seed(seed, worker, run));
549        }
550
551        let mut tx = BasicTxDetails {
552            warp: None,
553            roll: None,
554            sender: self.sender,
555            call_details: CallDetails {
556                target: address,
557                calldata: failure.calldata.clone(),
558                value: failure.value,
559            },
560        };
561        self.resolve_stateless_tx_with_executor(&self.executor_f, &mut tx)?;
562        let mut call = self.executor_f.call_raw(
563            tx.sender,
564            tx.call_details.target,
565            tx.call_details.calldata.clone(),
566            tx.call_details.value.unwrap_or_default(),
567        )?;
568        if call.result.as_ref() == MAGIC_ASSUME {
569            return Ok(FuzzTestResult {
570                skipped: true,
571                reason: Some("persisted fuzz failure rejected by `vm.assume`".to_string()),
572                ..Default::default()
573            });
574        }
575        if let Some(reason) = call.skip_reason() {
576            return Ok(FuzzTestResult { skipped: true, reason: reason.0, ..Default::default() });
577        }
578
579        let (breakpoints, deprecated_cheatcodes) =
580            call.cheatcodes.as_ref().map_or_else(Default::default, |cheats| {
581                (cheats.breakpoints.clone(), cheats.deprecated.clone())
582            });
583        let success = should_ignore_revert(
584            self.config.fail_on_revert,
585            address,
586            call.reverter,
587            self.executor_f.inspector().extra_cheatcode_addresses(),
588        ) || self.executor_f.is_raw_call_mut_success(address, &mut call);
589
590        let mut result = FuzzTestResult {
591            success,
592            labels: call.labels.clone(),
593            traces: call.traces.clone(),
594            debug_bytecodes: call.debug_bytecodes.clone(),
595            breakpoints: Some(breakpoints),
596            deprecated_cheatcodes,
597            fork_block_number: call.fork_block_number,
598            ..Default::default()
599        };
600
601        if success {
602            result.first_case = FuzzCase { gas: call.gas_used, stipend: call.stipend };
603            result.gas_by_case.push((call.gas_used, call.stipend));
604            result.line_coverage = call.line_coverage;
605            result.logs = call.logs;
606            result
607                .gas_report_traces
608                .extend(call.traces.into_iter().map(SparsedTraceArena::into_gas_report_arena));
609        } else {
610            let reason = call
611                .skip_reason()
612                .map(|reason| reason.to_string())
613                .or_else(|| rd.maybe_decode(&call.result, call.exit_reason));
614            result.reason = reason;
615            let args = tx
616                .call_details
617                .calldata
618                .get(4..)
619                .map_or_else(Vec::new, |data| func.abi_decode_input(data).unwrap_or_default());
620            result.counterexample = Some(CounterExample::Single(
621                BaseCounterExample::from_fuzz_tx(&tx, args, call.traces).with_fuzz_metadata(
622                    FuzzRunMetadata::new(
623                        seed,
624                        failure.fuzz.run,
625                        Some(failure.fuzz.worker.unwrap_or(0)),
626                    ),
627                ),
628            ));
629            result.logs = call.logs;
630        }
631
632        Ok(result)
633    }
634
635    /// Granular and single-step function that runs only one fuzz and returns either a `CaseOutcome`
636    /// or a `CounterExampleOutcome`
637    fn single_fuzz(
638        &self,
639        executor: &mut Executor<FEN>,
640        address: Address,
641        mut tx: BasicTxDetails,
642        coverage_metrics: &mut WorkerCorpus,
643        frontier_recorder: &mut FuzzFrontierRecorder,
644        fuzz_run: Option<&FuzzRunMetadata>,
645    ) -> Result<FuzzOutcome<FEN>, TestCaseError> {
646        tx.sender = self.sender;
647        tx.call_details.target = address;
648        tx.warp = None;
649        tx.roll = None;
650        self.resolve_stateless_tx_with_executor(executor, &mut tx)
651            .map_err(|e| TestCaseError::fail(e.to_string()))?;
652        let campaign = FuzzCampaign::new(FuzzCampaignMode::Stateless);
653        let mut state = (executor, tx);
654        let mut cmp_values = Vec::new();
655        let mut checked = None;
656        campaign
657            .run_sequence(
658                &mut state,
659                1,
660                |state| (state.0, &mut state.1),
661                |_| 0,
662                |_| false,
663                |_, event| {
664                    match event {
665                        CampaignEvent::Feedback(call) => {
666                            cmp_values = call.evm_cmp_values.take().unwrap_or_default();
667                        }
668                        CampaignEvent::Check { result, kind, .. } => {
669                            checked = Some((
670                                result.take().expect("campaign check result is available"),
671                                kind,
672                            ));
673                            return Ok(CampaignControl::Stop);
674                        }
675                        CampaignEvent::Advance | CampaignEvent::Next { .. } => {
676                            unreachable!("depth-one campaigns cannot advance")
677                        }
678                        CampaignEvent::PostCheck => {}
679                    }
680                    Ok(CampaignControl::Continue)
681                },
682            )
683            .map_err(|e| TestCaseError::fail(e.to_string()))?;
684        let (mut call, kind) = checked.expect("depth-one campaign emits a check event");
685        let tx = state.1.clone();
686
687        // Handle `vm.assume` before recording coverage or persisting the input.
688        if kind == CampaignCallKind::AssumptionRejected {
689            // Account for the attempted corpus mutation without retaining or crediting the input.
690            coverage_metrics.process_inputs(&[], &[], false, None);
691            return Err(TestCaseError::reject(FuzzError::AssumeReject));
692        }
693
694        if call.skip_reason().is_some() {
695            // Account for the attempted corpus mutation without retaining or crediting the input.
696            coverage_metrics.process_inputs(&[], &[], false, None);
697        } else {
698            let new_coverage = coverage_metrics.merge_edge_coverage(&mut call);
699            // `new_coverage` is only meaningful when edge coverage is collected; otherwise
700            // `merge_edge_coverage` always returns `false`, so record it as unknown for frontiers.
701            let frontier_new_coverage =
702                self.config.corpus.collect_edge_coverage().then_some(new_coverage);
703            frontier_recorder.capture_call(
704                fuzz_run,
705                std::slice::from_ref(&tx),
706                0,
707                &cmp_values,
708                frontier_new_coverage,
709            );
710            coverage_metrics.process_inputs(
711                std::slice::from_ref(&tx),
712                &[cmp_values],
713                new_coverage,
714                None,
715            );
716        }
717
718        let (breakpoints, deprecated_cheatcodes) =
719            call.cheatcodes.as_ref().map_or_else(Default::default, |cheats| {
720                (cheats.breakpoints.clone(), cheats.deprecated.clone())
721            });
722
723        // Consider call success if test should not fail on reverts and reverter is not the test
724        // address or one of the network's cheatcode contracts.
725        let success = should_ignore_revert(
726            self.config.fail_on_revert,
727            address,
728            call.reverter,
729            state.0.inspector().extra_cheatcode_addresses(),
730        ) || state.0.is_raw_call_mut_success(address, &mut call);
731
732        if success {
733            Ok(FuzzOutcome::Case(CaseOutcome {
734                case: FuzzCase { gas: call.gas_used, stipend: call.stipend },
735                traces: call.traces,
736                debug_bytecodes: call.debug_bytecodes,
737                coverage: call.line_coverage,
738                breakpoints,
739                logs: call.logs,
740                deprecated_cheatcodes,
741            }))
742        } else {
743            Ok(FuzzOutcome::CounterExample(CounterExampleOutcome {
744                exit_reason: call.exit_reason,
745                counterexample: (tx, call),
746                breakpoints,
747            }))
748        }
749    }
750
751    fn resolve_stateless_tx_with_executor(
752        &self,
753        executor: &Executor<FEN>,
754        tx: &mut BasicTxDetails,
755    ) -> Result<()> {
756        tx.call_details.value = match tx.call_details.value {
757            Some(requested) if !requested.is_zero() => {
758                let value = requested.min(executor.get_balance(tx.sender)?);
759                (!value.is_zero()).then_some(value)
760            }
761            _ => None,
762        };
763        Ok(())
764    }
765
766    /// Aggregates worker results, returning the shown input and its run along with the outcome
767    /// of the campaign's failing call, if any.
768    fn aggregate_results(
769        &self,
770        mut workers: Vec<WorkerState<FEN>>,
771        func: &Function,
772        shared_state: &SharedFuzzState,
773    ) -> (FuzzTestResult, Option<ReplayCase>, Option<RawFailure>) {
774        self.write_branch_frontiers(&mut workers, func);
775
776        let mut result = FuzzTestResult::default();
777        if workers.is_empty() {
778            result.success = true;
779            return (result, None, None);
780        }
781
782        // Find the worker of the last run, in the order of `SharedFuzzState::failure_order`. Set
783        // `failed_corpus_replays`.
784        let mut last_run_worker = None;
785        for (i, worker) in workers.iter().enumerate() {
786            if last_run_worker.is_none_or(|(runs, _)| worker.runs >= runs) {
787                last_run_worker = Some((worker.runs, i));
788            }
789
790            // Only set replays from master which is responsible for replaying persisted corpus.
791            if worker.id == 0 {
792                result.failed_corpus_replays = worker.failed_corpus_replays;
793            }
794        }
795        let (_, last_run_worker_idx) = last_run_worker.expect("at least one worker");
796        let mut output_worker_idx = last_run_worker_idx;
797        let shown_case;
798        let mut campaign_failure = None;
799
800        if let Some((failed_worker_id, failed_runs)) = shared_state.first_failure() {
801            result.success = false;
802
803            // The workers stop at different runs, so only keep the cases that are ordered before
804            // the failure.
805            for worker in &mut workers {
806                let cases = failed_runs as usize + usize::from(worker.id < failed_worker_id);
807                worker.gas_by_case.truncate(cases);
808            }
809
810            let failed_worker_idx = workers.iter().position(|w| w.id == failed_worker_id).unwrap();
811            output_worker_idx = failed_worker_idx;
812            let failed_worker = &mut workers[failed_worker_idx];
813
814            let counterexample = failed_worker.counterexample.take();
815            shown_case =
816                counterexample.as_ref().map(|(tx, _)| (tx.clone(), failed_worker.failure_run));
817            if let Some((_, call)) = &counterexample {
818                result.labels.clone_from(&call.labels);
819                result.traces.clone_from(&call.traces);
820                result.debug_bytecodes.clone_from(&call.debug_bytecodes);
821                result.breakpoints = call.cheatcodes.as_ref().map(|c| c.breakpoints.clone());
822                result.fork_block_number = call.fork_block_number;
823            }
824
825            match &failed_worker.failure {
826                Some(TestCaseError::Fail(reason)) => {
827                    let reason = reason.to_string();
828                    result.reason = (!reason.is_empty()).then_some(reason);
829                    if let Some((tx, call)) = counterexample {
830                        campaign_failure = call.raw_failure();
831                        let args =
832                            tx.call_details.calldata.get(4..).map_or_else(Vec::new, |data| {
833                                func.abi_decode_input(data).unwrap_or_default()
834                            });
835                        let fuzz = failed_worker.failure_run.unwrap_or_default();
836                        result.counterexample = Some(CounterExample::Single(
837                            BaseCounterExample::from_fuzz_tx(&tx, args, call.traces)
838                                .with_fuzz_metadata(FuzzRunMetadata::new(
839                                    fuzz.seed.or(self.config.seed),
840                                    fuzz.run,
841                                    fuzz.worker,
842                                )),
843                        ));
844                    }
845                }
846                Some(TestCaseError::Reject(reason)) => {
847                    let reason = reason.to_string();
848                    result.reason = (!reason.is_empty()).then_some(reason);
849                }
850                None => {}
851            }
852        } else {
853            let last_run_worker = &workers[last_run_worker_idx];
854            result.success = true;
855            let planned_runs = if self.config.run.is_some() { 1 } else { self.config.runs };
856            if shared_state.interrupted(planned_runs) {
857                result.skipped = true;
858                result.reason = Some("interrupted".to_string());
859            }
860            result.traces = last_run_worker.traces.last().cloned();
861            result.debug_bytecodes.clone_from(&last_run_worker.debug_bytecodes);
862            result.breakpoints = last_run_worker.breakpoints.clone();
863            shown_case = last_run_worker.last_case.clone();
864        }
865
866        if !self.config.show_logs {
867            result.logs = workers[output_worker_idx].logs.clone();
868        }
869
870        for mut worker in workers {
871            result.gas_by_case.append(&mut worker.gas_by_case);
872            if self.config.show_logs {
873                result.logs.append(&mut worker.logs);
874            }
875            result
876                .gas_report_traces
877                .extend(worker.traces.into_iter().map(SparsedTraceArena::into_gas_report_arena));
878            HitMaps::merge_opt(&mut result.line_coverage, worker.coverage);
879            result.deprecated_cheatcodes.extend(worker.deprecated_cheatcodes);
880        }
881        // The cases are in worker order.
882        if let Some(&(gas, stipend)) = result.gas_by_case.first() {
883            result.first_case = FuzzCase { gas, stipend };
884        }
885
886        if let Some(reason) = &result.reason
887            && let Some(reason) = SkipReason::decode_self(reason)
888        {
889            result.skipped = true;
890            result.reason = reason.0;
891        }
892
893        (result, shown_case, campaign_failure)
894    }
895
896    fn write_branch_frontiers(&self, workers: &mut [WorkerState<FEN>], func: &Function) {
897        let Some(frontier_dir) = &self.config.corpus.frontier_dir else {
898            return;
899        };
900        let limit = self.config.corpus.frontier_limit;
901        if limit == 0 {
902            return;
903        }
904
905        let frontiers = frontier::merge_frontiers(
906            limit,
907            workers.iter_mut().flat_map(|worker| worker.frontiers.drain(..)),
908        );
909        if frontiers.is_empty() {
910            return;
911        }
912
913        let artifact = FuzzBranchFrontierArtifact::new(func, limit, frontiers);
914        if let Err(err) = frontier::write_frontier_artifact(frontier_dir, &artifact) {
915            warn!(%err, path = ?frontier_dir, "failed to write fuzz branch frontier artifact");
916        }
917    }
918
919    /// Runs a single fuzz worker
920    #[allow(clippy::too_many_arguments)]
921    fn run_worker(
922        &self,
923        worker_id: usize,
924        func: &Function,
925        fuzz_fixtures: &FuzzFixtures,
926        address: Address,
927        rd: &RevertDecoder,
928        shared_state: &SharedFuzzState,
929        progress: Option<&ProgressBar>,
930        final_sync: Option<&CorpusSyncCoordinator>,
931    ) -> Result<WorkerState<FEN>> {
932        // Prepare
933        let fuzz_seed = shared_state.state.fork();
934        let generator = TxGenerator::stateless(
935            fuzz_seed.clone(),
936            fuzz_fixtures.clone(),
937            address,
938            self.sender,
939            func.clone(),
940            self.config.dictionary.dictionary_weight,
941            self.config.corpus.payable_value_weight,
942        );
943        let fuzz_state = fuzz_seed.stateless_worker();
944        let generator = foundry_evm_fuzz::sequence::SequenceGenerator::stateless_with_fixtures(
945            generator,
946            fuzz_state.clone(),
947            fuzz_fixtures.clone(),
948            func.clone(),
949            &self.config.corpus,
950        )?;
951
952        let replay_target = ReplayTarget {
953            stateless: Some(StatelessReplayTarget { function: func, address }),
954            fuzzed_contracts: None,
955            dynamic: None,
956            senders: None,
957        };
958        let mut corpus = WorkerCorpus::new(
959            worker_id,
960            self.config.corpus.clone(),
961            generator,
962            self.corpus_replay_dir.as_deref(),
963            // Master worker replays the persisted corpus using the executor
964            (worker_id == 0).then_some(&self.executor_f),
965            replay_target,
966        )?;
967        let mut executor = self.executor_f.clone();
968        let frontier_limit = if self.config.corpus.capture_branch_frontiers() {
969            self.config.corpus.frontier_limit
970        } else {
971            0
972        };
973        let mut frontier_recorder = FuzzFrontierRecorder::new(frontier_limit);
974
975        let mut worker = WorkerState::new(worker_id);
976        // We want to collect at least one trace which will be displayed to user.
977        let max_traces_to_collect =
978            std::cmp::max(1, self.config.gas_report_samples / self.num_workers as u32);
979
980        let worker_runs = self.runs_per_worker(worker_id);
981        debug!(worker_runs);
982
983        let mut runner_config = self.runner.config().clone();
984        runner_config.cases = worker_runs;
985
986        let mut runner = if let Some(seed) = self.config.seed {
987            let worker_seed = worker_seed(seed, worker_id as u32);
988            trace!(target: "forge::test", ?worker_seed, "deterministic seed for worker {worker_id}");
989            let rng = TestRng::from_seed(RngAlgorithm::ChaCha, &worker_seed.to_be_bytes::<32>());
990            TestRunner::new_with_rng(runner_config, rng)
991        } else {
992            TestRunner::new(runner_config)
993        };
994
995        if let Some(target_run) = self.config.run {
996            for _ in 1..target_run {
997                if let Err(err) = corpus.new_sequence(&mut runner) {
998                    worker.failure = Some(TestCaseError::fail(format!(
999                        "failed to generate fuzzed input in worker {}: {err}",
1000                        worker.id
1001                    )));
1002                    shared_state.record_failure(worker_id, worker.runs);
1003                    return Ok(worker);
1004                }
1005            }
1006        }
1007        let mut generated_inputs = 0;
1008
1009        let mut persisted_failure =
1010            self.persisted_failure.as_ref().filter(|_| worker_id == 0 && self.config.run.is_none());
1011
1012        // Offset to stagger corpus syncs across workers; so that workers don't sync at the same
1013        // time.
1014        let sync_offset = (worker_id as u32).saturating_mul(100);
1015        let sync_threshold = SYNC_INTERVAL + sync_offset;
1016        let mut runs_since_sync = sync_threshold; // Always sync at the start.
1017        let mut last_metrics_report = Instant::now();
1018        // Continue while:
1019        // 1. Global state allows (not timed out, not at global limit, no failure ordered before the
1020        //    next run)
1021        // 2. Worker hasn't reached its specific run limit
1022        'stop: while shared_state.should_continue(worker_id, worker.runs)
1023            && worker.runs < worker_runs
1024        {
1025            // The number of runs that the worker completed before this one.
1026            let runs = worker.runs;
1027            // If counterexample recorded, replay it first, without incrementing runs.
1028            let (input, fuzz_run, is_persisted_replay) = if worker_id == 0
1029                && let Some(failure) = persisted_failure.take()
1030                && failure.calldata.get(..4).is_some_and(|selector| func.selector() == selector)
1031            {
1032                let seed = failure.fuzz.seed.or(self.config.seed);
1033                if let Some(cheats) = executor.inspector_mut().cheatcodes.as_mut()
1034                    && let Some(seed) = seed
1035                {
1036                    let run = failure.fuzz.run.unwrap_or(1);
1037                    let worker = failure.fuzz.worker.unwrap_or(worker_id as u32) as usize;
1038                    cheats.core.set_seed(Self::fuzz_run_seed(seed, worker, run));
1039                }
1040
1041                (
1042                    BasicTxDetails {
1043                        warp: None,
1044                        roll: None,
1045                        sender: self.sender,
1046                        call_details: CallDetails {
1047                            target: address,
1048                            calldata: failure.calldata.clone(),
1049                            value: failure.value,
1050                        },
1051                    },
1052                    Some(FuzzRunMetadata::new(
1053                        seed,
1054                        failure.fuzz.run,
1055                        Some(failure.fuzz.worker.unwrap_or(worker_id as u32)),
1056                    )),
1057                    true,
1058                )
1059            } else {
1060                runs_since_sync += 1;
1061                if runs_since_sync >= sync_threshold {
1062                    let timer = Instant::now();
1063                    corpus.sync(
1064                        self.num_workers,
1065                        &executor,
1066                        replay_target,
1067                        &shared_state.global_corpus_metrics,
1068                    )?;
1069                    trace!("finished corpus sync in {:?}", timer.elapsed());
1070                    runs_since_sync = 0;
1071                }
1072
1073                let fuzz_run = self.config.run.unwrap_or_else(|| {
1074                    generated_inputs += 1;
1075                    generated_inputs
1076                });
1077                if let Some(cheats) = executor.inspector_mut().cheatcodes.as_mut()
1078                    && let Some(seed) = self.config.seed
1079                {
1080                    cheats.core.set_seed(Self::fuzz_run_seed(seed, worker_id, fuzz_run));
1081                }
1082
1083                let input = match corpus.new_sequence(&mut runner) {
1084                    Ok(plan) => plan.into_first(),
1085                    Err(err) => {
1086                        worker.failure = Some(TestCaseError::fail(format!(
1087                            "failed to generate fuzzed input in worker {}: {err}",
1088                            worker.id
1089                        )));
1090                        shared_state.record_failure(worker_id, runs);
1091                        break 'stop;
1092                    }
1093                };
1094
1095                (
1096                    input,
1097                    Some(FuzzRunMetadata::new(
1098                        self.config.seed,
1099                        Some(fuzz_run),
1100                        Some(worker_id as u32),
1101                    )),
1102                    false,
1103                )
1104            };
1105
1106            let mut inc_runs = || {
1107                let total_runs = shared_state.increment_runs();
1108                debug_assert!(
1109                    shared_state.timer.is_enabled()
1110                        || total_runs
1111                            <= if self.config.run.is_some() { 1 } else { self.config.runs },
1112                    "worker runs were not distributed correctly"
1113                );
1114                worker.runs += 1;
1115                if let Some(progress) = progress {
1116                    progress.inc(1);
1117                }
1118            };
1119
1120            let case_input = input.clone();
1121            match self.single_fuzz(
1122                &mut executor,
1123                address,
1124                input,
1125                &mut corpus,
1126                &mut frontier_recorder,
1127                fuzz_run.as_ref(),
1128            ) {
1129                Ok(fuzz_outcome) => match fuzz_outcome {
1130                    FuzzOutcome::Case(case) => {
1131                        if is_persisted_replay {
1132                            continue 'stop;
1133                        }
1134                        inc_runs();
1135
1136                        if worker_id == 0 && self.config.corpus.collect_edge_coverage() {
1137                            if let Some(progress) = progress {
1138                                corpus.sync_metrics(&shared_state.global_corpus_metrics);
1139                                progress
1140                                    .set_message(format!("{}", shared_state.global_corpus_metrics));
1141                            } else if last_metrics_report.elapsed()
1142                                > DURATION_BETWEEN_METRICS_REPORT
1143                            {
1144                                corpus.sync_metrics(&shared_state.global_corpus_metrics);
1145                                // Display metrics inline.
1146                                let metrics = json!({
1147                                    "timestamp": SystemTime::now()
1148                                        .duration_since(UNIX_EPOCH)?
1149                                        .as_secs(),
1150                                    "test": func.name,
1151                                    "metrics": shared_state.global_corpus_metrics.load(),
1152                                });
1153                                let _ = sh_eprintln!("{metrics}");
1154                                last_metrics_report = Instant::now();
1155                            }
1156                        }
1157
1158                        worker.gas_by_case.push((case.case.gas, case.case.stipend));
1159
1160                        if let Some(call_traces) = case.traces {
1161                            if worker.traces.len() == max_traces_to_collect as usize {
1162                                worker.traces.pop();
1163                            }
1164                            worker.traces.push(call_traces);
1165                            worker.debug_bytecodes = case.debug_bytecodes;
1166                            worker.breakpoints = Some(case.breakpoints);
1167                            worker.last_case = Some((case_input, fuzz_run));
1168                        }
1169
1170                        // Always store logs from the last run in test_data.logs for display at
1171                        // verbosity >= 2. When show_logs is true,
1172                        // accumulate all logs. When false, only keep the last run's logs.
1173                        if self.config.show_logs {
1174                            worker.logs.extend(case.logs);
1175                        } else {
1176                            worker.logs = case.logs;
1177                        }
1178
1179                        HitMaps::merge_opt(&mut worker.coverage, case.coverage);
1180                        worker.deprecated_cheatcodes = case.deprecated_cheatcodes;
1181                    }
1182                    FuzzOutcome::CounterExample(CounterExampleOutcome {
1183                        exit_reason: status,
1184                        counterexample: mut outcome,
1185                        ..
1186                    }) => {
1187                        // Keep the lines the failing input ran, as a failing unit test does.
1188                        HitMaps::merge_opt(&mut worker.coverage, outcome.1.line_coverage.take());
1189                        if !is_persisted_replay {
1190                            inc_runs();
1191                        }
1192                        worker.failure_run = fuzz_run;
1193
1194                        // Only classify magic skip payloads minted by the skip cheatcode.
1195                        let reason = outcome
1196                            .1
1197                            .skip_reason()
1198                            .map(|reason| reason.to_string())
1199                            .or_else(|| rd.maybe_decode(&outcome.1.result, status));
1200                        if self.config.show_logs {
1201                            worker.logs.extend(outcome.1.logs.clone());
1202                        } else {
1203                            worker.logs.clone_from(&outcome.1.logs);
1204                        }
1205                        worker.counterexample = Some(outcome);
1206                        worker.failure = Some(TestCaseError::fail(reason.unwrap_or_default()));
1207                        shared_state.record_failure(worker_id, runs);
1208                        break 'stop;
1209                    }
1210                },
1211                Err(err) => match err {
1212                    TestCaseError::Fail(_) => {
1213                        worker.failure = Some(err);
1214                        shared_state.record_failure(worker_id, runs);
1215                        break 'stop;
1216                    }
1217                    TestCaseError::Reject(_) => {
1218                        // The persisted replay is not part of the campaign, so its reject does
1219                        // not count against `max_test_rejects`.
1220                        if is_persisted_replay {
1221                            continue 'stop;
1222                        }
1223                        let max = self.config.max_test_rejects;
1224
1225                        let total = shared_state.increment_rejects();
1226
1227                        // Update progress bar to reflect rejected runs.
1228                        // TODO(dani): (pre-existing) conflicts with corpus metrics `set_message`
1229                        if !self.config.corpus.collect_edge_coverage()
1230                            && let Some(progress) = progress
1231                        {
1232                            progress.set_message(format!("([{total}] rejected)"));
1233                        }
1234
1235                        if max > 0 && total > max {
1236                            worker.failure =
1237                                Some(TestCaseError::reject(FuzzError::TooManyRejects(max)));
1238                            shared_state.record_failure(worker_id, runs);
1239                            break 'stop;
1240                        }
1241                    }
1242                },
1243            }
1244        }
1245
1246        if let Some(final_sync) = final_sync {
1247            corpus.finalize_sync(&executor, replay_target, final_sync)?;
1248        }
1249
1250        if worker_id == 0 {
1251            worker.failed_corpus_replays = corpus.failed_replays;
1252        }
1253        worker.frontiers = frontier_recorder.into_frontiers();
1254
1255        // Logs stats
1256        trace!("worker {worker_id} fuzz stats");
1257        fuzz_state.log_stats();
1258
1259        Ok(worker)
1260    }
1261
1262    /// Determines the number of runs per worker.
1263    const fn runs_per_worker(&self, worker_id: usize) -> u32 {
1264        let worker_id = worker_id as u32;
1265        let total_runs = if self.config.run.is_some() { 1 } else { self.config.runs };
1266        let n = self.num_workers as u32;
1267        let runs = total_runs / n;
1268        let remainder = total_runs % n;
1269        // Distribute the remainder evenly among the first `remainder` workers,
1270        // assuming `worker_id` is in `0..n`.
1271        if worker_id < remainder { runs + 1 } else { runs }
1272    }
1273
1274    /// Returns the worker IDs to execute.
1275    fn worker_ids(&self) -> Vec<usize> {
1276        if self.config.run.is_some() {
1277            vec![self.config.worker.unwrap_or(0) as usize]
1278        } else {
1279            (0..self.num_workers).collect()
1280        }
1281    }
1282
1283    /// Derives the deterministic RNG seed for cheatcode randomness in a worker-local run.
1284    fn fuzz_run_seed(seed: U256, worker_id: usize, run: u32) -> U256 {
1285        worker_seed(seed, worker_id as u32).wrapping_add(U256::from(run.saturating_sub(1)))
1286    }
1287}