Skip to main content

foundry_evm/executors/invariant/
mod.rs

1use crate::{
2    executors::{
3        DURATION_BETWEEN_METRICS_REPORT, EarlyExit, EvmError, EvmExecutionCancellation, Executor,
4        RawCallResult,
5        campaign::{
6            CampaignCallKind, CampaignControl, CampaignEvent, CampaignSequenceOutcome,
7            FuzzCampaign, FuzzCampaignMode,
8        },
9        corpus::{
10            CorpusInsertionMode, DynamicTargetCtx, ReplayTarget, WorkerCorpus, WorkerCorpusSeed,
11            persist_campaign_optimization,
12        },
13        fuzz::{
14            FuzzBranchFrontier, FuzzFrontierRecorder, StatefulFuzzBranchFrontierArtifact,
15            merge_frontiers, write_frontier_artifact,
16        },
17        worker_seed,
18    },
19    inspectors::Fuzzer,
20};
21use alloy_dyn_abi::{DynSolValue, JsonAbiExt};
22use alloy_json_abi::{Function, StateMutability};
23use alloy_primitives::{
24    Address, B256, Bytes, FixedBytes, I256, Selector, U256,
25    map::{AddressSet, HashMap},
26};
27use alloy_sol_types::{SolCall, sol};
28use campaign::{
29    InvariantCampaignAggregator, InvariantCampaignSpec, InvariantCampaignState,
30    InvariantWorkerOutput, InvariantWorkerPlan,
31};
32use evm2::evm::PendingState;
33use eyre::{ContextCompat, Result, eyre};
34use foundry_common::{
35    TestFunctionExt,
36    contracts::{ContractsByAddress, ContractsByArtifact},
37    sh_eprintln,
38};
39use foundry_config::{FuzzCorpusConfig, InvariantConfig, InvariantDepthMode, InvariantWorkers};
40use foundry_evm_core::{
41    constants::{
42        CALLER, CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, HARDHAT_CONSOLE_ADDRESS, MAGIC_ASSUME,
43    },
44    evm::FoundryEvmNetwork,
45    precompiles::PRECOMPILES,
46};
47use foundry_evm_coverage::HitMaps;
48use foundry_evm_fuzz::{
49    BasicTxDetails, FuzzCase, FuzzFixtures, ObservedCall,
50    invariant::{
51        ArtifactFilters, FuzzRunIdentifiedContracts, InvariantContract, RandomCallGenerator,
52        SenderFilters, TargetedContract, TargetedContracts,
53    },
54    strategies::{EvmFuzzState, FuzzState, TxGenerator, override_call_strat},
55};
56use foundry_evm_traces::{CallTraceArena, SparsedTraceArena};
57use indicatif::ProgressBar;
58use parking_lot::RwLock;
59use proptest::{
60    prelude::Rng,
61    test_runner::{RngAlgorithm, TestRng, TestRunner},
62};
63use rayon::iter::{IntoParallelIterator, ParallelIterator};
64use result::{assert_after_invariant, can_continue, invariant_preflight_check};
65use serde::{Deserialize, Serialize};
66use serde_json::{Value, json};
67use snapshot::StateSnapshots;
68use std::{
69    collections::{HashMap as Map, HashSet, btree_map::Entry},
70    sync::Arc,
71    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
72};
73
74mod error;
75pub(crate) use error::snapshot_edge_fingerprint;
76pub use error::{
77    FailureKey, HandlerAssertionFailure, InvariantFailures, InvariantFuzzError,
78    handler_edge_fingerprint, handler_site_already_minimal,
79};
80mod campaign;
81
82mod replay;
83pub use replay::{ReplayErrorResult, replay_error, replay_run};
84
85mod result;
86pub use result::{InvariantFuzzTestResult, did_fail_on_assert};
87
88mod shrink;
89pub use shrink::{
90    CandidateReplay, CheckSequenceFailureSite, CheckSequenceOptions, CheckSequenceOutcome,
91    HandlerReplayOutcome, SequenceShrink, ShrinkCandidateKeys, ShrinkRun, ShrinkRunStats,
92    check_sequence, check_sequence_value, deadline_passed, replay_handler_failure_sequence,
93    reset_shrink_progress, shrink_sequence_by_removing,
94};
95
96mod snapshot;
97
98mod live;
99pub use live::{LiveInvariantSolution, LiveInvariantSolver, LiveInvariantStats};
100
101/// Minimum number of logical runs assigned to each auto invariant worker at the default invariant
102/// depth.
103///
104/// Keeps short campaigns single-threaded and avoids producing many small rayon jobs.
105const MIN_RUNS_PER_INVARIANT_WORKER: u32 = 10_000;
106/// Baseline depth used to preserve the previous default-depth worker heuristic.
107const DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP: u32 = 500;
108/// Minimum estimated handler calls assigned to each auto invariant worker.
109const MIN_ESTIMATED_CALLS_PER_INVARIANT_WORKER: u64 =
110    MIN_RUNS_PER_INVARIANT_WORKER as u64 * DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP as u64;
111sol! {
112    interface IInvariantTest {
113        #[derive(Default)]
114        struct FuzzSelector {
115            address addr;
116            bytes4[] selectors;
117        }
118
119        #[derive(Default)]
120        struct FuzzArtifactSelector {
121            string artifact;
122            bytes4[] selectors;
123        }
124
125        #[derive(Default)]
126        struct FuzzInterface {
127            address addr;
128            string[] artifacts;
129        }
130
131        function afterInvariant() external;
132
133        #[derive(Default)]
134        function excludeArtifacts() public view returns (string[] memory excludedArtifacts);
135
136        #[derive(Default)]
137        function excludeContracts() public view returns (address[] memory excludedContracts);
138
139        #[derive(Default)]
140        function excludeSelectors() public view returns (FuzzSelector[] memory excludedSelectors);
141
142        #[derive(Default)]
143        function excludeSenders() public view returns (address[] memory excludedSenders);
144
145        #[derive(Default)]
146        function targetArtifacts() public view returns (string[] memory targetedArtifacts);
147
148        #[derive(Default)]
149        function targetArtifactSelectors() public view returns (FuzzArtifactSelector[] memory targetedArtifactSelectors);
150
151        #[derive(Default)]
152        function targetContracts() public view returns (address[] memory targetedContracts);
153
154        #[derive(Default)]
155        function targetSelectors() public view returns (FuzzSelector[] memory targetedSelectors);
156
157        #[derive(Default)]
158        function targetSenders() public view returns (address[] memory targetedSenders);
159
160        #[derive(Default)]
161        function targetInterfaces() public view returns (FuzzInterface[] memory targetedInterfaces);
162    }
163}
164
165/// Contains invariant metrics for a single fuzzed selector.
166#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
167pub struct InvariantMetrics {
168    // Count of fuzzed selector calls.
169    pub calls: usize,
170    // Count of fuzzed selector reverts.
171    pub reverts: usize,
172    // Count of fuzzed selector discards (through assume cheatcodes).
173    pub discards: usize,
174}
175
176impl InvariantMetrics {
177    const fn record_call(&mut self, reverted: bool, discarded: bool) {
178        self.calls += 1;
179        if discarded {
180            self.discards += 1;
181        } else if reverted {
182            self.reverts += 1;
183        }
184    }
185}
186
187/// Campaign-level throughput metrics for invariant progress reporting.
188#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
189struct InvariantThroughputMetrics {
190    total_txs: u64,
191    total_gas: u64,
192}
193
194impl InvariantThroughputMetrics {
195    fn tps(self, elapsed: Duration) -> f64 {
196        round_rate_for_progress(rate_per_sec(self.total_txs as f64, elapsed))
197    }
198
199    fn gps(self, elapsed: Duration) -> f64 {
200        round_rate_for_progress(rate_per_sec(self.total_gas as f64, elapsed))
201    }
202}
203
204fn max_invariant_workers_for_campaign(runs: u32, depth: u32) -> usize {
205    let estimated_calls = u64::from(runs) * u64::from(depth.max(1));
206    usize::try_from((estimated_calls / MIN_ESTIMATED_CALLS_PER_INVARIANT_WORKER).max(1))
207        .unwrap_or(usize::MAX)
208}
209
210fn invariant_run_depth(config: &InvariantConfig, runner: &mut TestRunner) -> u32 {
211    match config.depth_mode {
212        InvariantDepthMode::Fixed => config.depth,
213        InvariantDepthMode::Random => {
214            let min_depth = config.min_depth.max(1);
215            if config.depth <= min_depth {
216                config.depth.max(1)
217            } else {
218                runner.rng().random_range(min_depth..=config.depth)
219            }
220        }
221    }
222}
223
224fn auto_invariant_worker_count(
225    available_threads: usize,
226    invariant_campaign_anchors: usize,
227) -> usize {
228    (available_threads.max(1) / invariant_campaign_anchors.max(1)).max(1)
229}
230
231fn invariant_worker_count_with_threads(
232    config: &InvariantConfig,
233    available_threads: usize,
234    invariant_campaign_anchors: usize,
235) -> usize {
236    match config.workers {
237        InvariantWorkers::Fixed(workers) => workers.get(),
238        InvariantWorkers::Auto => {
239            let requested =
240                auto_invariant_worker_count(available_threads, invariant_campaign_anchors);
241            if config.timeout.is_some() {
242                requested
243            } else {
244                requested.min(max_invariant_workers_for_campaign(config.runs, config.depth))
245            }
246        }
247    }
248}
249
250const fn invariant_worker_config(
251    mut config: InvariantConfig,
252    worker_id: u32,
253    worker_count: usize,
254) -> InvariantConfig {
255    // Keep one- and two-worker campaigns on the stable default, but let one extra worker explore
256    // the broader fresh-input setting once the user has enough workers to keep the exploratory
257    // share below half of the campaign. The last worker does not receive remainder runs from
258    // campaign sharding, so this keeps exposure bounded to one worker shard.
259    let exploratory_worker_id = worker_count.saturating_sub(1) as u32;
260    if worker_count > 2
261        && worker_id == exploratory_worker_id
262        && !config.corpus_random_sequence_weight_configured
263        && config.corpus.corpus_random_sequence_weight
264            == FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
265    {
266        config.corpus.corpus_random_sequence_weight =
267            FuzzCorpusConfig::ENSEMBLE_CORPUS_RANDOM_SEQUENCE_WEIGHT;
268    }
269    config
270}
271
272fn gas_report_samples_for_worker(total_samples: u32, worker_id: u32, worker_count: usize) -> usize {
273    let total_samples = total_samples as usize;
274    let worker_count = worker_count.max(1);
275    total_samples / worker_count + usize::from((worker_id as usize) < total_samples % worker_count)
276}
277
278fn invariant_worker_collects_evm_cmp_log(
279    config: &InvariantConfig,
280    worker_id: u32,
281    worker_count: usize,
282) -> bool {
283    config.corpus.collect_evm_cmp_log() && (worker_count <= 1 || worker_id == 0)
284}
285
286fn campaign_seed_and_corpus_seed_for_worker(
287    campaign_seed: &InvariantCampaignSeed,
288    corpus_seed: &WorkerCorpusSeed,
289    plan: InvariantWorkerPlan,
290    worker_count: usize,
291    include_cmp_seq: bool,
292) -> (InvariantCampaignSeed, WorkerCorpusSeed) {
293    let worker_corpus_seed =
294        corpus_seed.clone_for_worker(plan.worker_id as usize, worker_count, include_cmp_seq);
295    (campaign_seed.clone(), worker_corpus_seed)
296}
297
298fn should_continue_invariant_worker(
299    campaign_state: &InvariantCampaignState,
300    runs: u32,
301    plan: InvariantWorkerPlan,
302) -> bool {
303    if campaign_state.should_stop() {
304        return false;
305    }
306
307    campaign_state.is_timed_campaign() || runs < plan.runs
308}
309
310fn invariant_worker_runner(
311    runner: &mut TestRunner,
312    worker_id: u32,
313    seed: Option<U256>,
314) -> TestRunner {
315    if let Some(seed) = seed {
316        let worker_seed = worker_seed(seed, worker_id);
317        trace!(target: "forge::test", ?worker_seed, "deterministic seed for invariant worker {worker_id}");
318        let rng = TestRng::from_seed(RngAlgorithm::ChaCha, &worker_seed.to_be_bytes::<32>());
319        TestRunner::new_with_rng(runner.config().clone(), rng)
320    } else if worker_id == 0 {
321        runner.clone()
322    } else {
323        TestRunner::new_with_rng(runner.config().clone(), runner.new_rng())
324    }
325}
326
327/// Converts a cumulative campaign total into an average per-second rate.
328///
329/// Returns `0.0` during the initial zero-elapsed startup window to avoid
330/// dividing by zero while progress reporting is warming up.
331fn rate_per_sec(total: f64, elapsed: Duration) -> f64 {
332    let elapsed_secs = elapsed.as_secs_f64();
333    if elapsed_secs > 0.0 { total / elapsed_secs } else { 0.0 }
334}
335
336fn round_rate_for_progress(rate: f64) -> f64 {
337    (rate * 100.0).round() / 100.0
338}
339
340/// Tracks invariant failure counts during a campaign.
341#[derive(Clone, Debug, Default)]
342struct InvariantFailureMetrics {
343    failures: u64,
344    unique_failures: HashSet<String>,
345    /// Unique handler-side assertion bugs found so far.
346    broken_handlers: usize,
347}
348
349impl InvariantFailureMetrics {
350    /// Records a failure and emits a structured JSON `"failure"` event.
351    fn record_failure(&mut self, invariant_name: &str, target: &str, reason: &str) {
352        self.failures += 1;
353        self.unique_failures.insert(invariant_name.to_string());
354
355        let timestamp =
356            SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
357        let event = json!({
358            "timestamp": timestamp,
359            "event": "failure",
360            "invariant": invariant_name,
361            "target": target,
362            "reason": reason,
363        });
364        let _ = sh_eprintln!("{}", serde_json::to_string(&event).unwrap_or_default());
365    }
366
367    /// Records a handler assertion and emits a structured JSON `"failure"` event.
368    fn record_handler_failure(&mut self, target: Address, selector: Selector, reason: &str) {
369        self.broken_handlers += 1;
370
371        let timestamp =
372            SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
373        let event = build_handler_failure_event(timestamp, target, selector, reason);
374        let _ = sh_eprintln!("{}", serde_json::to_string(&event).unwrap_or_default());
375    }
376}
377
378fn build_handler_failure_event(
379    timestamp_secs: u64,
380    target: Address,
381    selector: Selector,
382    reason: &str,
383) -> Value {
384    json!({
385        "timestamp": timestamp_secs,
386        "event": "failure",
387        "failure_type": "handler_assertion",
388        "target": target,
389        "selector": selector,
390        "reason": reason,
391    })
392}
393
394/// Bridges newly-recorded invariant breaks from `failures.errors` into the pulse
395/// `failure_metrics` so the live progress stream reflects breaks as they happen.
396/// Iterates in declaration order so the emitted "failure" events are deterministic.
397fn record_new_invariant_failures(
398    campaign_state: &InvariantCampaignState,
399    invariant_contract: &InvariantContract<'_>,
400    failures: &InvariantFailures,
401) {
402    for (f, _) in &invariant_contract.invariant_fns {
403        if let Some(failure) = failures.get_failure(f) {
404            let reason = failure.revert_reason().unwrap_or_default();
405            campaign_state.record_invariant_failure(&f.name, invariant_contract.name, &reason);
406        }
407    }
408}
409
410struct InvariantProgressContext<'a> {
411    timestamp_secs: u64,
412    contract_name: &'a str,
413    optimization_best: Option<I256>,
414    throughput: InvariantThroughputMetrics,
415    elapsed: Duration,
416    worker_id: u32,
417    worker_count: usize,
418    /// Time since this worker last saw a new edge, or `None` if it has not seen one yet.
419    time_since_new_edge: Option<Duration>,
420}
421
422/// Builds the machine-readable invariant progress payload emitted during a
423/// campaign.
424///
425/// This keeps the existing corpus progress metrics together with cumulative and
426/// derived throughput fields so downstream benchmark tooling can consume a
427/// single JSON event shape.
428fn build_invariant_progress_json<M: Serialize>(
429    context: InvariantProgressContext<'_>,
430    corpus_metrics: &M,
431    failure_metrics: &InvariantFailureMetrics,
432) -> serde_json::Value {
433    let mut metrics = serde_json::to_value(corpus_metrics).unwrap_or_default();
434    if let Some(obj) = metrics.as_object_mut() {
435        obj.insert("broken_invariants".to_string(), json!(failure_metrics.unique_failures.len()));
436        obj.insert("broken_assertions".to_string(), json!(failure_metrics.broken_handlers));
437    }
438
439    let mut payload = json!({
440        "timestamp": context.timestamp_secs,
441        "event": "pulse",
442        "contract": context.contract_name,
443        "metrics": metrics,
444        "total_txs": context.throughput.total_txs,
445        "total_gas": context.throughput.total_gas,
446        "tps": context.throughput.tps(context.elapsed),
447        "gps": context.throughput.gps(context.elapsed),
448        "worker": {
449            "id": context.worker_id,
450            "count": context.worker_count,
451            // `null` until this worker sees its first edge.
452            "secs_since_new_edge": context
453                .time_since_new_edge
454                .map(|d| d.as_secs_f64()),
455        },
456    });
457
458    if let Some(best) = context.optimization_best {
459        payload["optimization_best"] = json!(best.to_string());
460    }
461
462    payload
463}
464
465/// Contains data collected during invariant test runs.
466struct InvariantTestData {
467    // Number of completed invariant runs.
468    runs: usize,
469    // Number of completed fuzzed calls across all invariant runs.
470    calls: usize,
471    // Data related to reverts or failed assertions of the test.
472    failures: InvariantFailures,
473    // Calldata in the last invariant run.
474    last_run_inputs: Vec<BasicTxDetails>,
475    // Additional traces for gas report.
476    gas_report_traces: Vec<Vec<CallTraceArena>>,
477    // Line coverage information collected from all fuzzed calls.
478    line_coverage: Option<HitMaps>,
479    // Metrics for each fuzzed selector.
480    metrics: HashMap<String, InvariantMetrics>,
481    // Cache from fuzzed (target, selector) to its metric key. Only resolved keys are cached and
482    // they are invalidated when targets change (see `invalidate_metric_key_cache`).
483    metric_key_cache: HashMap<(Address, Selector), String>,
484
485    // Proptest runner to query for random values.
486    // The strategy only comes with the first `input`. We fill the rest of the `inputs`
487    // until the desired `depth` so we can use the evolving fuzz dictionary
488    // during the run.
489    branch_runner: TestRunner,
490
491    // Optimization mode state: tracks the best (maximum) value and the sequence that produced it.
492    // Only used when invariant function returns int256.
493    optimization_best_value: Option<I256>,
494    optimization_best_sequence: Vec<BasicTxDetails>,
495}
496
497/// Contains invariant test data.
498struct InvariantTest {
499    // Fuzz state of invariant test.
500    fuzz_state: FuzzState,
501    // Contracts fuzzed by the invariant test.
502    targeted_contracts: FuzzRunIdentifiedContracts,
503    // Data collected during invariant runs.
504    test_data: InvariantTestData,
505}
506
507impl InvariantTest {
508    /// Instantiates an invariant test.
509    fn new(
510        fuzz_state: FuzzState,
511        targeted_contracts: FuzzRunIdentifiedContracts,
512        failures: InvariantFailures,
513        branch_runner: TestRunner,
514    ) -> Self {
515        let test_data = InvariantTestData {
516            runs: 0,
517            calls: 0,
518            failures,
519            last_run_inputs: vec![],
520            gas_report_traces: vec![],
521            line_coverage: None,
522            metrics: HashMap::default(),
523            metric_key_cache: HashMap::default(),
524            branch_runner,
525            optimization_best_value: None,
526            optimization_best_sequence: vec![],
527        };
528        Self { fuzz_state, targeted_contracts, test_data }
529    }
530
531    /// Returns number of invariant test reverts.
532    const fn reverts(&self) -> usize {
533        self.test_data.failures.reverts
534    }
535
536    /// Set invariant test error.
537    fn set_error(&mut self, invariant: &Function, error: InvariantFuzzError) {
538        self.test_data.failures.record_failure(invariant, error);
539    }
540
541    /// Set last invariant run call sequence.
542    fn set_last_run_inputs(&mut self, inputs: Vec<BasicTxDetails>) {
543        self.test_data.last_run_inputs = inputs;
544    }
545
546    /// Merge current collected line coverage with the new coverage from last fuzzed call.
547    fn merge_line_coverage(&mut self, new_coverage: Option<HitMaps>) {
548        HitMaps::merge_opt(&mut self.test_data.line_coverage, new_coverage);
549    }
550
551    /// Update metrics for a fuzzed selector, extracted from tx details.
552    /// Always increments number of calls; discarded runs (through assume cheatcodes) are tracked
553    /// separated from reverts.
554    fn record_metrics(&mut self, tx_details: &BasicTxDetails, reverted: bool, discarded: bool) {
555        let Some(selector) = tx_details.call_details.calldata.get(..4).map(Selector::from_slice)
556        else {
557            return;
558        };
559        let cache_key = (tx_details.call_details.target, selector);
560
561        if let Some(metric_key) = self.test_data.metric_key_cache.get(&cache_key) {
562            if let Some(invariant_metrics) = self.test_data.metrics.get_mut(metric_key) {
563                invariant_metrics.record_call(reverted, discarded);
564            } else {
565                self.test_data
566                    .metrics
567                    .entry(metric_key.to_owned())
568                    .or_default()
569                    .record_call(reverted, discarded);
570            }
571            return;
572        }
573
574        // Not cached: resolve from the current target set. Unresolved keys aren't cached so a tx
575        // whose target isn't known yet is re-resolved once that target is added.
576        let Some(metric_key) = self
577            .targeted_contracts
578            .targets()
579            .fuzzed_metric_key_for_selector(tx_details.call_details.target, selector)
580        else {
581            return;
582        };
583        self.test_data.metric_key_cache.insert(cache_key, metric_key.clone());
584        self.test_data.metrics.entry(metric_key).or_default().record_call(reverted, discarded);
585    }
586
587    /// Drops cached metric keys for the given addresses, keeping the cache coherent when targets
588    /// are added or removed (an address can be reused for a different artifact across runs).
589    fn invalidate_metric_key_cache(&mut self, addresses: &[Address]) {
590        if addresses.is_empty() {
591            return;
592        }
593        self.test_data.metric_key_cache.retain(|(addr, _), _| !addresses.contains(addr));
594    }
595
596    /// End invariant test run by collecting results, cleaning collected artifacts and reverting
597    /// created fuzz state.
598    fn end_run<FEN: FoundryEvmNetwork>(&mut self, run: InvariantTestRun<FEN>, gas_samples: usize) {
599        // Clear contracts created during this run, dropping their cached metric keys so a reused
600        // address can't resolve to a stale contract in a later run.
601        self.invalidate_metric_key_cache(&run.created_contracts);
602        self.targeted_contracts.clear_created_contracts(run.created_contracts);
603
604        if self.test_data.gas_report_traces.len() < gas_samples {
605            self.test_data.gas_report_traces.push(
606                run.run_traces.into_iter().map(SparsedTraceArena::into_gas_report_arena).collect(),
607            );
608        }
609        self.test_data.runs += 1;
610        self.test_data.calls += run.fuzz_runs.len();
611
612        // Revert state to not persist values between runs.
613        self.fuzz_state.revert();
614    }
615
616    /// Updates the optimization state if the new value is better (higher) than the current best.
617    fn update_optimization_value(&mut self, value: I256, sequence: &[BasicTxDetails]) {
618        if self.test_data.optimization_best_value.is_none_or(|best| value > best) {
619            self.test_data.optimization_best_value = Some(value);
620            self.test_data.optimization_best_sequence = sequence.to_vec();
621        }
622    }
623}
624
625/// Contains data for an invariant test run.
626struct InvariantTestRun<FEN: FoundryEvmNetwork> {
627    // Invariant run call sequence.
628    inputs: Vec<BasicTxDetails>,
629    // Per-call EVM comparison operands (parallel to `inputs`), captured for I2S corpus mutation.
630    cmp_seq: Vec<Vec<crate::inspectors::CmpOperands>>,
631    // Current invariant run executor.
632    executor: Executor<FEN>,
633    // Invariant run stat reports (eg. gas usage).
634    fuzz_runs: Vec<FuzzCase>,
635    // Contracts created during current invariant run.
636    created_contracts: Vec<Address>,
637    // Traces of each call of the invariant run call sequence.
638    run_traces: Vec<SparsedTraceArena>,
639    // Current depth of invariant run.
640    depth: u32,
641    // Current assume rejects of the invariant run.
642    rejects: u32,
643    // Whether new coverage was discovered during this run.
644    new_coverage: bool,
645    // Line coverage staged until the run is accepted.
646    line_coverage: Option<HitMaps>,
647    // Whether this run's inputs should become the reported last run.
648    save_last_run_inputs: bool,
649    // For optimization mode: the best value found during this run (if any).
650    optimization_value: Option<I256>,
651    // For optimization mode: the length of the input prefix that produced the best value.
652    optimization_prefix_len: usize,
653}
654
655/// Recorded call sequence used by corpus feedback and frontier recording.
656struct RecordedCallSequence {
657    inputs: Vec<BasicTxDetails>,
658    cmp_seq: Vec<Vec<crate::inspectors::CmpOperands>>,
659}
660
661/// Immutable state selected once for a logical invariant campaign and cloned into each worker.
662#[derive(Clone)]
663struct InvariantCampaignSeed {
664    artifact_filters: ArtifactFilters,
665    sender_filters: SenderFilters,
666    targeted_contracts: TargetedContracts,
667    targets_are_updatable: bool,
668    initial_handler_failures: Map<(Address, Selector), InvariantFuzzError>,
669}
670
671impl<FEN: FoundryEvmNetwork> InvariantTestRun<FEN> {
672    /// Instantiates an invariant test run.
673    ///
674    /// A run resumed from a snapshot starts with the calls that reached it as its inputs.
675    fn new(
676        prefix: &[BasicTxDetails],
677        first_input: BasicTxDetails,
678        executor: Executor<FEN>,
679        depth: usize,
680    ) -> Self {
681        let mut inputs = Vec::with_capacity(prefix.len() + depth.saturating_add(1));
682        inputs.extend_from_slice(prefix);
683        inputs.push(first_input);
684        let mut cmp_seq = Vec::with_capacity(prefix.len() + depth);
685        cmp_seq.resize_with(prefix.len(), Vec::new);
686        Self {
687            inputs,
688            cmp_seq,
689            executor,
690            fuzz_runs: Vec::with_capacity(depth),
691            created_contracts: vec![],
692            run_traces: vec![],
693            depth: 0,
694            rejects: 0,
695            new_coverage: false,
696            line_coverage: None,
697            save_last_run_inputs: false,
698            optimization_value: None,
699            optimization_prefix_len: 0,
700        }
701    }
702
703    /// Releases per-run corpus payloads once the worker corpus manager has consumed them.
704    ///
705    /// Successful runs only need `fuzz_runs`, traces, and created-contract bookkeeping for final
706    /// reporting. Counterexample inputs are copied into `InvariantTestData::last_run_inputs`
707    /// before this point, so retaining the full per-run input/cmp buffers until `end_run` only
708    /// extends peak memory in long invariant campaigns.
709    fn drop_corpus_payloads(&mut self) {
710        self.inputs.clear();
711        self.inputs.shrink_to_fit();
712        self.cmp_seq.clear();
713        self.cmp_seq.shrink_to_fit();
714    }
715}
716
717/// Wrapper around any [`Executor`] implementer which provides fuzzing support using [`proptest`].
718///
719/// After instantiation, calling `invariant_fuzz` will proceed to hammer the deployed smart
720/// contracts with inputs, until it finds a counterexample sequence. The provided [`TestRunner`]
721/// contains all the configuration which can be overridden via [environment
722/// variables](proptest::test_runner::Config)
723pub struct InvariantExecutor<'a, FEN: FoundryEvmNetwork> {
724    pub executor: Executor<FEN>,
725    /// Proptest runner.
726    runner: TestRunner,
727    /// Configured fuzz seed used to derive deterministic invariant worker runners.
728    fuzz_seed: Option<U256>,
729    /// The invariant configuration
730    config: InvariantConfig,
731    /// Contracts deployed with `setUp()`
732    setup_contracts: &'a ContractsByAddress,
733    /// Contracts that are part of the project but have not been deployed yet. We need the bytecode
734    /// to identify them from the stateset changes.
735    project_contracts: &'a ContractsByArtifact,
736    /// Filters contracts to be fuzzed through their artifact identifiers.
737    artifact_filters: ArtifactFilters,
738    /// Number of matching invariant campaign anchors in the current test pass.
739    invariant_campaign_anchors: usize,
740    live_solver: Option<LiveInvariantSolver>,
741}
742
743impl<'a, FEN: FoundryEvmNetwork> InvariantExecutor<'a, FEN> {
744    /// Instantiates an invariant executor with the configured fuzz seed for deterministic worker
745    /// runner derivation.
746    pub fn new_with_fuzz_seed(
747        executor: Executor<FEN>,
748        runner: TestRunner,
749        fuzz_seed: Option<U256>,
750        config: InvariantConfig,
751        setup_contracts: &'a ContractsByAddress,
752        project_contracts: &'a ContractsByArtifact,
753        invariant_campaign_anchors: usize,
754    ) -> Self {
755        Self {
756            executor,
757            runner,
758            fuzz_seed,
759            config,
760            setup_contracts,
761            project_contracts,
762            artifact_filters: ArtifactFilters::default(),
763            invariant_campaign_anchors,
764            live_solver: None,
765        }
766    }
767
768    /// Attaches one bounded solver worker to this campaign.
769    pub fn set_live_solver(&mut self, solver: LiveInvariantSolver) {
770        self.live_solver = Some(solver);
771    }
772
773    pub fn config(&self) -> InvariantConfig {
774        self.config.clone()
775    }
776
777    /// Retains corpus replay and result aggregation without starting fresh invariant runs.
778    pub const fn skip_fresh_runs(&mut self) {
779        self.config.runs = 0;
780        self.config.timeout = None;
781    }
782
783    /// Refs for tracking contracts deployed mid-sequence during corpus replay.
784    pub const fn dynamic_target_ctx(&self) -> DynamicTargetCtx<'_> {
785        DynamicTargetCtx {
786            project_contracts: self.project_contracts,
787            setup_contracts: self.setup_contracts,
788            artifact_filters: &self.artifact_filters,
789        }
790    }
791
792    /// Fuzzes any deployed contract and checks any broken invariant at `invariant_address`.
793    ///
794    /// `initial_handler_failures` pre-seeds the campaign's `broken_handlers` map with bugs
795    /// recovered from disk by the runner's persisted-failure replay step, so the live
796    /// progress bar and JSON pulse stream surface them from the first emission instead of
797    /// jumping at the final report. `sender_filters` and `targeted_contracts` are the selection
798    /// from [`Self::select_contracts_and_senders`], made before the executor's gas limit was
799    /// lowered to `call_gas_limit`.
800    #[allow(clippy::too_many_arguments)]
801    pub fn invariant_fuzz(
802        &mut self,
803        invariant_contract: InvariantContract<'_>,
804        sender_filters: SenderFilters,
805        targeted_contracts: &FuzzRunIdentifiedContracts,
806        fuzz_fixtures: &FuzzFixtures,
807        fuzz_state: EvmFuzzState,
808        progress: Option<&ProgressBar>,
809        early_exit: &EarlyExit,
810        initial_handler_failures: std::collections::HashMap<
811            (Address, Selector),
812            InvariantFuzzError,
813        >,
814    ) -> Result<InvariantFuzzTestResult> {
815        let campaign_spec = InvariantCampaignSpec::new(self.config.runs);
816        let worker_plans = campaign_spec.worker_plans(invariant_worker_count_with_threads(
817            &self.config,
818            rayon::current_num_threads(),
819            self.invariant_campaign_anchors,
820        ))?;
821        let actual_worker_count = worker_plans.len();
822        let campaign_seed = InvariantCampaignSeed {
823            artifact_filters: self.artifact_filters.clone(),
824            sender_filters,
825            targeted_contracts: targeted_contracts.targets().clone(),
826            targets_are_updatable: targeted_contracts.is_updatable,
827            initial_handler_failures,
828        };
829        let replay_targets = FuzzRunIdentifiedContracts::new(
830            campaign_seed.targeted_contracts.clone(),
831            campaign_seed.targets_are_updatable,
832        );
833        let mut corpus_replay_executor = self.executor.clone();
834        corpus_replay_executor.inspector_mut().collect_evm_cmp_log(
835            invariant_worker_collects_evm_cmp_log(&self.config, 0, actual_worker_count),
836        );
837        let dynamic = self.dynamic_target_ctx();
838        let mut corpus_seed = WorkerCorpusSeed::load_from_disk(
839            &self.config.corpus,
840            None,
841            Some(&corpus_replay_executor),
842            ReplayTarget {
843                stateless: None,
844                fuzzed_contracts: Some(&replay_targets),
845                dynamic: Some(&dynamic),
846                senders: Some(&campaign_seed.sender_filters),
847            },
848        )?;
849        if invariant_contract.is_optimization()
850            && let Some(best_value) = corpus_seed.optimization_best_value
851        {
852            let sequence = (0..corpus_seed.optimization_best_sequence.len()).collect::<Vec<_>>();
853            let replayed = check_sequence_value(
854                self.executor.clone(),
855                &corpus_seed.optimization_best_sequence,
856                &sequence,
857                invariant_contract.address,
858                invariant_contract.anchor_calldata(),
859                self.config.fail_on_revert,
860                &campaign_seed.targeted_contracts.keys().copied().collect::<Vec<_>>(),
861            );
862            if !matches!(replayed, Ok(Some(value)) if value == best_value) {
863                // Keep the sequence in the mutation corpus, but do not report its stale value.
864                corpus_seed.optimization_best_value = None;
865                corpus_seed.optimization_best_sequence.clear();
866            }
867        }
868        let mut runner = self.runner.clone();
869        let config = self.config.clone();
870        let setup_contracts = self.setup_contracts;
871        let project_contracts = self.project_contracts;
872        let base_executor = self.executor.clone();
873        let mut campaign_state =
874            InvariantCampaignState::new(early_exit.clone(), self.config.timeout);
875        campaign_state.live_solver = self.live_solver.take().map(std::sync::Mutex::new);
876        let campaign_state = Arc::new(campaign_state);
877
878        let frontier_test = self
879            .config
880            .corpus
881            .capture_branch_frontiers()
882            .then(|| invariant_contract.anchor().clone());
883        let mut worker_outputs = if actual_worker_count > 1 {
884            let worker_jobs = worker_plans
885                .into_iter()
886                .map(|worker_plan| {
887                    let worker_runner =
888                        invariant_worker_runner(&mut runner, worker_plan.worker_id, self.fuzz_seed);
889                    let gas_report_samples = gas_report_samples_for_worker(
890                        config.gas_report_samples,
891                        worker_plan.worker_id,
892                        actual_worker_count,
893                    );
894                    let collect_cmp_log = invariant_worker_collects_evm_cmp_log(
895                        &config,
896                        worker_plan.worker_id,
897                        actual_worker_count,
898                    );
899                    (worker_plan, worker_runner, gas_report_samples, collect_cmp_log)
900                })
901                .collect::<Vec<_>>();
902            worker_jobs
903                .into_par_iter()
904                .map(|(worker_plan, worker_runner, gas_report_samples, collect_cmp_log)| {
905                    let _guard =
906                        info_span!("invariant_worker", id = worker_plan.worker_id).entered();
907                    let timer = Instant::now();
908                    let (worker_campaign_seed, worker_corpus_seed) =
909                        campaign_seed_and_corpus_seed_for_worker(
910                            &campaign_seed,
911                            &corpus_seed,
912                            worker_plan,
913                            actual_worker_count,
914                            collect_cmp_log,
915                        );
916                    let output = Self::run_invariant_worker(
917                        base_executor.clone(),
918                        worker_runner,
919                        config.clone(),
920                        setup_contracts,
921                        project_contracts,
922                        worker_plan,
923                        invariant_contract.clone(),
924                        fuzz_fixtures,
925                        fuzz_state.fork(),
926                        progress,
927                        &campaign_state,
928                        worker_campaign_seed,
929                        worker_corpus_seed,
930                        actual_worker_count,
931                        gas_report_samples,
932                    );
933                    if output.is_err() {
934                        campaign_state.request_terminal_stop();
935                    }
936                    debug!("finished in {:?}", timer.elapsed());
937                    output
938                })
939                .collect::<Result<Vec<_>>>()?
940        } else {
941            let worker_plan = worker_plans[0];
942            let runner =
943                invariant_worker_runner(&mut runner, worker_plan.worker_id, self.fuzz_seed);
944            let gas_report_samples = config.gas_report_samples as usize;
945            let collect_cmp_log = invariant_worker_collects_evm_cmp_log(
946                &config,
947                worker_plan.worker_id,
948                actual_worker_count,
949            );
950            let (worker_campaign_seed, worker_corpus_seed) =
951                campaign_seed_and_corpus_seed_for_worker(
952                    &campaign_seed,
953                    &corpus_seed,
954                    worker_plan,
955                    actual_worker_count,
956                    collect_cmp_log,
957                );
958            vec![Self::run_invariant_worker(
959                base_executor,
960                runner,
961                config,
962                setup_contracts,
963                project_contracts,
964                worker_plan,
965                invariant_contract,
966                fuzz_fixtures,
967                fuzz_state,
968                progress,
969                &campaign_state,
970                worker_campaign_seed,
971                worker_corpus_seed,
972                actual_worker_count,
973                gas_report_samples,
974            )?]
975        };
976
977        let frontier_limit = self.config.corpus.frontier_limit;
978        if let (Some(frontier_dir), Some(frontier_test)) =
979            (&self.config.corpus.frontier_dir, frontier_test.as_ref())
980        {
981            let frontiers = merge_frontiers(
982                frontier_limit,
983                worker_outputs.iter_mut().flat_map(|(_, frontiers)| frontiers.drain(..)),
984            );
985            if !frontiers.is_empty() {
986                let artifact = StatefulFuzzBranchFrontierArtifact::new(
987                    frontier_test,
988                    frontier_limit,
989                    frontiers,
990                );
991                if let Err(err) = write_frontier_artifact(frontier_dir, &artifact) {
992                    warn!(%err, path = ?frontier_dir, "failed to write fuzz branch frontier artifact");
993                }
994            }
995        }
996
997        let mut aggregator = InvariantCampaignAggregator::new(campaign_spec);
998        for (worker_output, _) in worker_outputs {
999            aggregator.push(worker_output);
1000        }
1001        let mut result = if campaign_state.is_timed_campaign() {
1002            aggregator.finish_partial()?
1003        } else {
1004            aggregator.finish_campaign()?
1005        };
1006        result.interrupted = campaign_state.interrupted(result.runs, self.config.runs);
1007        result.shrink_deadline = campaign_state.shrink_deadline();
1008        result.symbolic_live =
1009            campaign_state.live_solver.as_ref().map(|solver| solver.lock().unwrap().finish());
1010        persist_campaign_optimization(
1011            &self.config.corpus,
1012            result.optimization_best_value,
1013            &result.optimization_best_sequence,
1014        );
1015        Ok(result)
1016    }
1017
1018    /// Runs one worker-local slice of an invariant campaign.
1019    #[allow(clippy::too_many_arguments)]
1020    fn run_invariant_worker(
1021        mut executor: Executor<FEN>,
1022        runner: TestRunner,
1023        config: InvariantConfig,
1024        setup_contracts: &'a ContractsByAddress,
1025        project_contracts: &'a ContractsByArtifact,
1026        plan: InvariantWorkerPlan,
1027        invariant_contract: InvariantContract<'_>,
1028        fuzz_fixtures: &FuzzFixtures,
1029        fuzz_state: EvmFuzzState,
1030        progress: Option<&ProgressBar>,
1031        campaign_state: &InvariantCampaignState,
1032        campaign_seed: InvariantCampaignSeed,
1033        corpus_seed: WorkerCorpusSeed,
1034        worker_count: usize,
1035        gas_report_samples: usize,
1036    ) -> Result<(InvariantWorkerOutput, Vec<FuzzBranchFrontier>)> {
1037        // Note: invariant function signatures (no inputs) are validated upstream in the
1038        // suite runner so parameterized `invariant_*` functions are rejected with a per-test
1039        // failure entry before any campaign runs.
1040        let config = invariant_worker_config(config, plan.worker_id, worker_count);
1041        let frontier_limit = if config.corpus.capture_branch_frontiers()
1042            && invariant_worker_collects_evm_cmp_log(&config, plan.worker_id, worker_count)
1043        {
1044            config.corpus.frontier_limit
1045        } else {
1046            0
1047        };
1048        let live_solver =
1049            (plan.worker_id == 0).then_some(campaign_state.live_solver.as_ref()).flatten();
1050        let mut frontier_recorder = FuzzFrontierRecorder::new(frontier_limit);
1051        // The campaign deadline must not cancel the initial invariant check, or an initial-state
1052        // failure is dropped. `prepare_worker` installs it right after that check.
1053        executor.inspector_mut().set_early_exit(campaign_state.early_exit().clone());
1054
1055        let (mut invariant_test, mut corpus_manager) = Self::prepare_worker(
1056            &mut executor,
1057            plan,
1058            worker_count,
1059            &invariant_contract,
1060            fuzz_fixtures,
1061            fuzz_state,
1062            &runner,
1063            &config,
1064            &campaign_seed,
1065            corpus_seed,
1066            campaign_state.cancellation().clone(),
1067        )?;
1068        let collect_corpus_cmp =
1069            invariant_worker_collects_evm_cmp_log(&config, plan.worker_id, worker_count);
1070        let mut runs = 0;
1071        // Where the next view harvesting window starts; kept across runs so it keeps rotating.
1072        let mut view_cursor = 0;
1073        let mut snapshots = StateSnapshots::new(config.depth, &executor, worker_count);
1074        campaign_state.sync_handler_failures(&invariant_test.test_data.failures);
1075        // Report invariants that already fail in the initial state. Later runs only report
1076        // failures that they add.
1077        record_new_invariant_failures(
1078            campaign_state,
1079            &invariant_contract,
1080            &invariant_test.test_data.failures,
1081        );
1082        let broken_initially = invariant_test.test_data.failures.broken_invariants();
1083
1084        // Invariant runs with edge coverage if corpus dir is set or showing edge coverage.
1085        let edge_coverage_enabled = config.corpus.collect_edge_coverage();
1086
1087        'stop: while should_continue_invariant_worker(campaign_state, runs, plan) {
1088            // Per-run failure count snapshot used to gate `afterInvariant` below.
1089            let failures_before_run = invariant_test.test_data.failures.invariant_count();
1090            // A run that records no failure changes only the revert count.
1091            let failures_revision = invariant_test.test_data.failures.revision();
1092            let handler_failures_before_run = invariant_test.test_data.failures.handler_count();
1093            let reverts_before_run = invariant_test.test_data.failures.reverts;
1094            let mut stop_after_run = false;
1095            let mut run_cancelled = false;
1096            let mut observed_call_entries = Vec::<(Vec<ObservedCall>, BasicTxDetails)>::new();
1097
1098            let call_campaign = FuzzCampaign::new(FuzzCampaignMode::Invariant {
1099                check_interval: config.check_interval,
1100                optimization: invariant_contract.is_optimization(),
1101            });
1102
1103            let mut run_depth =
1104                invariant_run_depth(&config, &mut invariant_test.test_data.branch_runner);
1105
1106            let mut corpus_run = Option::<RecordedCallSequence>::None;
1107            // Before each run, we must reset the backend state: to the post-setUp state or to a
1108            // snapshot reached by an earlier run.
1109            let candidate = live_solver
1110                .and_then(|solver| solver.lock().unwrap().next(config.depth.max(1) as usize));
1111            if let Some(candidate) = &candidate {
1112                run_depth = run_depth.max(candidate.len() as u32);
1113            }
1114            let start = if candidate.is_some() {
1115                snapshots.start_from_setup(&executor)
1116            } else {
1117                snapshots.start(&mut invariant_test.test_data.branch_runner, &executor)
1118            };
1119            // The calls of a run are not checked for the invariants already broken, but a run
1120            // resumed from a snapshot carries calls of earlier runs, which may have been checked
1121            // for any invariant that broke after the initial checks, so only those broken
1122            // initially are left out.
1123            let unchecked_invariants = if start.prefix.is_empty() {
1124                invariant_test.test_data.failures.broken_invariants()
1125            } else {
1126                broken_initially.clone()
1127            };
1128            invariant_test.test_data.failures.start_run(unchecked_invariants);
1129            // Corpus entries replay from the post-setUp state, so a resumed run makes fresh calls.
1130            let sequence_plan = if let Some(candidate) = candidate {
1131                corpus_manager
1132                    .replay_sequence(candidate, &mut invariant_test.test_data.branch_runner)?
1133            } else if start.prefix.is_empty() {
1134                corpus_manager.new_sequence(&mut invariant_test.test_data.branch_runner)?
1135            } else {
1136                corpus_manager.fresh_sequence(&mut invariant_test.test_data.branch_runner)?
1137            };
1138            let initial_seq = sequence_plan.initial();
1139            let collect_live = live_solver.is_some_and(|solver| solver.lock().unwrap().is_active());
1140            let mut frontier_calldata_bytes = if collect_live {
1141                start.prefix.iter().map(|tx| tx.call_details.calldata.len()).sum::<usize>()
1142            } else {
1143                0
1144            };
1145            // Storage states this run reached, as the index of the call that produced each and a
1146            // feature that call reached first. A resumed run starts from its snapshot's state.
1147            let mut frontier_states = start
1148                .state
1149                .map(|state| (start.prefix.len() - 1, state))
1150                .into_iter()
1151                .collect::<Vec<_>>();
1152            let mut frontier_run = (frontier_limit > 0
1153                || (collect_live
1154                    && LiveInvariantSolver::accepts_sequence(
1155                        start.prefix.len(),
1156                        frontier_calldata_bytes,
1157                    )))
1158            .then(|| RecordedCallSequence {
1159                inputs: start.prefix.to_vec(),
1160                cmp_seq: vec![Vec::new(); start.prefix.len()],
1161            });
1162
1163            // Create current invariant run data.
1164            let mut current_run = InvariantTestRun::new(
1165                &start.prefix,
1166                initial_seq[0].clone(),
1167                start.executor,
1168                run_depth as usize,
1169            );
1170            // Snapshots can carry instrumentation from an earlier live run. Restore only the
1171            // independently requested corpus logging once the assistant stops accepting work.
1172            if live_solver.is_some() {
1173                current_run
1174                    .executor
1175                    .inspector_mut()
1176                    .collect_evm_cmp_log(collect_corpus_cmp || frontier_run.is_some());
1177            }
1178
1179            // We stop the run immediately if we have reverted, and `fail_on_revert` is set.
1180            if config.fail_on_revert && invariant_test.reverts() > 0 {
1181                campaign_state.request_terminal_stop();
1182                return Err(eyre!("call reverted"));
1183            }
1184
1185            let mut call_cmp_values = Vec::new();
1186            let mut call_new_coverage = false;
1187            let mut run_reverts = 0u64;
1188            let mut coverage_prefix_len = 0;
1189            let mut assertion_failure = false;
1190            let mut pre_merge_edges_hash = None;
1191            let mut handler = None;
1192            let mut abort_campaign = false;
1193            let sequence_outcome = call_campaign.run_sequence(
1194                &mut current_run,
1195                run_depth,
1196                |run| {
1197                    let tx = run.inputs.last_mut().expect("campaign always has a current input");
1198                    (&mut run.executor, tx)
1199                },
1200                |run| run.depth,
1201                |_| campaign_state.should_stop(),
1202                |current_run, event| {
1203                    match event {
1204                        CampaignEvent::Feedback(call_result) => {
1205                            let current_tx = current_run.inputs.last().ok_or_else(|| {
1206                                eyre!("no input generated to call fuzzed target.")
1207                            })?;
1208                            let selector = current_tx
1209                                .call_details
1210                                .calldata
1211                                .get(..4)
1212                                .map(Selector::from_slice)
1213                                .unwrap_or_default();
1214                            handler = Some((current_tx.call_details.target, selector));
1215                            call_cmp_values = call_result.evm_cmp_values.take().unwrap_or_default();
1216                            let discarded = call_result.result.as_ref() == MAGIC_ASSUME;
1217                            if config.show_metrics {
1218                                invariant_test.record_metrics(
1219                                    current_tx,
1220                                    call_result.reverted,
1221                                    discarded,
1222                                );
1223                            }
1224                            HitMaps::merge_opt(
1225                                &mut current_run.line_coverage,
1226                                call_result.line_coverage.take(),
1227                            );
1228                            assertion_failure = !discarded
1229                                && did_fail_on_assert(call_result, &call_result.state_changeset);
1230                            // A revert that fails an invariant is committed before the failure is
1231                            // recorded, so its provenance is recorded now. The block delay was
1232                            // already applied.
1233                            if call_result.reverted
1234                                && !discarded
1235                                && !assertion_failure
1236                                && invariant_contract.invariant_fns.iter().any(
1237                                    |(invariant, fail_on_revert)| {
1238                                        *fail_on_revert
1239                                            && !invariant_test
1240                                                .test_data
1241                                                .failures
1242                                                .has_failure(invariant)
1243                                    },
1244                                )
1245                            {
1246                                let tx =
1247                                    BasicTxDetails { warp: None, roll: None, ..current_tx.clone() };
1248                                call_result.failure_provenance = failure_provenance(
1249                                    &current_run.executor,
1250                                    &config,
1251                                    |executor| execute_tx(executor, &tx).ok(),
1252                                );
1253                            }
1254                            pre_merge_edges_hash = assertion_failure
1255                                .then(|| error::snapshot_edge_fingerprint(call_result))
1256                                .flatten();
1257                            call_new_coverage = corpus_manager.merge_edge_coverage(call_result);
1258                            if call_new_coverage {
1259                                current_run.new_coverage = true;
1260                            }
1261                            let observed_calls = std::mem::take(&mut call_result.observed_calls);
1262                            if call_new_coverage && !observed_calls.is_empty() {
1263                                observed_call_entries.push((observed_calls, current_tx.clone()));
1264                            }
1265                        }
1266                        CampaignEvent::Check { result, kind, should_check } => {
1267                            let mut result =
1268                                result.take().expect("campaign check result is available");
1269                            if kind == CampaignCallKind::AssumptionRejected {
1270                                current_run.inputs.pop();
1271                                current_run.rejects += 1;
1272                                if current_run.rejects > config.max_assume_rejects {
1273                                    invariant_test.set_error(
1274                                        invariant_contract.anchor(),
1275                                        InvariantFuzzError::MaxAssumeRejects(
1276                                            config.max_assume_rejects,
1277                                        ),
1278                                    );
1279                                    campaign_state.request_terminal_stop();
1280                                    abort_campaign = true;
1281                                    return Ok(CampaignControl::Stop);
1282                                }
1283                                return Ok(CampaignControl::Continue);
1284                            }
1285                            debug_assert_eq!(kind, CampaignCallKind::Accepted);
1286                            if let Some(history) = &mut frontier_run {
1287                                let tx = current_run
1288                                    .inputs
1289                                    .last()
1290                                    .expect("accepted call has a campaign input");
1291                                frontier_calldata_bytes += tx.call_details.calldata.len();
1292                                if frontier_limit > 0
1293                                    || (LiveInvariantSolver::accepts_sequence(
1294                                        history.inputs.len() + 1,
1295                                        frontier_calldata_bytes,
1296                                    ) && live_solver
1297                                        .is_some_and(|solver| solver.lock().unwrap().is_active()))
1298                                {
1299                                    history.inputs.push(tx.clone());
1300                                    history.cmp_seq.push(call_cmp_values.clone());
1301                                } else {
1302                                    frontier_run = None;
1303                                    current_run
1304                                        .executor
1305                                        .inspector_mut()
1306                                        .collect_evm_cmp_log(collect_corpus_cmp);
1307                                }
1308                            }
1309                            if config.corpus.is_coverage_guided() {
1310                                let preserve_revert =
1311                                    invariant_contract.is_optimization() || config.has_delay();
1312                                let retain_for_corpus =
1313                                    !result.reverted || preserve_revert || call_new_coverage;
1314                                if let Some(corpus_run) = &mut corpus_run {
1315                                    if retain_for_corpus {
1316                                        corpus_run.inputs.push(
1317                                            current_run
1318                                                .inputs
1319                                                .last()
1320                                                .expect("accepted call has a campaign input")
1321                                                .clone(),
1322                                        );
1323                                        corpus_run
1324                                            .cmp_seq
1325                                            .push(std::mem::take(&mut call_cmp_values));
1326                                    }
1327                                } else if result.reverted && !preserve_revert && call_new_coverage {
1328                                    let mut cmp_seq = std::mem::take(&mut current_run.cmp_seq);
1329                                    cmp_seq.push(std::mem::take(&mut call_cmp_values));
1330                                    corpus_run = Some(RecordedCallSequence {
1331                                        inputs: current_run.inputs.clone(),
1332                                        cmp_seq,
1333                                    });
1334                                } else if !result.reverted || preserve_revert {
1335                                    current_run.cmp_seq.push(std::mem::take(&mut call_cmp_values));
1336                                }
1337                                if call_new_coverage {
1338                                    coverage_prefix_len = corpus_run
1339                                        .as_ref()
1340                                        .map_or(current_run.inputs.len(), |history| {
1341                                            history.inputs.len()
1342                                        });
1343                                }
1344                            }
1345                            let (handler_target, handler_selector) =
1346                                handler.take().expect("feedback precedes campaign checks");
1347                            if result.reverted {
1348                                run_reverts += 1;
1349                            }
1350                            let state_changeset = std::mem::take(&mut result.state_changeset);
1351                            let reverted = result.reverted;
1352                            if !result.reverted {
1353                                collect_data(
1354                                    &invariant_test,
1355                                    &state_changeset,
1356                                    current_run.inputs.last().expect("checked above"),
1357                                    &result,
1358                                    run_depth,
1359                                );
1360                                if config.dictionary.include_view_values {
1361                                    collect_view_values(
1362                                        &invariant_test,
1363                                        &current_run.executor,
1364                                        &state_changeset,
1365                                        current_run.inputs.last().expect("checked above"),
1366                                        run_depth,
1367                                        &mut view_cursor,
1368                                    );
1369                                }
1370                            }
1371
1372                            let created_before = current_run.created_contracts.len();
1373                            if let Err(error) =
1374                                &invariant_test.targeted_contracts.collect_created_contracts(
1375                                    state_changeset.account_changes(),
1376                                    project_contracts,
1377                                    setup_contracts,
1378                                    &campaign_seed.artifact_filters,
1379                                    &mut current_run.created_contracts,
1380                                )
1381                            {
1382                                warn!(target: "forge::test", "{error}");
1383                            }
1384                            invariant_test.invalidate_metric_key_cache(
1385                                &current_run.created_contracts[created_before..],
1386                            );
1387                            current_run
1388                                .fuzz_runs
1389                                .push(FuzzCase { gas: result.gas_used, stipend: result.stipend });
1390
1391                            let continues = if should_check || assertion_failure || reverted {
1392                                let outcome = can_continue(
1393                                    &invariant_contract,
1394                                    &mut invariant_test,
1395                                    current_run,
1396                                    &config,
1397                                    result,
1398                                    &state_changeset,
1399                                    handler_target,
1400                                    handler_selector,
1401                                    assertion_failure,
1402                                    pre_merge_edges_hash,
1403                                )
1404                                .map_err(|error| eyre!(error.to_string()))?;
1405                                run_cancelled = outcome.cancelled;
1406                                outcome.continues
1407                            } else {
1408                                true
1409                            };
1410
1411                            if run_cancelled {
1412                                return Ok(CampaignControl::Stop);
1413                            }
1414                            if !continues || current_run.depth == run_depth - 1 {
1415                                current_run.save_last_run_inputs = true;
1416                            }
1417                            if !continues {
1418                                if invariant_contract.invariant_fns.len() == 1
1419                                    || config.fail_on_revert
1420                                {
1421                                    campaign_state.request_terminal_stop();
1422                                    stop_after_run = true;
1423                                }
1424                                return Ok(CampaignControl::Stop);
1425                            }
1426                            if !reverted {
1427                                let novel = snapshots.observe(&state_changeset);
1428                                if let Some(&state) = novel.first()
1429                                    && let Some(history) = &frontier_run
1430                                {
1431                                    frontier_states.push((history.inputs.len() - 1, state));
1432                                }
1433                                // Targets created mid-run are dropped at its end, so states
1434                                // holding them are not resumed.
1435                                if current_run.created_contracts.is_empty() {
1436                                    snapshots.capture(
1437                                        &current_run.executor,
1438                                        &current_run.inputs,
1439                                        novel,
1440                                    );
1441                                }
1442                            }
1443                        }
1444                        CampaignEvent::Advance => current_run.depth += 1,
1445                        CampaignEvent::Next { discarded, depth } => {
1446                            current_run.inputs.push(sequence_plan.next(
1447                                &mut invariant_test.test_data.branch_runner,
1448                                discarded,
1449                                depth as usize,
1450                            )?);
1451                        }
1452                        CampaignEvent::PostCheck => {
1453                            // A complete run ends with the input generated after its last call,
1454                            // which never runs.
1455                            if current_run.depth >= run_depth {
1456                                current_run.inputs.pop();
1457                            }
1458                            // Multi-predicate campaigns keep running after earlier failures, but
1459                            // the hook must still execute on subsequent clean runs.
1460                            if !abort_campaign
1461                                && !run_cancelled
1462                                && invariant_contract.call_after_invariant
1463                                && invariant_test.test_data.failures.invariant_count()
1464                                    == failures_before_run
1465                            {
1466                                let (broken, hook_cancelled) = assert_after_invariant(
1467                                    &invariant_contract,
1468                                    &mut invariant_test,
1469                                    current_run,
1470                                    &config,
1471                                )
1472                                .map_err(|_| eyre!("Failed to call afterInvariant"))?;
1473                                if hook_cancelled {
1474                                    run_cancelled = true;
1475                                } else if broken.is_some() {
1476                                    current_run.save_last_run_inputs = true;
1477                                }
1478                            }
1479                        }
1480                    }
1481                    Ok(CampaignControl::Continue)
1482                },
1483            )?;
1484            if sequence_outcome == CampaignSequenceOutcome::Cancelled {
1485                // A timed-out partial run remains successful, matching the previous worker
1486                // behavior, but it must not be persisted or counted.
1487                run_cancelled = true;
1488            }
1489            if abort_campaign {
1490                break 'stop;
1491            }
1492
1493            // The worker which requested a terminal stop for its own failure still owns a
1494            // complete failing run. All other campaign stops discard the partial run before any
1495            // corpus persistence or accounting.
1496            if campaign_state.should_stop() && !stop_after_run {
1497                run_cancelled = true;
1498            }
1499
1500            if run_cancelled {
1501                let completed_finding =
1502                    invariant_test.test_data.failures.revision() != failures_revision;
1503                if completed_finding {
1504                    record_new_invariant_failures(
1505                        campaign_state,
1506                        &invariant_contract,
1507                        &invariant_test.test_data.failures,
1508                    );
1509                    campaign_state.sync_handler_failures(&invariant_test.test_data.failures);
1510                } else {
1511                    invariant_test.test_data.failures.reverts = reverts_before_run;
1512                }
1513                break 'stop;
1514            }
1515
1516            if invariant_test.test_data.failures.invariant_count() > failures_before_run {
1517                record_new_invariant_failures(
1518                    campaign_state,
1519                    &invariant_contract,
1520                    &invariant_test.test_data.failures,
1521                );
1522            }
1523            if invariant_test.test_data.failures.handler_count() > handler_failures_before_run {
1524                campaign_state.sync_handler_failures(&invariant_test.test_data.failures);
1525            }
1526
1527            for (observed_calls, parent_tx) in observed_call_entries {
1528                corpus_manager.hoist_observed_calls(
1529                    &observed_calls,
1530                    &parent_tx,
1531                    &invariant_test.targeted_contracts,
1532                    &campaign_seed.sender_filters,
1533                    CorpusInsertionMode::Live,
1534                );
1535            }
1536
1537            // Extend corpus only after the run and its optional hook have completed.
1538            if let Some(frontier_run) = &frontier_run {
1539                // Frontiers past the depth are dropped by frontier seeding, so a resumed run's
1540                // deeper calls must not displace the ones it can use.
1541                let len = frontier_run.cmp_seq.len().min(config.depth.max(1) as usize);
1542                frontier_recorder
1543                    .capture_sequence(&frontier_run.inputs, &frontier_run.cmp_seq[..len]);
1544                if let Some(solver) = live_solver {
1545                    solver.lock().unwrap().submit(
1546                        frontier_run,
1547                        config.depth as usize,
1548                        &frontier_states,
1549                    );
1550                }
1551            }
1552            let optimization = current_run
1553                .optimization_value
1554                .map(|value| (value, &current_run.inputs[..current_run.optimization_prefix_len]));
1555            let mut corpus_inputs = corpus_run
1556                .as_ref()
1557                .map_or(current_run.inputs.as_slice(), |history| history.inputs.as_slice());
1558            let mut corpus_cmp_seq = corpus_run
1559                .as_ref()
1560                .map_or(current_run.cmp_seq.as_slice(), |history| history.cmp_seq.as_slice());
1561            if current_run.new_coverage && !invariant_contract.is_optimization() {
1562                corpus_inputs = &corpus_inputs[..coverage_prefix_len];
1563                corpus_cmp_seq = &corpus_cmp_seq[..coverage_prefix_len];
1564            }
1565            if worker_count > 1 {
1566                corpus_manager.process_inputs_for_campaign(
1567                    corpus_inputs,
1568                    corpus_cmp_seq,
1569                    current_run.new_coverage,
1570                    optimization,
1571                );
1572            } else {
1573                corpus_manager.process_inputs(
1574                    corpus_inputs,
1575                    corpus_cmp_seq,
1576                    current_run.new_coverage,
1577                    optimization,
1578                );
1579            }
1580
1581            // End current invariant test run.
1582            if let Some(value) = current_run.optimization_value {
1583                invariant_test.update_optimization_value(
1584                    value,
1585                    &current_run.inputs[..current_run.optimization_prefix_len],
1586                );
1587            }
1588            if current_run.save_last_run_inputs {
1589                invariant_test.set_last_run_inputs(std::mem::take(&mut current_run.inputs));
1590            }
1591            invariant_test.merge_line_coverage(current_run.line_coverage.take());
1592            for fuzz_run in &current_run.fuzz_runs {
1593                campaign_state.record_call(fuzz_run.gas);
1594            }
1595            snapshots.finish_run(
1596                current_run.new_coverage,
1597                current_run.fuzz_runs.len() as u64,
1598                run_reverts,
1599            );
1600            current_run.drop_corpus_payloads();
1601            invariant_test.end_run(current_run, gas_report_samples);
1602            runs += 1;
1603            let total_runs = campaign_state.increment_runs();
1604            debug_assert!(
1605                campaign_state.is_timed_campaign() || total_runs <= config.runs,
1606                "worker runs were not distributed correctly"
1607            );
1608            if let Some(progress) = progress {
1609                progress.inc(1);
1610                campaign_state.sync_handler_failures(&invariant_test.test_data.failures);
1611                // Display current best value, corpus metrics, and failure counts.
1612                let best = invariant_test.test_data.optimization_best_value;
1613                let failure_metrics = campaign_state.failure_metrics();
1614                let broken = failure_metrics.unique_failures.len();
1615                let handler_bugs = failure_metrics.broken_handlers;
1616                let total_invariants = invariant_contract.invariant_fns.len();
1617                if edge_coverage_enabled || best.is_some() || broken > 0 || handler_bugs > 0 {
1618                    let mut msg = String::new();
1619                    if let Some(best) = best {
1620                        msg.push_str(&format!("best: {best}"));
1621                    }
1622                    if edge_coverage_enabled {
1623                        if !msg.is_empty() {
1624                            msg.push_str(", ");
1625                        }
1626                        msg.push_str(&format!("{}", corpus_manager.metrics));
1627                        match corpus_manager.time_since_new_edge() {
1628                            Some(elapsed) => msg.push_str(&format!(
1629                                "\n        - time since new edge: {:.1}s",
1630                                elapsed.as_secs_f64()
1631                            )),
1632                            None => msg.push_str("\n        - time since new edge: never"),
1633                        }
1634                    }
1635                    if broken > 0 {
1636                        if !msg.is_empty() {
1637                            msg.push_str(", ");
1638                        }
1639                        msg.push_str(&format!("❌ {broken}/{total_invariants} broken"));
1640                    }
1641                    if handler_bugs > 0 {
1642                        if !msg.is_empty() {
1643                            msg.push_str(", ");
1644                        }
1645                        msg.push_str(&format!("⚠ {handler_bugs} handler bug(s)"));
1646                    }
1647                    let msg =
1648                        if worker_count > 1 { format!("[w{}] {msg}", plan.worker_id) } else { msg };
1649                    progress.set_message(msg);
1650                }
1651            } else if edge_coverage_enabled
1652                && campaign_state.should_emit_metrics_report(DURATION_BETWEEN_METRICS_REPORT)
1653            {
1654                campaign_state.sync_handler_failures(&invariant_test.test_data.failures);
1655                let failure_metrics = campaign_state.failure_metrics();
1656                let (total_txs, total_gas) = campaign_state.throughput_totals();
1657                let throughput = InvariantThroughputMetrics { total_txs, total_gas };
1658                // Display corpus metrics inline as JSON.
1659                let metrics = build_invariant_progress_json(
1660                    InvariantProgressContext {
1661                        timestamp_secs: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
1662                        contract_name: invariant_contract.name,
1663                        optimization_best: invariant_test.test_data.optimization_best_value,
1664                        throughput,
1665                        elapsed: campaign_state.elapsed(),
1666                        worker_id: plan.worker_id,
1667                        worker_count,
1668                        time_since_new_edge: corpus_manager.time_since_new_edge(),
1669                    },
1670                    &corpus_manager.metrics,
1671                    &failure_metrics,
1672                );
1673                let _ = sh_eprintln!("{}", serde_json::to_string(&metrics)?);
1674            }
1675
1676            if stop_after_run {
1677                break 'stop;
1678            }
1679        }
1680
1681        trace!(?fuzz_fixtures);
1682        invariant_test.fuzz_state.log_stats();
1683
1684        // Campaign-local terminal stops and deadlines must not suppress post-campaign shrinking,
1685        // which a timed campaign bounds by its own shrink deadline instead.
1686        executor.inspector_mut().set_early_exit(campaign_state.early_exit().clone());
1687        Self::shrink_handler_failures(
1688            &config,
1689            &executor,
1690            &mut invariant_test.test_data,
1691            progress,
1692            campaign_state.early_exit(),
1693            campaign_state.shrink_deadline(),
1694        );
1695
1696        // Move out the final test data and drop worker-local fuzz state before returning this
1697        // worker's aggregate output. Long invariant campaigns can leave large dictionaries and
1698        // target state behind; once shrinking is complete, only `test_data` is needed.
1699        let InvariantTest { fuzz_state: _, targeted_contracts: _, test_data: result } =
1700            invariant_test;
1701        let reverts = result.failures.reverts;
1702        let (errors, handler_errors) = result.failures.partition();
1703        let worker_result = InvariantFuzzTestResult::new(
1704            errors,
1705            handler_errors,
1706            result.runs,
1707            result.calls,
1708            reverts,
1709            result.last_run_inputs,
1710            result.gas_report_traces,
1711            result.line_coverage,
1712            result.metrics.into_iter().collect(),
1713            if plan.worker_id == 0 { corpus_manager.failed_replays } else { 0 },
1714            1,
1715            result.optimization_best_value,
1716            result.optimization_best_sequence,
1717        );
1718        drop(corpus_manager);
1719        let reported_plan = if campaign_state.is_timed_campaign() {
1720            InvariantWorkerPlan { runs, ..plan }
1721        } else {
1722            // Sharded campaigns must report the original assigned range. Early worker exit changes
1723            // the number of executed runs, but it must not shrink `plan.runs`: following workers'
1724            // `first_global_run` offsets were computed from the original partition.
1725            plan
1726        };
1727        Ok((
1728            InvariantWorkerOutput { plan: reported_plan, result: worker_result },
1729            frontier_recorder.into_frontiers(),
1730        ))
1731    }
1732
1733    fn shrink_handler_failures(
1734        config: &InvariantConfig,
1735        executor: &Executor<FEN>,
1736        result: &mut InvariantTestData,
1737        progress: Option<&ProgressBar>,
1738        early_exit: &EarlyExit,
1739        shrink_deadline: Option<Instant>,
1740    ) {
1741        let total = result.failures.handler_count();
1742        if total == 0 {
1743            return;
1744        }
1745
1746        for (idx, error) in result.failures.handler_failures_mut().enumerate() {
1747            if early_exit.should_stop() {
1748                break;
1749            }
1750            let Some(failure) = error.as_handler_assertion_mut() else {
1751                continue;
1752            };
1753            let shrink_progress = shrink::ShrinkProgress::new(
1754                config,
1755                progress,
1756                &format!("handler {:#x}::{}", failure.reverter, failure.selector),
1757                Some((idx + 1, total)),
1758                None,
1759                false,
1760            );
1761            match shrink::shrink_handler_sequence(
1762                config,
1763                &failure.call_sequence,
1764                failure.edge_fingerprint,
1765                executor,
1766                &shrink_progress,
1767                early_exit,
1768                shrink_deadline,
1769            ) {
1770                Ok(shrunk) if !shrunk.is_empty() => {
1771                    failure.call_sequence = shrunk;
1772                }
1773                Ok(_) => {}
1774                Err(e) => trace!(target: "forge::test", "handler shrink failed: {e}"),
1775            }
1776        }
1777    }
1778
1779    /// Prepares worker-local structures to execute an invariant campaign slice.
1780    #[allow(clippy::too_many_arguments)]
1781    fn prepare_worker(
1782        executor: &mut Executor<FEN>,
1783        plan: InvariantWorkerPlan,
1784        worker_count: usize,
1785        invariant_contract: &InvariantContract<'_>,
1786        fuzz_fixtures: &FuzzFixtures,
1787        fuzz_state: EvmFuzzState,
1788        runner: &TestRunner,
1789        config: &InvariantConfig,
1790        campaign_seed: &InvariantCampaignSeed,
1791        corpus_seed: WorkerCorpusSeed,
1792        cancellation: EvmExecutionCancellation,
1793    ) -> Result<(InvariantTest, WorkerCorpus)> {
1794        let fuzz_state = fuzz_state.into_invariant();
1795        let targeted_contracts = FuzzRunIdentifiedContracts::new(
1796            campaign_seed.targeted_contracts.clone(),
1797            campaign_seed.targets_are_updatable,
1798        );
1799        executor.inspector_mut().collect_evm_cmp_log(invariant_worker_collects_evm_cmp_log(
1800            config,
1801            plan.worker_id,
1802            worker_count,
1803        ));
1804
1805        // Creates the invariant strategy.
1806        let generator = TxGenerator::invariant(
1807            fuzz_state.clone(),
1808            campaign_seed.sender_filters.clone(),
1809            targeted_contracts.clone(),
1810            config.clone(),
1811            fuzz_fixtures.clone(),
1812        );
1813
1814        // Set up fuzzer WITHOUT call_generator initially.
1815        // We defer call_override until after the initial invariant check to avoid
1816        // injecting random calls during setup which would break the invariant assertion.
1817        let extra_cheatcode_addresses = executor.inspector().extra_cheatcode_addresses();
1818        executor.inspector_mut().set_fuzzer(
1819            Fuzzer::default()
1820                .with_extra_cheatcode_addresses(extra_cheatcode_addresses)
1821                .with_call_recording(config.corpus.is_coverage_guided()),
1822        );
1823
1824        // Let's make sure the invariant is sound before actually starting the run:
1825        // We'll assert the invariant in its initial state, and if it fails, we'll
1826        // already know if we can early exit the invariant run.
1827        // This does not count as a fuzz run. It will just register the revert.
1828        let mut failures = InvariantFailures::new();
1829        // Seed disk-recovered handler bugs so live counters reflect them from tick 0.
1830        for (&(addr, sel), err) in &campaign_seed.initial_handler_failures {
1831            failures.seed_handler_failure(addr, sel, err.clone());
1832        }
1833        invariant_preflight_check(
1834            invariant_contract,
1835            config,
1836            &targeted_contracts,
1837            executor,
1838            &[],
1839            &mut failures,
1840        )?;
1841        executor.inspector_mut().set_execution_cancellation(cancellation);
1842        if let Some(fuzzer) = executor.inspector_mut().fuzzer.as_mut() {
1843            let _ = fuzzer.take_observed_calls();
1844        }
1845        let generator = foundry_evm_fuzz::sequence::SequenceGenerator::invariant_with_fixtures(
1846            generator,
1847            fuzz_state.clone(),
1848            fuzz_fixtures.clone(),
1849            targeted_contracts.clone(),
1850            &config.corpus,
1851        )?;
1852        let mut worker = WorkerCorpus::from_seed(
1853            plan.worker_id as usize,
1854            config.corpus.clone(),
1855            generator,
1856            corpus_seed,
1857        )?;
1858
1859        if let Err(err) = worker.seed_from_test_traces(
1860            invariant_contract,
1861            &targeted_contracts,
1862            &campaign_seed.sender_filters,
1863            executor,
1864        ) {
1865            debug!(target: "corpus", %err, "failed to seed corpus from test traces");
1866        }
1867
1868        // NOW enable call_override after the initial invariant check and corpus trace seeding have
1869        // passed. This allows `override_call_strat` to inject calls during actual fuzz runs for
1870        // reentrancy vulnerability detection.
1871        if config.call_override {
1872            let target_contract_ref = Arc::new(RwLock::new(Address::ZERO));
1873
1874            // Collect handler addresses - these are the contracts we want to inject
1875            // reentrancy into (simulating malicious receive() functions).
1876            let handler_addresses: AddressSet =
1877                targeted_contracts.targets().keys().copied().collect();
1878            let override_targets = targeted_contracts
1879                .targets()
1880                .iter()
1881                .filter_map(|(address, contract)| {
1882                    let functions = contract.abi_fuzzed_functions().cloned().collect::<Vec<_>>();
1883                    (!functions.is_empty()).then_some((*address, functions))
1884                })
1885                .collect::<Vec<_>>();
1886
1887            let call_generator = RandomCallGenerator::new(
1888                invariant_contract.address,
1889                handler_addresses,
1890                runner.clone(),
1891                override_call_strat(
1892                    fuzz_state.snapshot(),
1893                    override_targets,
1894                    target_contract_ref.clone(),
1895                    fuzz_fixtures.clone(),
1896                    config.dictionary.dictionary_weight,
1897                    config.corpus.payable_value_weight,
1898                ),
1899                target_contract_ref,
1900            );
1901
1902            if let Some(fuzzer) = executor.inspector_mut().fuzzer.as_mut() {
1903                fuzzer.call_generator = Some(call_generator);
1904            }
1905        }
1906
1907        let mut invariant_test =
1908            InvariantTest::new(fuzz_state, targeted_contracts, failures, runner.clone());
1909
1910        // Seed invariant test with previously persisted optimization state,
1911        // but only if the current invariant is in optimization mode. Persisted optimization state
1912        // is a master-worker artifact loaded with the initial corpus.
1913        if invariant_contract.is_optimization() {
1914            let (opt_best_value, opt_best_sequence) = worker.optimization_initial_state();
1915            if let Some(value) = opt_best_value {
1916                invariant_test.update_optimization_value(value, &opt_best_sequence);
1917            }
1918        }
1919
1920        Ok((invariant_test, worker))
1921    }
1922
1923    /// Fills the `InvariantExecutor` with the artifact identifier filters (in `path:name` string
1924    /// format). They will be used to filter contracts after the `setUp`, and more importantly,
1925    /// during the runs.
1926    ///
1927    /// Also excludes any contract without any mutable functions.
1928    ///
1929    /// Priority:
1930    ///
1931    /// targetArtifactSelectors > excludeArtifacts > targetArtifacts
1932    pub fn select_contract_artifacts(&mut self, invariant_address: Address) -> Result<()> {
1933        let targeted_artifact_selectors = self
1934            .executor
1935            .call_sol_default(invariant_address, &IInvariantTest::targetArtifactSelectorsCall {});
1936
1937        // Insert them into the executor `targeted_abi`.
1938        for IInvariantTest::FuzzArtifactSelector { artifact, selectors } in
1939            targeted_artifact_selectors
1940        {
1941            let identifier = self.validate_selected_contract(artifact, &selectors)?;
1942            self.artifact_filters.targeted.entry(identifier).or_default().extend(selectors);
1943        }
1944
1945        let targeted_artifacts = self
1946            .executor
1947            .call_sol_default(invariant_address, &IInvariantTest::targetArtifactsCall {});
1948        let excluded_artifacts = self
1949            .executor
1950            .call_sol_default(invariant_address, &IInvariantTest::excludeArtifactsCall {});
1951
1952        // Insert `excludeArtifacts` into the executor `excluded_abi`.
1953        for contract in excluded_artifacts {
1954            let identifier = self.validate_selected_contract(contract, &[])?;
1955
1956            if !self.artifact_filters.excluded.contains(&identifier) {
1957                self.artifact_filters.excluded.push(identifier);
1958            }
1959        }
1960
1961        // Exclude any artifact without mutable functions.
1962        for (artifact, contract) in self.project_contracts.iter() {
1963            if contract
1964                .abi
1965                .functions()
1966                .filter(|func| {
1967                    !matches!(
1968                        func.state_mutability,
1969                        alloy_json_abi::StateMutability::Pure
1970                            | alloy_json_abi::StateMutability::View
1971                    )
1972                })
1973                .count()
1974                == 0
1975                && !self.artifact_filters.excluded.contains(&artifact.identifier())
1976            {
1977                self.artifact_filters.excluded.push(artifact.identifier());
1978            }
1979        }
1980
1981        // Insert `targetArtifacts` into the executor `targeted_abi`, if they have not been seen
1982        // before.
1983        for contract in targeted_artifacts {
1984            let identifier = self.validate_selected_contract(contract, &[])?;
1985
1986            if !self.artifact_filters.targeted.contains_key(&identifier)
1987                && !self.artifact_filters.excluded.contains(&identifier)
1988            {
1989                self.artifact_filters.targeted.insert(identifier, vec![]);
1990            }
1991        }
1992        Ok(())
1993    }
1994
1995    /// Makes sure that the contract exists in the project. If so, it returns its artifact
1996    /// identifier.
1997    fn validate_selected_contract(
1998        &mut self,
1999        contract: String,
2000        selectors: &[FixedBytes<4>],
2001    ) -> Result<String> {
2002        if let Some((artifact, contract_data)) =
2003            self.project_contracts.find_by_name_or_identifier(&contract)?
2004        {
2005            // Check that the selectors really exist for this contract.
2006            for selector in selectors {
2007                contract_data
2008                    .abi
2009                    .functions()
2010                    .find(|func| func.selector().as_slice() == selector.as_slice())
2011                    .wrap_err(format!("{contract} does not have the selector {selector:?}"))?;
2012            }
2013
2014            return Ok(artifact.identifier());
2015        }
2016        eyre::bail!(
2017            "{contract} not found in the project. Allowed format: `contract_name` or `contract_path:contract_name`."
2018        );
2019    }
2020
2021    /// Selects senders and contracts based on the contract methods `targetSenders() -> address[]`,
2022    /// `targetContracts() -> address[]` and `excludeContracts() -> address[]`.
2023    pub fn select_contracts_and_senders(
2024        &self,
2025        to: Address,
2026    ) -> Result<(SenderFilters, FuzzRunIdentifiedContracts)> {
2027        let targeted_senders =
2028            self.executor.call_sol_default(to, &IInvariantTest::targetSendersCall {});
2029        let mut excluded_senders =
2030            self.executor.call_sol_default(to, &IInvariantTest::excludeSendersCall {});
2031        // Extend with default excluded addresses - https://github.com/foundry-rs/foundry/issues/4163
2032        excluded_senders.extend([
2033            CHEATCODE_ADDRESS,
2034            HARDHAT_CONSOLE_ADDRESS,
2035            DEFAULT_CREATE2_DEPLOYER,
2036        ]);
2037        // Extend with precompiles - https://github.com/foundry-rs/foundry/issues/4287
2038        excluded_senders.extend(PRECOMPILES);
2039        let sender_filters = SenderFilters::new(targeted_senders, excluded_senders);
2040
2041        let selected = self.executor.call_sol_default(to, &IInvariantTest::targetContractsCall {});
2042        let excluded = self.executor.call_sol_default(to, &IInvariantTest::excludeContractsCall {});
2043
2044        let contracts = self
2045            .setup_contracts
2046            .iter()
2047            .filter(|&(addr, (identifier, _))| {
2048                // Include to address if explicitly set as target.
2049                if *addr == to && selected.contains(&to) {
2050                    return true;
2051                }
2052
2053                *addr != to
2054                    && *addr != CHEATCODE_ADDRESS
2055                    && *addr != HARDHAT_CONSOLE_ADDRESS
2056                    && (selected.is_empty() || selected.contains(addr))
2057                    && (excluded.is_empty() || !excluded.contains(addr))
2058                    && self.artifact_filters.matches(identifier)
2059            })
2060            .map(|(addr, (identifier, abi))| {
2061                (
2062                    *addr,
2063                    TargetedContract::new(identifier.clone(), abi.clone())
2064                        .with_project_contracts(self.project_contracts),
2065                )
2066            })
2067            .collect();
2068        let mut contracts = TargetedContracts { inner: contracts };
2069
2070        self.target_interfaces(to, &mut contracts)?;
2071
2072        self.select_selectors(to, &mut contracts)?;
2073        self.exclude_default_storage_hook_callbacks(&mut contracts)?;
2074
2075        // There should be at least one contract identified as target for fuzz runs.
2076        if contracts.is_empty() {
2077            eyre::bail!("No contracts to fuzz.");
2078        }
2079        if contracts.fuzzed_functions().next().is_none() {
2080            eyre::bail!("No functions to fuzz.");
2081        }
2082
2083        Ok((sender_filters, FuzzRunIdentifiedContracts::new(contracts, selected.is_empty())))
2084    }
2085
2086    /// Excludes registered storage-hook callbacks from implicit invariant targets.
2087    ///
2088    /// Explicit selector filters take precedence, so users can still target a callback
2089    /// intentionally.
2090    fn exclude_default_storage_hook_callbacks(
2091        &self,
2092        targeted_contracts: &mut TargetedContracts,
2093    ) -> Result<()> {
2094        let Some(cheatcodes) = self.executor.inspector().cheatcodes.as_deref() else {
2095            return Ok(());
2096        };
2097        let callbacks =
2098            cheatcodes
2099                .storage_load_hooks()
2100                .chain(cheatcodes.storage_store_hooks())
2101                .map(|(_, hook)| (hook.callback_target, Selector::from(hook.callback_selector)))
2102                .chain(cheatcodes.mapping_storage_store_hooks().map(|(_, _, hook)| {
2103                    (hook.callback_target, Selector::from(hook.callback_selector))
2104                }))
2105                .collect::<HashSet<_>>();
2106
2107        for (target, selector) in callbacks {
2108            let Some(contract) = targeted_contracts.get_mut(&target) else { continue };
2109            if !contract.targeted_functions.is_empty()
2110                || contract.function_by_selector(selector).is_none()
2111            {
2112                continue;
2113            }
2114            contract.add_selectors([selector], true)?;
2115        }
2116        Ok(())
2117    }
2118
2119    /// Extends the contracts and selectors to fuzz with the addresses and ABIs specified in
2120    /// `targetInterfaces() -> (address, string[])[]`. Enables targeting of addresses that are
2121    /// not deployed during `setUp` such as when fuzzing in a forked environment. Also enables
2122    /// targeting of delegate proxies and contracts deployed with `create` or `create2`.
2123    pub fn target_interfaces(
2124        &self,
2125        invariant_address: Address,
2126        targeted_contracts: &mut TargetedContracts,
2127    ) -> Result<()> {
2128        let interfaces = self
2129            .executor
2130            .call_sol_default(invariant_address, &IInvariantTest::targetInterfacesCall {});
2131
2132        // Since `targetInterfaces` returns a tuple array there is no guarantee
2133        // that the addresses are unique this map is used to merge functions of
2134        // the specified interfaces for the same address. For example:
2135        // `[(addr1, ["IERC20", "IOwnable"])]` and `[(addr1, ["IERC20"]), (addr1, ("IOwnable"))]`
2136        // should be equivalent.
2137        let mut combined = TargetedContracts::new();
2138
2139        // Loop through each address and its associated artifact identifiers.
2140        // We're borrowing here to avoid taking full ownership.
2141        for IInvariantTest::FuzzInterface { addr, artifacts } in &interfaces {
2142            // Identifiers are specified as an array, so we loop through them.
2143            for identifier in artifacts {
2144                // Try to find the contract by name or identifier in the project's contracts.
2145                if let Some((_, contract_data)) =
2146                    self.project_contracts.iter().find(|(artifact, _)| {
2147                        &artifact.name == identifier || &artifact.identifier() == identifier
2148                    })
2149                {
2150                    let abi = &contract_data.abi;
2151                    combined
2152                        // Check if there's an entry for the given key in the 'combined' map.
2153                        .entry(*addr)
2154                        // If the entry exists, extends its ABI with the function list.
2155                        .and_modify(|entry| {
2156                            // Extend the ABI's function list with the new functions.
2157                            entry.abi.functions.extend(abi.functions.clone());
2158                            entry.rebuild_function_lookups();
2159                        })
2160                        // Otherwise insert it into the map.
2161                        .or_insert_with(|| {
2162                            let mut contract =
2163                                TargetedContract::new(identifier.clone(), abi.clone());
2164                            contract.storage_layout =
2165                                contract_data.storage_layout.as_ref().map(Arc::clone);
2166                            contract
2167                        });
2168                }
2169            }
2170        }
2171
2172        targeted_contracts.extend(combined.inner);
2173
2174        Ok(())
2175    }
2176
2177    /// Selects the functions to fuzz based on the contract method `targetSelectors()` and
2178    /// `targetArtifactSelectors()`.
2179    pub fn select_selectors(
2180        &self,
2181        address: Address,
2182        targeted_contracts: &mut TargetedContracts,
2183    ) -> Result<()> {
2184        for (address, (identifier, _)) in self.setup_contracts {
2185            if let Some(selectors) = self.artifact_filters.targeted.get(identifier) {
2186                self.add_address_with_functions(*address, selectors, false, targeted_contracts)?;
2187            }
2188        }
2189
2190        let mut target_test_selectors = vec![];
2191        let mut excluded_test_selectors = vec![];
2192
2193        // Collect contract functions marked as target for fuzzing campaign.
2194        let selectors =
2195            self.executor.call_sol_default(address, &IInvariantTest::targetSelectorsCall {});
2196        for IInvariantTest::FuzzSelector { addr, selectors } in selectors {
2197            if addr == address {
2198                target_test_selectors = selectors.clone();
2199            }
2200            self.add_address_with_functions(addr, &selectors, false, targeted_contracts)?;
2201        }
2202
2203        // Collect contract functions excluded from fuzzing campaign.
2204        let excluded_selectors =
2205            self.executor.call_sol_default(address, &IInvariantTest::excludeSelectorsCall {});
2206        for IInvariantTest::FuzzSelector { addr, selectors } in excluded_selectors {
2207            if addr == address {
2208                // If fuzz selector address is the test contract, then record selectors to be
2209                // later excluded if needed.
2210                excluded_test_selectors = selectors.clone();
2211            }
2212            self.add_address_with_functions(addr, &selectors, true, targeted_contracts)?;
2213        }
2214
2215        if target_test_selectors.is_empty()
2216            && let Some(target) = targeted_contracts.get(&address)
2217        {
2218            // If test contract is marked as a target and no target selector explicitly set, then
2219            // include only state-changing functions that are not reserved and selectors that are
2220            // not explicitly excluded.
2221            let selectors: Vec<_> = target
2222                .abi
2223                .functions()
2224                .filter_map(|func| {
2225                    if matches!(
2226                        func.state_mutability,
2227                        alloy_json_abi::StateMutability::Pure
2228                            | alloy_json_abi::StateMutability::View
2229                    ) || func.is_reserved()
2230                        || excluded_test_selectors.contains(&func.selector())
2231                    {
2232                        None
2233                    } else {
2234                        Some(func.selector())
2235                    }
2236                })
2237                .collect();
2238            self.add_address_with_functions(address, &selectors, false, targeted_contracts)?;
2239        }
2240
2241        Ok(())
2242    }
2243
2244    /// Adds the address and fuzzed or excluded functions to `TargetedContracts`.
2245    fn add_address_with_functions(
2246        &self,
2247        address: Address,
2248        selectors: &[Selector],
2249        should_exclude: bool,
2250        targeted_contracts: &mut TargetedContracts,
2251    ) -> eyre::Result<()> {
2252        // Do not add address in target contracts if no function selected.
2253        if selectors.is_empty() {
2254            return Ok(());
2255        }
2256
2257        let contract = match targeted_contracts.entry(address) {
2258            Entry::Occupied(entry) => entry.into_mut(),
2259            Entry::Vacant(entry) => {
2260                let (identifier, abi) = self.setup_contracts.get(&address).ok_or_else(|| {
2261                    eyre::eyre!(
2262                        "[{}] address does not have an associated contract: {}",
2263                        if should_exclude { "excludeSelectors" } else { "targetSelectors" },
2264                        address
2265                    )
2266                })?;
2267                entry.insert(
2268                    TargetedContract::new(identifier.clone(), abi.clone())
2269                        .with_project_contracts(self.project_contracts),
2270                )
2271            }
2272        };
2273        contract.add_selectors(selectors.iter().copied(), should_exclude)?;
2274        Ok(())
2275    }
2276}
2277
2278/// Collects data from call for fuzzing. However, it first verifies that the sender is not an EOA
2279/// before inserting it into the dictionary. Otherwise, we flood the dictionary with
2280/// randomly generated addresses.
2281fn collect_data<FEN: FoundryEvmNetwork>(
2282    invariant_test: &InvariantTest,
2283    state_changeset: &PendingState,
2284    tx: &BasicTxDetails,
2285    call_result: &RawCallResult<FEN>,
2286    run_depth: u32,
2287) {
2288    // Collect values from fuzzed call result and add them to fuzz dictionary.
2289    invariant_test.fuzz_state.collect_values_from_call(
2290        &invariant_test.targeted_contracts,
2291        tx,
2292        &call_result.result,
2293        &call_result.logs,
2294        // Skip the EOA sender's own nonce and balance changes.
2295        state_changeset.account_changes().filter(|changes| {
2296            changes.address != tx.sender
2297                || changes.current.is_some_and(|info| !info.is_empty_code_hash())
2298        }),
2299        run_depth,
2300    );
2301
2302    // Inject typed sancov trace-cmp operands into the fuzz dictionary.
2303    if let Some(cmp_values) = &call_result.sancov_cmp_values {
2304        invariant_test.fuzz_state.collect_typed_cmp_values(
2305            cmp_values.iter().map(|s| (s.width, alloy_primitives::B256::from(s.value))),
2306        );
2307    }
2308}
2309
2310/// Maximum number of view calls made to harvest dictionary values after one invariant call.
2311const MAX_VIEW_CALLS_PER_TX: usize = 32;
2312
2313/// Calls the view functions of targeted contracts that the successful call accessed (read or
2314/// written), and adds their decoded results to the fuzz dictionary, whole structs included.
2315///
2316/// Eligible views take no inputs or only addresses, which are bound to the call's sender, so
2317/// values such as `balanceOf(sender)` or a getter's struct describe the state the next calls
2318/// act on. Calls run against the committed state without changing it; reverted calls are ignored.
2319///
2320/// At most [`MAX_VIEW_CALLS_PER_TX`] views are called. When more are eligible, `view_cursor`
2321/// starts each call's window where the previous one ended, so views past the first window are
2322/// reached too; with a stable set of eligible views, every one is called in turn.
2323fn collect_view_values<FEN: FoundryEvmNetwork>(
2324    invariant_test: &InvariantTest,
2325    executor: &Executor<FEN>,
2326    state_changeset: &PendingState,
2327    tx: &BasicTxDetails,
2328    run_depth: u32,
2329    view_cursor: &mut usize,
2330) {
2331    let calls = {
2332        let targets = invariant_test.targeted_contracts.targets();
2333        let mut candidates = targets
2334            .iter()
2335            .filter(|(address, _)| state_changeset.account_changes_for(address).is_some())
2336            .flat_map(|(address, contract)| {
2337                contract
2338                    .abi
2339                    .functions()
2340                    .filter(|function| is_harvestable_view(function))
2341                    .map(move |function| (*address, function))
2342            })
2343            .collect::<Vec<_>>();
2344        if candidates.len() > MAX_VIEW_CALLS_PER_TX {
2345            let start = *view_cursor % candidates.len();
2346            candidates.rotate_left(start);
2347            candidates.truncate(MAX_VIEW_CALLS_PER_TX);
2348            *view_cursor = start + MAX_VIEW_CALLS_PER_TX;
2349        }
2350        candidates
2351            .into_iter()
2352            .map(|(address, function)| (address, function.clone()))
2353            .collect::<Vec<_>>()
2354    };
2355
2356    for (address, function) in calls {
2357        let args = vec![DynSolValue::Address(tx.sender); function.inputs.len()];
2358        let Ok(calldata) = function.abi_encode_input(&args) else { continue };
2359        let Ok(call_result) = executor.call_raw_without_fuzz_instrumentation(
2360            tx.sender,
2361            address,
2362            calldata.into(),
2363            U256::ZERO,
2364        ) else {
2365            continue;
2366        };
2367        if !call_result.reverted {
2368            invariant_test.fuzz_state.collect_values_from_view(
2369                &function,
2370                &call_result.result,
2371                run_depth,
2372            );
2373        }
2374    }
2375}
2376
2377/// Returns whether a function is a view whose result can be harvested without fuzzed inputs.
2378fn is_harvestable_view(function: &Function) -> bool {
2379    matches!(function.state_mutability, StateMutability::View | StateMutability::Pure)
2380        && !function.outputs.is_empty()
2381        && function.inputs.iter().all(|input| input.ty == "address")
2382        && !function.name.starts_with("invariant")
2383        && !function.name.starts_with("target")
2384        && !function.name.starts_with("exclude")
2385}
2386
2387/// Calls the `afterInvariant()` function on a contract.
2388/// Returns call result and if call succeeded.
2389/// The state after the call is not persisted.
2390///
2391/// Uses the handler-gate success check so a stale committed `GLOBAL_FAIL_SLOT` from a
2392/// previously-recorded handler bug doesn't false-positive this call (the slot is `1` from
2393/// the prior bug, but `afterInvariant` itself didn't write it in this changeset).
2394pub(crate) fn call_after_invariant_function<FEN: FoundryEvmNetwork>(
2395    executor: &Executor<FEN>,
2396    to: Address,
2397) -> Result<(RawCallResult<FEN>, bool), EvmError<FEN>> {
2398    let calldata = Bytes::from_static(&IInvariantTest::afterInvariantCall::SELECTOR);
2399    let mut call_result =
2400        executor.call_raw_without_fuzz_instrumentation(CALLER, to, calldata, U256::ZERO)?;
2401    let success = executor.is_raw_call_mut_success_handler_gate(to, &mut call_result);
2402    Ok((call_result, success))
2403}
2404
2405/// Calls the invariant function and returns call result and if succeeded.
2406///
2407/// Uses the handler-gate success check (same rationale as `call_after_invariant_function`):
2408/// the predicate is broken iff this call's own changeset writes `GLOBAL_FAIL_SLOT` (via `t()` /
2409/// `vm.assert*`) or the call reverts; a stale committed slot from a prior handler bug must not
2410/// poison every later predicate evaluation in the run.
2411pub(crate) fn call_invariant_function<FEN: FoundryEvmNetwork>(
2412    executor: &Executor<FEN>,
2413    address: Address,
2414    calldata: Bytes,
2415) -> Result<(RawCallResult<FEN>, bool)> {
2416    let mut call_result =
2417        executor.call_raw_without_fuzz_instrumentation(CALLER, address, calldata, U256::ZERO)?;
2418    let success = executor.is_raw_call_mut_success_handler_gate(address, &mut call_result);
2419    Ok((call_result, success))
2420}
2421
2422/// Runs a failing campaign call again with `call` on a copy of `executor` that records its failure
2423/// identity and provenance. The campaign does not record them for every call, since that steps
2424/// their instructions.
2425///
2426/// Returns the provenance of the identified failure, for minimization to check that a replay
2427/// reached it. `None` without a shrink budget or when the failure is not identified, which
2428/// minimization handles alike.
2429pub(crate) fn failure_provenance<FEN: FoundryEvmNetwork>(
2430    executor: &Executor<FEN>,
2431    config: &InvariantConfig,
2432    call: impl FnOnce(&mut Executor<FEN>) -> Option<RawCallResult<FEN>>,
2433) -> Option<B256> {
2434    if config.shrink_run_limit == 0 {
2435        return None;
2436    }
2437    let mut executor = executor.clone();
2438    executor.inspector_mut().disable_fuzz_instrumentation();
2439    executor.inspector_mut().collect_failure_identity(true);
2440    executor.inspector_mut().collect_failure_provenance(true);
2441    let result = call(&mut executor).filter(|result| !result.execution_cancelled)?;
2442    result.failure_identity.and(result.failure_provenance)
2443}
2444
2445/// Executes an invariant replay fuzz call and returns the result.
2446///
2447/// This applies invariant replay semantics: warp/roll deltas are applied before the call and the
2448/// requested value is clamped to the sender balance. It is intended for invariant sequence replay,
2449/// shrinking, and artifact validation rather than as a general raw-call helper.
2450///
2451/// Applies any block timestamp (warp) and block number (roll) adjustments before the call.
2452pub fn execute_tx<FEN: FoundryEvmNetwork>(
2453    executor: &mut Executor<FEN>,
2454    tx: &BasicTxDetails,
2455) -> Result<RawCallResult<FEN>> {
2456    super::campaign::execute_invariant_tx(executor, &mut tx.clone())
2457}
2458
2459/// Executes an invariant replay call on a validation executor and registers created targets.
2460///
2461/// This uses live campaign acceptance and commit behavior while allowing callers to update
2462/// updatable target sets before validating later calls in the same artifact.
2463pub fn execute_tx_and_register_created<FEN: FoundryEvmNetwork>(
2464    executor: &mut Executor<FEN>,
2465    tx: &BasicTxDetails,
2466    targeted_contracts: &FuzzRunIdentifiedContracts,
2467    dynamic_target_ctx: &DynamicTargetCtx<'_>,
2468    created_contracts: &mut Vec<Address>,
2469) -> Result<()> {
2470    let call_result = execute_and_commit_tx(executor, tx)?;
2471    targeted_contracts.collect_created_contracts(
2472        call_result.state_changeset.account_changes(),
2473        dynamic_target_ctx.project_contracts,
2474        dynamic_target_ctx.setup_contracts,
2475        dynamic_target_ctx.artifact_filters,
2476        created_contracts,
2477    )?;
2478    Ok(())
2479}
2480
2481/// Executes and commits an invariant prefix call with campaign acceptance semantics.
2482pub fn execute_and_commit_tx<FEN: FoundryEvmNetwork>(
2483    executor: &mut Executor<FEN>,
2484    tx: &BasicTxDetails,
2485) -> Result<RawCallResult<FEN>> {
2486    let (kind, result) = super::campaign::execute_invariant_replay_tx(executor, tx)?;
2487    if kind == CampaignCallKind::AssumptionRejected {
2488        return Err(eyre!("invariant replay prefix rejected by vm.assume"));
2489    }
2490    Ok(result)
2491}
2492
2493/// Advances the executor's block by an invariant call's warp and roll delays, as the campaign
2494/// does before it executes the call.
2495pub fn apply_invariant_call_delay<FEN: FoundryEvmNetwork>(
2496    executor: &mut Executor<FEN>,
2497    tx: &BasicTxDetails,
2498) {
2499    super::campaign::apply_block_delay(
2500        executor,
2501        tx.warp.unwrap_or_default(),
2502        tx.roll.unwrap_or_default(),
2503    );
2504}
2505
2506#[cfg(test)]
2507mod tests {
2508
2509    use super::*;
2510    use crate::executors::ExecutorBuilder;
2511    use evm2::{bytecode::Bytecode, evm::InMemoryDB};
2512    use foundry_cheatcodes::CheatsConfig;
2513    use foundry_config::{FuzzCorpusMutationWeights, FuzzDictionaryConfig};
2514    use foundry_evm_core::evm::EthEvmNetwork;
2515    use foundry_evm_fuzz::CallDetails;
2516    use proptest::{
2517        prelude::any,
2518        strategy::{Strategy, ValueTree},
2519        test_runner::Config,
2520    };
2521    use serde_json::json;
2522    use std::{sync::mpsc, thread};
2523
2524    fn first_generated_u64(runner: &mut TestRunner) -> u64 {
2525        any::<u64>().new_tree(runner).unwrap().current()
2526    }
2527
2528    fn test_runner() -> TestRunner {
2529        TestRunner::new(Config { failure_persistence: None, ..Default::default() })
2530    }
2531
2532    fn seeded_test_runner(seed: U256) -> TestRunner {
2533        let config = Config { failure_persistence: None, ..Default::default() };
2534        let rng = TestRng::from_seed(RngAlgorithm::ChaCha, &seed.to_be_bytes::<32>());
2535        TestRunner::new_with_rng(config, rng)
2536    }
2537
2538    #[test]
2539    fn assumption_rejection_restores_delayed_block_environment() {
2540        let mut executor = crate::executors::test_executor(
2541            ExecutorBuilder::<EthEvmNetwork>::default()
2542                .inspectors(|stack| stack.cheatcodes(Arc::new(CheatsConfig::default())))
2543                .gas_limit(1 << 24),
2544            Default::default(),
2545        );
2546        let target = Address::repeat_byte(0x11);
2547        let mut code = vec![0x6e]; // PUSH15.
2548        code.extend_from_slice(MAGIC_ASSUME);
2549        code.extend_from_slice(&[0x60, 0x00, 0x52, 0x60, 0x0f, 0x60, 0x11, 0xf3]);
2550        executor.set_code(target, Bytecode::new_raw(Bytes::from(code))).unwrap();
2551
2552        let initial_block = executor.evm_env().block;
2553        let initial_cheatcode_block = executor.inspector().cheatcodes.as_ref().unwrap().block;
2554        let expected_timestamp = initial_block.timestamp + U256::from(10);
2555        let expected_number = initial_block.number + U256::from(5);
2556        let tx = BasicTxDetails {
2557            warp: Some(U256::from(10)),
2558            roll: Some(U256::from(5)),
2559            sender: Address::ZERO,
2560            call_details: CallDetails { target, calldata: Bytes::new(), value: None },
2561        };
2562        let mut state = (executor, tx);
2563        let campaign = FuzzCampaign::new(FuzzCampaignMode::Invariant {
2564            check_interval: 1,
2565            optimization: false,
2566        });
2567
2568        let outcome = campaign
2569            .run_sequence(
2570                &mut state,
2571                1,
2572                |state| (&mut state.0, &mut state.1),
2573                |_| 0,
2574                |_| false,
2575                |state, event| {
2576                    match event {
2577                        CampaignEvent::Feedback(_) => {
2578                            let block = &state.0.evm_env().block;
2579                            assert_eq!(block.timestamp, expected_timestamp);
2580                            assert_eq!(block.number, expected_number);
2581                            let block = state
2582                                .0
2583                                .inspector()
2584                                .cheatcodes
2585                                .as_ref()
2586                                .unwrap()
2587                                .block
2588                                .as_ref()
2589                                .unwrap();
2590                            assert_eq!(block.timestamp, expected_timestamp);
2591                            assert_eq!(block.number, expected_number);
2592                        }
2593                        CampaignEvent::Check { kind, .. } => {
2594                            assert_eq!(kind, CampaignCallKind::AssumptionRejected);
2595                            return Ok(CampaignControl::Stop);
2596                        }
2597                        _ => {}
2598                    }
2599                    Ok(CampaignControl::Continue)
2600                },
2601            )
2602            .unwrap();
2603
2604        assert_eq!(outcome, CampaignSequenceOutcome::Stopped);
2605        assert_eq!(state.0.evm_env().block, initial_block);
2606        assert_eq!(state.0.inspector().cheatcodes.as_ref().unwrap().block, initial_cheatcode_block);
2607
2608        let (kind, _) =
2609            crate::executors::campaign::execute_invariant_replay_tx(&mut state.0, &state.1)
2610                .unwrap();
2611        assert_eq!(kind, CampaignCallKind::AssumptionRejected);
2612        assert_eq!(state.0.evm_env().block, initial_block);
2613        assert_eq!(state.0.inspector().cheatcodes.as_ref().unwrap().block, initial_cheatcode_block);
2614    }
2615
2616    #[test]
2617    fn invariant_worker_runner_preserves_seed_for_master_worker() {
2618        let seed = U256::from(0x1234);
2619        let mut seeded_runner = seeded_test_runner(seed);
2620        let mut parent = test_runner();
2621        let mut worker = invariant_worker_runner(&mut parent, 0, Some(seed));
2622
2623        assert_eq!(first_generated_u64(&mut worker), first_generated_u64(&mut seeded_runner));
2624    }
2625
2626    #[test]
2627    fn invariant_worker_runner_uses_seed_independent_of_parent_rng_state() {
2628        let seed = U256::from(0x1234);
2629        let mut parent = test_runner();
2630        let mut advanced_parent = test_runner();
2631        let _ = first_generated_u64(&mut advanced_parent);
2632
2633        let mut worker = invariant_worker_runner(&mut parent, 1, Some(seed));
2634        let mut worker_from_advanced_parent =
2635            invariant_worker_runner(&mut advanced_parent, 1, Some(seed));
2636
2637        assert_eq!(
2638            first_generated_u64(&mut worker),
2639            first_generated_u64(&mut worker_from_advanced_parent)
2640        );
2641    }
2642
2643    #[test]
2644    fn invariant_progress_json_includes_throughput_fields() {
2645        let throughput = InvariantThroughputMetrics { total_txs: 2, total_gas: 50 };
2646
2647        let payload = build_invariant_progress_json(
2648            InvariantProgressContext {
2649                timestamp_secs: 123,
2650                contract_name: "InvariantContract",
2651                optimization_best: Some(I256::try_from(42).unwrap()),
2652                throughput,
2653                elapsed: Duration::from_secs(10),
2654                worker_id: 1,
2655                worker_count: 4,
2656                time_since_new_edge: Some(Duration::from_secs(3)),
2657            },
2658            &json!({ "corpus_count": 7 }),
2659            &InvariantFailureMetrics::default(),
2660        );
2661
2662        assert_eq!(payload["timestamp"], json!(123));
2663        assert_eq!(payload["contract"], json!("InvariantContract"));
2664        assert!(payload.get("invariant").is_none());
2665        assert_eq!(payload["metrics"]["corpus_count"], json!(7));
2666        assert_eq!(payload["metrics"]["broken_assertions"], json!(0));
2667        assert!(payload["metrics"].get("broken_handlers").is_none());
2668        assert_eq!(payload["total_txs"], json!(2));
2669        assert_eq!(payload["total_gas"], json!(50));
2670        assert_eq!(payload["tps"], json!(0.2));
2671        assert_eq!(payload["gps"], json!(5.0));
2672        assert!(payload.get("tx_per_sec").is_none());
2673        assert!(payload.get("gas_per_sec").is_none());
2674        assert_eq!(payload["worker"]["id"], json!(1));
2675        assert_eq!(payload["worker"]["count"], json!(4));
2676        assert_eq!(payload["optimization_best"], json!("42"));
2677    }
2678
2679    #[test]
2680    fn invariant_worker_count_keeps_short_campaigns_single_worker() {
2681        assert_eq!(
2682            max_invariant_workers_for_campaign(0, DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP),
2683            1
2684        );
2685        assert_eq!(
2686            max_invariant_workers_for_campaign(
2687                MIN_RUNS_PER_INVARIANT_WORKER - 1,
2688                DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP
2689            ),
2690            1
2691        );
2692        assert_eq!(
2693            max_invariant_workers_for_campaign(
2694                MIN_RUNS_PER_INVARIANT_WORKER,
2695                DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP
2696            ),
2697            1
2698        );
2699        assert_eq!(
2700            max_invariant_workers_for_campaign(
2701                MIN_RUNS_PER_INVARIANT_WORKER * 2,
2702                DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP
2703            ),
2704            2
2705        );
2706        assert_eq!(max_invariant_workers_for_campaign(256, 100_000), 5);
2707    }
2708
2709    #[test]
2710    fn invariant_run_depth_random_min_depth_zero_never_returns_zero() {
2711        let mut runner = test_runner();
2712        let config = InvariantConfig {
2713            depth: 8,
2714            min_depth: 0,
2715            depth_mode: InvariantDepthMode::Random,
2716            ..Default::default()
2717        };
2718
2719        for _ in 0..128 {
2720            assert!((1..=8).contains(&invariant_run_depth(&config, &mut runner)));
2721        }
2722    }
2723
2724    #[test]
2725    fn invariant_run_depth_fixed_zero_preserves_zero() {
2726        let mut runner = test_runner();
2727        let config = InvariantConfig {
2728            depth: 0,
2729            depth_mode: InvariantDepthMode::Fixed,
2730            ..Default::default()
2731        };
2732
2733        assert_eq!(invariant_run_depth(&config, &mut runner), 0);
2734    }
2735
2736    #[test]
2737    fn invariant_worker_config_keeps_single_worker_default() {
2738        let config = InvariantConfig::default();
2739
2740        assert_eq!(
2741            invariant_worker_config(config, 0, 1).corpus.corpus_random_sequence_weight,
2742            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2743        );
2744    }
2745
2746    #[test]
2747    fn invariant_worker_config_uses_one_exploratory_worker_with_default_config() {
2748        let config = InvariantConfig::default();
2749
2750        assert_eq!(
2751            invariant_worker_config(config.clone(), 0, 4).corpus.corpus_random_sequence_weight,
2752            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2753        );
2754        assert_eq!(
2755            invariant_worker_config(config.clone(), 1, 4).corpus.corpus_random_sequence_weight,
2756            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2757        );
2758        assert_eq!(
2759            invariant_worker_config(config.clone(), 2, 4).corpus.corpus_random_sequence_weight,
2760            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2761        );
2762        assert_eq!(
2763            invariant_worker_config(config, 3, 4).corpus.corpus_random_sequence_weight,
2764            FuzzCorpusConfig::ENSEMBLE_CORPUS_RANDOM_SEQUENCE_WEIGHT
2765        );
2766    }
2767
2768    #[test]
2769    fn invariant_worker_config_keeps_two_worker_campaign_on_default() {
2770        let config = InvariantConfig::default();
2771
2772        assert_eq!(
2773            invariant_worker_config(config.clone(), 0, 2).corpus.corpus_random_sequence_weight,
2774            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2775        );
2776        assert_eq!(
2777            invariant_worker_config(config, 1, 2).corpus.corpus_random_sequence_weight,
2778            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2779        );
2780    }
2781
2782    #[test]
2783    fn invariant_worker_config_uses_last_worker_for_three_worker_campaign() {
2784        let config = InvariantConfig::default();
2785
2786        assert_eq!(
2787            invariant_worker_config(config.clone(), 0, 3).corpus.corpus_random_sequence_weight,
2788            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2789        );
2790        assert_eq!(
2791            invariant_worker_config(config.clone(), 1, 3).corpus.corpus_random_sequence_weight,
2792            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2793        );
2794        assert_eq!(
2795            invariant_worker_config(config, 2, 3).corpus.corpus_random_sequence_weight,
2796            FuzzCorpusConfig::ENSEMBLE_CORPUS_RANDOM_SEQUENCE_WEIGHT
2797        );
2798    }
2799
2800    #[test]
2801    fn invariant_worker_config_preserves_explicit_corpus_random_sequence_weight() {
2802        let config = InvariantConfig {
2803            corpus: FuzzCorpusConfig {
2804                corpus_random_sequence_weight: 25,
2805                ..FuzzCorpusConfig::default()
2806            },
2807            corpus_random_sequence_weight_configured: true,
2808            ..InvariantConfig::default()
2809        };
2810
2811        assert_eq!(
2812            invariant_worker_config(config.clone(), 1, 4).corpus.corpus_random_sequence_weight,
2813            25
2814        );
2815        assert_eq!(invariant_worker_config(config, 0, 1).corpus.corpus_random_sequence_weight, 25);
2816
2817        let config = InvariantConfig {
2818            corpus_random_sequence_weight_configured: true,
2819            ..InvariantConfig::default()
2820        };
2821
2822        assert_eq!(
2823            invariant_worker_config(config, 1, 4).corpus.corpus_random_sequence_weight,
2824            FuzzCorpusConfig::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT
2825        );
2826    }
2827
2828    #[test]
2829    fn invariant_worker_count_preserves_fixed_workers() {
2830        let mut config = InvariantConfig {
2831            runs: MIN_RUNS_PER_INVARIANT_WORKER * 4,
2832            workers: foundry_config::InvariantWorkers::Fixed(
2833                std::num::NonZeroUsize::new(4).unwrap(),
2834            ),
2835            ..Default::default()
2836        };
2837        assert_eq!(invariant_worker_count_with_threads(&config, 8, 1), 4);
2838
2839        config.corpus.show_edge_coverage = true;
2840        assert_eq!(invariant_worker_count_with_threads(&config, 8, 1), 4);
2841
2842        config.corpus.show_edge_coverage = false;
2843        config.corpus.corpus_dir = Some(std::path::PathBuf::from("corpus"));
2844        assert_eq!(invariant_worker_count_with_threads(&config, 8, 1), 4);
2845
2846        config.runs = MIN_RUNS_PER_INVARIANT_WORKER - 1;
2847        config.timeout = None;
2848        assert_eq!(invariant_worker_count_with_threads(&config, 8, 1), 4);
2849
2850        config.timeout = Some(1);
2851        assert_eq!(invariant_worker_count_with_threads(&config, 8, 4), 4);
2852    }
2853
2854    #[test]
2855    fn invariant_worker_count_does_not_cap_configured_workers_by_available_threads() {
2856        let config = InvariantConfig {
2857            runs: MIN_RUNS_PER_INVARIANT_WORKER * 8,
2858            workers: foundry_config::InvariantWorkers::Fixed(
2859                std::num::NonZeroUsize::new(8).unwrap(),
2860            ),
2861            ..Default::default()
2862        };
2863
2864        assert_eq!(invariant_worker_count_with_threads(&config, 4, 1), 8);
2865    }
2866
2867    #[test]
2868    fn invariant_worker_count_splits_available_threads_for_auto_workers() {
2869        let mut config = InvariantConfig {
2870            runs: MIN_RUNS_PER_INVARIANT_WORKER * 4,
2871            depth: DEFAULT_DEPTH_FOR_INVARIANT_WORKER_CAP,
2872            workers: foundry_config::InvariantWorkers::Auto,
2873            ..Default::default()
2874        };
2875
2876        assert_eq!(invariant_worker_count_with_threads(&config, 4, 1), 4);
2877        assert_eq!(invariant_worker_count_with_threads(&config, 8, 2), 4);
2878        assert_eq!(invariant_worker_count_with_threads(&config, 8, 3), 2);
2879        assert_eq!(invariant_worker_count_with_threads(&config, 3, 8), 1);
2880        assert_eq!(invariant_worker_count_with_threads(&config, 0, 0), 1);
2881
2882        config.runs = MIN_RUNS_PER_INVARIANT_WORKER - 1;
2883        assert_eq!(invariant_worker_count_with_threads(&config, 8, 2), 1);
2884
2885        config.depth = 100_000;
2886        assert_eq!(invariant_worker_count_with_threads(&config, 8, 2), 4);
2887
2888        config.timeout = Some(1);
2889        assert_eq!(invariant_worker_count_with_threads(&config, 8, 2), 4);
2890    }
2891
2892    fn function(signature: &str) -> Function {
2893        Function::parse(signature).unwrap()
2894    }
2895
2896    fn targeted_contract(identifier: &str, functions: Vec<Function>) -> TargetedContract {
2897        let mut abi = alloy_json_abi::JsonAbi::new();
2898        for function in functions {
2899            abi.functions.entry(function.name.clone()).or_default().push(function);
2900        }
2901        TargetedContract::new(identifier.to_string(), abi)
2902    }
2903
2904    #[test]
2905    fn campaign_terminal_stop_interrupts_handler_without_accepting_run() {
2906        const GAS_LIMIT: u64 = 1 << 24;
2907        let invariant_address = Address::repeat_byte(0x11);
2908        let handler_address = Address::repeat_byte(0x22);
2909        let mut executor = crate::executors::test_executor(
2910            ExecutorBuilder::<EthEvmNetwork>::default().gas_limit(GAS_LIMIT),
2911            Default::default(),
2912        );
2913        // Return ABI-encoded `true` for the invariant predicate.
2914        executor
2915            .set_code(
2916                invariant_address,
2917                Bytecode::new_raw(Bytes::from_static(&[
2918                    0x60, 0x01, 0x60, 0x00, 0x52, 0x60, 0x20, 0x60, 0x00, 0xf3,
2919                ])),
2920            )
2921            .unwrap();
2922        // JUMPDEST; PUSH1 0; JUMP loops until the campaign stop reaches the inspector.
2923        executor
2924            .set_code(
2925                handler_address,
2926                Bytecode::new_raw(Bytes::from_static(&[0x5b, 0x60, 0x00, 0x56])),
2927            )
2928            .unwrap();
2929
2930        let (handler_entered_tx, handler_entered_rx) = mpsc::channel();
2931        let (handler_release_tx, handler_release_rx) = mpsc::channel();
2932        executor.inspector_mut().set_early_exit_test_gate(
2933            handler_entered_tx,
2934            handler_release_rx,
2935            0,
2936        );
2937
2938        let invariant = function("invariant_ok() view returns (bool)");
2939        let mut invariant_abi = alloy_json_abi::JsonAbi::new();
2940        invariant_abi.functions.entry(invariant.name.clone()).or_default().push(invariant.clone());
2941        let invariant_contract = InvariantContract::new(
2942            invariant_address,
2943            "InvariantTest",
2944            vec![(&invariant, false)],
2945            0,
2946            false,
2947            &invariant_abi,
2948        );
2949
2950        let handler = function("loopForever()");
2951        let mut handler_contract = targeted_contract("Handler", vec![handler.clone()]);
2952        handler_contract.targeted_functions = vec![handler];
2953        let mut targeted_contracts = TargetedContracts::new();
2954        targeted_contracts.insert(handler_address, handler_contract);
2955        let campaign_seed = InvariantCampaignSeed {
2956            artifact_filters: ArtifactFilters::default(),
2957            sender_filters: SenderFilters::new(vec![CALLER], Vec::new()),
2958            targeted_contracts,
2959            targets_are_updatable: false,
2960            initial_handler_failures: Map::default(),
2961        };
2962
2963        let config =
2964            InvariantConfig { runs: 1, depth: 1, show_metrics: false, ..Default::default() };
2965        let campaign_state = InvariantCampaignState::new(EarlyExit::new(false), None);
2966        let fuzz_state =
2967            EvmFuzzState::new(&[], &InMemoryDB::default(), FuzzDictionaryConfig::default(), None);
2968        let setup_contracts = ContractsByAddress::default();
2969        let project_contracts = ContractsByArtifact::default();
2970        let (result_tx, result_rx) = mpsc::channel();
2971
2972        let (handler_entered, result) = thread::scope(|scope| {
2973            let handle = scope.spawn(|| {
2974                let result = InvariantExecutor::<EthEvmNetwork>::run_invariant_worker(
2975                    executor,
2976                    test_runner(),
2977                    config,
2978                    &setup_contracts,
2979                    &project_contracts,
2980                    InvariantWorkerPlan { worker_id: 0, first_global_run: 0, runs: 1 },
2981                    invariant_contract,
2982                    &FuzzFixtures::default(),
2983                    fuzz_state,
2984                    None,
2985                    &campaign_state,
2986                    campaign_seed,
2987                    WorkerCorpusSeed::default(),
2988                    1,
2989                    1,
2990                );
2991                let _ = result_tx.send(result);
2992            });
2993
2994            let handler_entered = handler_entered_rx.recv_timeout(Duration::from_secs(1)).is_ok();
2995            campaign_state.request_terminal_stop();
2996            let _ = handler_release_tx.send(());
2997
2998            let result = result_rx.recv_timeout(Duration::from_secs(1));
2999            handle.join().unwrap();
3000            (handler_entered, result)
3001        });
3002        assert!(handler_entered, "invariant handler did not begin EVM execution");
3003        let (output, _) = result.expect("invariant campaign did not observe early exit").unwrap();
3004        assert_eq!(output.result.runs, 0);
3005        assert_eq!(output.result.calls, 0);
3006        assert_eq!(campaign_state.total_runs(), 0);
3007        assert_eq!(campaign_state.throughput_totals(), (0, 0));
3008        assert!(output.result.errors.is_empty());
3009        assert!(output.result.handler_errors.is_empty());
3010        assert!(output.result.last_run_inputs.is_empty());
3011        assert!(output.result.line_coverage.is_none());
3012        assert!(output.result.metrics.is_empty());
3013        assert!(output.result.optimization_best_value.is_none());
3014    }
3015
3016    #[test]
3017    fn invariant_worker_cmp_log_selection_uses_one_worker_per_campaign() {
3018        let mut config = InvariantConfig::default();
3019        assert!(!invariant_worker_collects_evm_cmp_log(&config, 0, 1));
3020
3021        config.corpus.corpus_dir = Some("corpus".into());
3022        assert!(invariant_worker_collects_evm_cmp_log(&config, 0, 1));
3023        assert!(invariant_worker_collects_evm_cmp_log(&config, 0, 4));
3024        assert!(!invariant_worker_collects_evm_cmp_log(&config, 1, 4));
3025        assert!(!invariant_worker_collects_evm_cmp_log(&config, 3, 4));
3026
3027        config.corpus.mutation_weights = FuzzCorpusMutationWeights {
3028            mutation_weight_splice: 1,
3029            mutation_weight_repeat: 1,
3030            mutation_weight_interleave: 1,
3031            mutation_weight_prefix: 1,
3032            mutation_weight_suffix: 1,
3033            mutation_weight_abi: 1,
3034            mutation_weight_cmp: 0,
3035        };
3036        assert!(!invariant_worker_collects_evm_cmp_log(&config, 0, 1));
3037
3038        // All-zero configured weights resolve to the default mutation distribution.
3039        config.corpus.mutation_weights = FuzzCorpusMutationWeights {
3040            mutation_weight_splice: 0,
3041            mutation_weight_repeat: 0,
3042            mutation_weight_interleave: 0,
3043            mutation_weight_prefix: 0,
3044            mutation_weight_suffix: 0,
3045            mutation_weight_abi: 0,
3046            mutation_weight_cmp: 0,
3047        };
3048        assert!(invariant_worker_collects_evm_cmp_log(&config, 0, 1));
3049
3050        config.corpus.sancov_edges = true;
3051        assert!(!invariant_worker_collects_evm_cmp_log(&config, 0, 1));
3052        assert!(!invariant_worker_collects_evm_cmp_log(&config, 0, 4));
3053    }
3054
3055    #[test]
3056    fn timed_invariant_workers_are_not_bounded_by_assigned_runs() {
3057        let plan = InvariantWorkerPlan { worker_id: 0, first_global_run: 0, runs: 1 };
3058
3059        let untimed = InvariantCampaignState::new(EarlyExit::new(false), None);
3060        assert!(should_continue_invariant_worker(&untimed, 0, plan));
3061        assert!(!should_continue_invariant_worker(&untimed, 1, plan));
3062
3063        let timed = InvariantCampaignState::new(EarlyExit::new(false), Some(60));
3064        assert!(should_continue_invariant_worker(&timed, 0, plan));
3065        assert!(should_continue_invariant_worker(&timed, 1, plan));
3066        assert!(should_continue_invariant_worker(&timed, 10_000, plan));
3067    }
3068
3069    #[test]
3070    fn gas_report_samples_are_split_across_workers() {
3071        assert_eq!(gas_report_samples_for_worker(0, 0, 4), 0);
3072        assert_eq!(gas_report_samples_for_worker(8, 0, 4), 2);
3073        assert_eq!(gas_report_samples_for_worker(8, 3, 4), 2);
3074        assert_eq!(gas_report_samples_for_worker(10, 0, 4), 3);
3075        assert_eq!(gas_report_samples_for_worker(10, 1, 4), 3);
3076        assert_eq!(gas_report_samples_for_worker(10, 2, 4), 2);
3077        assert_eq!(gas_report_samples_for_worker(10, 3, 4), 2);
3078        assert_eq!(gas_report_samples_for_worker(3, 3, 4), 0);
3079    }
3080
3081    #[test]
3082    fn invariant_progress_json_zero_elapsed_reports_zero_rates() {
3083        let throughput = InvariantThroughputMetrics { total_txs: 1, total_gas: 21_000 };
3084
3085        let payload = build_invariant_progress_json(
3086            InvariantProgressContext {
3087                timestamp_secs: 456,
3088                contract_name: "invariant_zero_elapsed",
3089                optimization_best: None,
3090                throughput,
3091                elapsed: Duration::ZERO,
3092                worker_id: 0,
3093                worker_count: 1,
3094                time_since_new_edge: None,
3095            },
3096            &json!({ "corpus_count": 1 }),
3097            &InvariantFailureMetrics::default(),
3098        );
3099
3100        assert_eq!(payload["tps"], json!(0.0));
3101        assert_eq!(payload["gps"], json!(0.0));
3102        assert!(payload.get("optimization_best").is_none());
3103        // No edge seen yet -> `null`.
3104        assert_eq!(payload["worker"]["secs_since_new_edge"], json!(null));
3105    }
3106
3107    #[test]
3108    fn invariant_progress_json_reports_secs_since_new_edge() {
3109        let payload = build_invariant_progress_json(
3110            InvariantProgressContext {
3111                timestamp_secs: 1,
3112                contract_name: "TestContract",
3113                optimization_best: None,
3114                throughput: InvariantThroughputMetrics::default(),
3115                elapsed: Duration::from_secs(1),
3116                worker_id: 2,
3117                worker_count: 4,
3118                time_since_new_edge: Some(Duration::from_millis(1500)),
3119            },
3120            &json!({ "corpus_count": 1 }),
3121            &InvariantFailureMetrics::default(),
3122        );
3123
3124        assert_eq!(payload["worker"]["id"], json!(2));
3125        assert_eq!(payload["worker"]["secs_since_new_edge"], json!(1.5));
3126    }
3127
3128    #[test]
3129    fn invariant_progress_json_rounds_fractional_rates() {
3130        let payload = build_invariant_progress_json(
3131            InvariantProgressContext {
3132                timestamp_secs: 456,
3133                contract_name: "TestContract",
3134                optimization_best: None,
3135                throughput: InvariantThroughputMetrics { total_txs: 1, total_gas: 1 },
3136                elapsed: Duration::from_secs(3),
3137                worker_id: 0,
3138                worker_count: 1,
3139                time_since_new_edge: None,
3140            },
3141            &json!({ "corpus_count": 1 }),
3142            &InvariantFailureMetrics::default(),
3143        );
3144
3145        assert_eq!(payload["tps"], json!(0.33));
3146        assert_eq!(payload["gps"], json!(0.33));
3147    }
3148
3149    #[test]
3150    fn invariant_progress_json_includes_broken_counts() {
3151        let mut failure_metrics = InvariantFailureMetrics::default();
3152        failure_metrics.record_failure("invariant_a", "TestContract", "revert");
3153        failure_metrics.record_failure("invariant_a", "TestContract", "revert");
3154        failure_metrics.record_failure("invariant_b", "TestContract", "assertion failed");
3155        failure_metrics.broken_handlers = 7;
3156
3157        let payload = build_invariant_progress_json(
3158            InvariantProgressContext {
3159                timestamp_secs: 789,
3160                contract_name: "TestContract",
3161                optimization_best: None,
3162                throughput: InvariantThroughputMetrics::default(),
3163                elapsed: Duration::from_secs(1),
3164                worker_id: 0,
3165                worker_count: 1,
3166                time_since_new_edge: None,
3167            },
3168            &json!({ "corpus_count": 5 }),
3169            &failure_metrics,
3170        );
3171
3172        assert!(payload["metrics"].get("failures").is_none());
3173        assert!(payload["metrics"].get("unique_failures").is_none());
3174        assert_eq!(payload["metrics"]["broken_invariants"], json!(2));
3175        assert_eq!(payload["metrics"]["broken_assertions"], json!(7));
3176        assert!(payload["metrics"].get("broken_handlers").is_none());
3177    }
3178
3179    #[test]
3180    fn handler_assertion_failure_event_includes_site_and_reason() {
3181        let target = Address::repeat_byte(0x11);
3182        let selector = Selector::from([0xde, 0xad, 0xbe, 0xef]);
3183
3184        assert_eq!(
3185            build_handler_failure_event(123, target, selector, "assertion failed"),
3186            json!({
3187                "timestamp": 123,
3188                "event": "failure",
3189                "failure_type": "handler_assertion",
3190                "target": target,
3191                "selector": "0xdeadbeef",
3192                "reason": "assertion failed",
3193            })
3194        );
3195    }
3196
3197    #[test]
3198    fn failure_metrics_tracks_total_and_unique_failures() {
3199        let mut metrics = InvariantFailureMetrics::default();
3200        metrics.record_failure("invariant_a", "TestContract", "revert");
3201        metrics.record_failure("invariant_a", "TestContract", "revert");
3202        metrics.record_failure("invariant_b", "TestContract", "assertion failed");
3203
3204        assert_eq!(metrics.failures, 3);
3205        assert_eq!(metrics.unique_failures.len(), 2);
3206        assert!(metrics.unique_failures.contains("invariant_a"));
3207        assert!(metrics.unique_failures.contains("invariant_b"));
3208    }
3209
3210    #[test]
3211    fn failure_metrics_default_is_zero() {
3212        let metrics = InvariantFailureMetrics::default();
3213        assert_eq!(metrics.failures, 0);
3214        assert!(metrics.unique_failures.is_empty());
3215        assert_eq!(metrics.broken_handlers, 0);
3216    }
3217}