Skip to main content

foundry_evm_symbolic/runtime/solver/
mod.rs

1//! Solver orchestration, query scheduling, caching, and model validation.
2
3use super::*;
4use std::{
5    io::{BufRead, BufReader, Read},
6    process::{Child, ChildStdin, Output},
7    sync::mpsc::{Receiver, RecvTimeoutError},
8    thread::JoinHandle,
9};
10use wait_timeout::ChildExt;
11
12mod fallback;
13mod normalize;
14mod reasoning;
15mod smt;
16
17use fallback::{checked_mul_guard_branch_model, hard_arith_fallback_first_vars};
18use normalize::{
19    NormalizationCache, constraints_are_directly_unsat, normalize_constraints_for_solver_cached,
20    sorted_bool_exprs_are_subset,
21};
22use reasoning::{
23    CheckedXorResult, checked_xor_result, product_monotonic_unsat_normalized,
24    remove_implied_monotonic_constraints,
25};
26use smt::write_smt_assertions;
27
28pub(crate) use fallback::{
29    fallback_bounded_model, fallback_single_var_model, hard_arith_fallback_model,
30};
31
32const Z3_QUERY_END: &str = "foundry-query-complete";
33
34/// Errors that arise when parsing or constructing solver commands from configuration.
35#[derive(Debug, thiserror::Error)]
36pub(crate) enum SolverConfigError {
37    /// The command string parsed to an empty argv.
38    #[error("symbolic solver command is empty")]
39    EmptyCommand,
40    /// The command string contains invalid shell quoting.
41    #[error("invalid shell quoting in symbolic solver command")]
42    InvalidShellQuoting,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub(crate) enum SolverOutcome {
47    Cancelled,
48    Error,
49    NotStarted,
50    SatAfterWinner,
51    SatInvalid,
52    SatValid,
53    TimeoutOrUnknown,
54    Unknown,
55    UnknownAfterWinner,
56    Unsat,
57    UnsatAfterWinner,
58    Unexpected,
59}
60
61impl fmt::Display for SolverOutcome {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(match self {
64            Self::Cancelled => "cancelled",
65            Self::Error => "error",
66            Self::NotStarted => "not-started",
67            Self::SatAfterWinner => "sat-after-winner",
68            Self::SatInvalid => "sat-invalid",
69            Self::SatValid => "sat-valid",
70            Self::TimeoutOrUnknown => "timeout-or-unknown",
71            Self::Unknown => "unknown",
72            Self::UnknownAfterWinner => "unknown-after-winner",
73            Self::Unsat => "unsat",
74            Self::UnsatAfterWinner => "unsat-after-winner",
75            Self::Unexpected => "unexpected",
76        })
77    }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub(crate) enum BranchFeasibility {
82    Sat,
83    Unsat,
84    NeedsSolver,
85}
86
87impl BranchFeasibility {
88    const fn into_result(self) -> Result<bool, SymbolicError> {
89        match self {
90            Self::Sat => Ok(true),
91            Self::Unsat => Ok(false),
92            Self::NeedsSolver => Err(SymbolicError::SolverUnknown),
93        }
94    }
95}
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub(crate) struct SolverCommand {
98    program: String,
99    args: Vec<String>,
100    display: String,
101    smt_timeout: bool,
102}
103
104impl SolverCommand {
105    /// Constructs a solver command from a program plus arguments.
106    pub(crate) fn new(parts: Vec<String>, smt_timeout: bool) -> Result<Self, SolverConfigError> {
107        let mut parts = parts.into_iter();
108        let Some(program) = parts.next().filter(|part| !part.is_empty()) else {
109            return Err(SolverConfigError::EmptyCommand);
110        };
111        let args = parts.collect::<Vec<_>>();
112        let display = std::iter::once(program.as_str())
113            .chain(args.iter().map(String::as_str))
114            .collect::<Vec<_>>()
115            .join(" ");
116        Ok(Self { program, args, display, smt_timeout })
117    }
118}
119
120pub(crate) struct SmtLibSubprocessSolver {
121    commands: Result<Vec<SolverCommand>, SolverConfigError>,
122    timeout: Option<u32>,
123    max_queries: usize,
124    queries: usize,
125    dump_smt: bool,
126    portfolio_scheduler: PortfolioScheduler,
127    heuristic_witnesses: usize,
128    replayable_storage: SymbolicVars,
129    normalization_cache: NormalizationCache,
130    sat_cache: HashMap<Vec<SymBoolExpr>, bool>,
131    model_cache: HashMap<Vec<SymBoolExpr>, SymbolicModel>,
132    sat_queries: usize,
133    model_queries: usize,
134    sat_cache_hits: usize,
135    model_cache_hits: usize,
136    smt_queries: usize,
137    solver_time: Duration,
138    smt_input_bytes: u64,
139    smt_max_query_bytes: u64,
140    smt_build_time: Duration,
141    smt_max_query_time: Duration,
142    z3_session: Option<Z3Session>,
143}
144
145impl SmtLibSubprocessSolver {
146    /// Constructs a subprocess solver from Foundry symbolic config.
147    pub(crate) fn from_config(config: &SymbolicConfig) -> Self {
148        Self {
149            commands: solver_commands_for_config(config),
150            timeout: config.timeout,
151            max_queries: config.max_solver_queries as usize,
152            queries: 0,
153            dump_smt: config.dump_smt,
154            portfolio_scheduler: PortfolioScheduler::default(),
155            heuristic_witnesses: 0,
156            replayable_storage: SymbolicVars::default(),
157            normalization_cache: NormalizationCache::default(),
158            sat_cache: HashMap::default(),
159            model_cache: HashMap::default(),
160            sat_queries: 0,
161            model_queries: 0,
162            sat_cache_hits: 0,
163            model_cache_hits: 0,
164            smt_queries: 0,
165            solver_time: Duration::ZERO,
166            smt_input_bytes: 0,
167            smt_max_query_bytes: 0,
168            smt_build_time: Duration::ZERO,
169            smt_max_query_time: Duration::ZERO,
170            z3_session: None,
171        }
172    }
173
174    /// Returns solver counters collected by this backend.
175    pub(crate) fn stats(&self) -> SymbolicStats {
176        SymbolicStats {
177            paths: 0,
178            solver_queries: self.queries,
179            smt_queries: self.smt_queries,
180            sat_queries: self.sat_queries,
181            model_queries: self.model_queries,
182            sat_cache_hits: self.sat_cache_hits,
183            model_cache_hits: self.model_cache_hits,
184            heuristic_witnesses: self.heuristic_witnesses,
185            solver_time_ms: self.solver_time.as_millis().try_into().unwrap_or(u64::MAX),
186            smt_input_bytes: self.smt_input_bytes,
187            smt_max_query_bytes: self.smt_max_query_bytes,
188            smt_build_time_ms: self.smt_build_time.as_millis().try_into().unwrap_or(u64::MAX),
189            smt_max_query_time_ms: self
190                .smt_max_query_time
191                .as_millis()
192                .try_into()
193                .unwrap_or(u64::MAX),
194        }
195    }
196
197    /// Clears cached expression keys tied to a previous symbolic context.
198    pub(crate) fn clear_context_caches(&mut self) {
199        self.normalization_cache.clear();
200        self.sat_cache.clear();
201        self.model_cache.clear();
202    }
203
204    /// Verifies that a configured solver can be invoked before exploration starts.
205    pub(crate) fn check_available(&self) -> Result<(), SymbolicError> {
206        let commands = self.commands()?;
207        let mut errors = Vec::new();
208        // Availability must not strand a joined live worker before exploration can check its
209        // deadline. Share one budget across the portfolio and discard unneeded version output.
210        let seconds = self.timeout.filter(|seconds| *seconds > 0).unwrap_or(30);
211        let deadline = Instant::now() + Duration::from_secs(seconds.into());
212        for command in commands {
213            let mut child = match Command::new(&command.program)
214                .arg("--version")
215                .stdin(Stdio::null())
216                .stdout(Stdio::null())
217                .stderr(Stdio::null())
218                .spawn()
219            {
220                Ok(child) => SolverChild::new(child),
221                Err(err) => {
222                    errors.push(format!("failed to execute `{}`: {err}", command.program));
223                    continue;
224                }
225            };
226            match child.child_mut().wait_timeout(deadline.saturating_duration_since(Instant::now()))
227            {
228                Ok(Some(status)) if status.success() => return Ok(()),
229                Ok(Some(_)) => errors
230                    .push(format!("`{}` is not a usable SMT solver executable", command.program)),
231                Ok(None) => return Err(SymbolicError::Timeout(seconds)),
232                Err(err) => errors.push(format!("failed to wait for `{}`: {err}", command.program)),
233            }
234        }
235        Err(SymbolicError::Solver(errors.join("; ")))
236    }
237
238    /// Returns satisfiability with path-local storage symbols that concrete replay can set.
239    pub(crate) fn is_sat_with_replayable_storage(
240        &mut self,
241        cx: &mut SymCx,
242        constraints: &[SymBoolExpr],
243        replayable_storage: &SymbolicVars,
244    ) -> Result<bool, SymbolicError> {
245        self.with_replayable_storage(replayable_storage, |solver| {
246            solver.is_sat_inner(cx, constraints, false).and_then(BranchFeasibility::into_result)
247        })
248    }
249
250    /// Returns branch feasibility with path-local storage symbols concrete replay can set.
251    pub(crate) fn branch_feasibility_with_replayable_storage(
252        &mut self,
253        cx: &mut SymCx,
254        constraints: &[SymBoolExpr],
255        replayable_storage: &SymbolicVars,
256    ) -> Result<BranchFeasibility, SymbolicError> {
257        self.with_replayable_storage(replayable_storage, |solver| {
258            solver.is_sat_inner(cx, constraints, true)
259        })
260    }
261
262    /// Returns a model with path-local storage symbols that concrete replay can set.
263    pub(crate) fn model_with_replayable_storage(
264        &mut self,
265        cx: &mut SymCx,
266        constraints: &[SymBoolExpr],
267        replayable_storage: &SymbolicVars,
268    ) -> Result<SymbolicModel, SymbolicError> {
269        self.with_replayable_storage(replayable_storage, |solver| solver.model(cx, constraints))
270    }
271
272    fn with_replayable_storage<T>(
273        &mut self,
274        replayable_storage: &SymbolicVars,
275        operation: impl FnOnce(&mut Self) -> T,
276    ) -> T {
277        let previous = std::mem::replace(&mut self.replayable_storage, replayable_storage.clone());
278        let result = operation(self);
279        self.replayable_storage = previous;
280        result
281    }
282
283    /// Returns variable assignments used to materialize inputs for concrete replay.
284    pub(crate) fn model(
285        &mut self,
286        cx: &mut SymCx,
287        constraints: &[SymBoolExpr],
288    ) -> Result<SymbolicModel, SymbolicError> {
289        // Local witnesses may decide the feasibility of gas-dependent branches, but a model assigns
290        // `gasleft()` a concrete value the engine cannot replay faithfully, so fail closed here.
291        if constraints.iter().any(SymBoolExpr::contains_gasleft) {
292            return Err(SymbolicError::Unsupported("GAS/gasleft() not modeled"));
293        }
294        self.model_queries += 1;
295        let smt_constraints =
296            normalize_constraints_for_solver_cached(cx, constraints, &mut self.normalization_cache);
297        let cache_key = smt_constraints.clone();
298
299        if self.sat_cache.get(&cache_key) == Some(&false) {
300            self.model_cache.remove(&cache_key);
301            trace!("model: normalized sat cache says unsat");
302            return Err(SymbolicError::Solver("counterexample path became unsat".to_string()));
303        }
304        if self.has_cached_unsat_subset(&cache_key) {
305            self.cache_sat_result(cache_key.clone(), false);
306            self.model_cache.remove(&cache_key);
307            trace!("model: normalized unsat subset cache hit");
308            return Err(SymbolicError::Solver("counterexample path became unsat".to_string()));
309        }
310
311        if let Some(model) = self.model_cache.get(&cache_key) {
312            if eval_model_constraints(constraints, model) {
313                let model = model.clone();
314                self.model_cache_hits += 1;
315                trace!("model: normalized cache hit");
316                self.cache_sat_result(cache_key.clone(), true);
317                return Ok(model);
318            }
319            trace!("model: normalized cache hit failed validation");
320        }
321        if self.model_cache.remove(&cache_key).is_some() {
322            self.sat_cache.remove(&cache_key);
323        }
324
325        self.reserve_query()?;
326        self.queries += 1;
327        let _span = trace_span!(
328            "solver_query",
329            query_id = self.queries,
330            constraint_count = constraints.len(),
331            kind = "model"
332        )
333        .entered();
334        trace!(query_id = self.queries, constraint_count = constraints.len(), "solver model");
335        if let Some(result) = checked_xor_result(constraints) {
336            match result {
337                CheckedXorResult::Unsat => {
338                    self.cache_sat_result(cache_key, false);
339                    return Err(SymbolicError::Solver(
340                        "counterexample path became unsat".to_string(),
341                    ));
342                }
343                CheckedXorResult::Model(model) => {
344                    self.cache_sat_result(cache_key.clone(), true);
345                    self.cache_model_result(cache_key, model.clone());
346                    return Ok(model);
347                }
348            }
349        }
350        if let Some(model) = fallback_single_var_model(&smt_constraints)
351            && eval_model_constraints(constraints, &model)
352        {
353            self.cache_sat_result(cache_key.clone(), true);
354            self.cache_model_result(cache_key, model.clone());
355            return Ok(model);
356        }
357        if let Some(model) = fallback_bounded_model(&smt_constraints)
358            && eval_model_constraints(constraints, &model)
359        {
360            self.cache_sat_result(cache_key.clone(), true);
361            self.cache_model_result(cache_key, model.clone());
362            return Ok(model);
363        }
364        if let Some(model) = checked_mul_guard_branch_model(
365            cx,
366            &smt_constraints,
367            constraints,
368            &self.replayable_storage,
369        ) {
370            trace!("model: validated constructive checked-multiply guard model");
371            self.cache_sat_result(cache_key.clone(), true);
372            return Ok(model);
373        }
374        if hard_arith_fallback_first_vars(cx, &smt_constraints).is_some()
375            && let Some(model) =
376                validated_hard_arith_fallback_model(cx, &smt_constraints, constraints)
377        {
378            self.heuristic_witnesses += 1;
379            trace!("model: validated hard arithmetic fallback model before solver");
380            self.cache_sat_result(cache_key.clone(), true);
381            self.cache_model_result(cache_key, model.clone());
382            return Ok(model);
383        }
384        let output = self.query_normalized(cx, &smt_constraints, true, constraints)?;
385        let mut lines = output.lines();
386        match lines.next().unwrap_or_default().trim() {
387            "sat" => {
388                let model = parse_and_validate_model(cx, &output, constraints)?;
389                self.cache_sat_result(cache_key.clone(), true);
390                self.cache_model_result(cache_key, model.clone());
391                Ok(model)
392            }
393            "unsat" => {
394                self.model_cache.remove(&cache_key);
395                self.cache_sat_result(cache_key, false);
396                Err(SymbolicError::Solver("counterexample path became unsat".to_string()))
397            }
398            "unknown" => Err(SymbolicError::SolverUnknown),
399            other => Err(SymbolicError::Solver(format!("unexpected solver response `{other}`"))),
400        }
401    }
402
403    fn is_sat_inner(
404        &mut self,
405        cx: &mut SymCx,
406        constraints: &[SymBoolExpr],
407        defer_hard_arith_without_witness: bool,
408    ) -> Result<BranchFeasibility, SymbolicError> {
409        self.sat_queries += 1;
410        let smt_constraints =
411            normalize_sat_constraints(cx, constraints, &mut self.normalization_cache);
412        let cache_key = smt_constraints.clone();
413        if let Some(result) = self.sat_cache.get(&cache_key) {
414            self.sat_cache_hits += 1;
415            trace!(result, "is_sat: normalized cache hit");
416            return Ok(if *result { BranchFeasibility::Sat } else { BranchFeasibility::Unsat });
417        }
418        if self.has_cached_unsat_subset(&cache_key) {
419            self.sat_cache_hits += 1;
420            trace!("is_sat: normalized unsat subset cache hit");
421            self.cache_sat_result(cache_key, false);
422            return Ok(BranchFeasibility::Unsat);
423        }
424        if defer_hard_arith_without_witness
425            && let Some((condition, base)) = constraints.split_last()
426            && {
427                let normalized_base =
428                    normalize_sat_constraints(cx, base, &mut self.normalization_cache);
429                self.sat_cache.get(&normalized_base) == Some(&true)
430            }
431            && {
432                let mut complement = Vec::with_capacity(constraints.len());
433                complement.extend(base.iter().cloned());
434                complement.push(condition.clone().not(cx));
435                let normalized_complement =
436                    normalize_sat_constraints(cx, &complement, &mut self.normalization_cache);
437                self.has_cached_unsat_subset(&normalized_complement)
438            }
439        {
440            self.sat_cache_hits += 1;
441            trace!("is_sat: branch complement unsat cache hit");
442            self.cache_sat_result(cache_key, true);
443            return Ok(BranchFeasibility::Sat);
444        }
445
446        self.reserve_query()?;
447        self.queries += 1;
448        let _span = trace_span!(
449            "solver_query",
450            query_id = self.queries,
451            constraint_count = constraints.len(),
452            kind = "is_sat"
453        )
454        .entered();
455        trace!(query_id = self.queries, constraint_count = constraints.len(), "solver is_sat");
456        if constraints_are_directly_unsat(cx, &smt_constraints) {
457            trace!("is_sat: direct contradiction");
458            self.cache_sat_result(cache_key, false);
459            return Ok(BranchFeasibility::Unsat);
460        }
461        if product_monotonic_unsat_normalized(&smt_constraints) {
462            trace!("is_sat: monotonic product contradiction");
463            self.cache_sat_result(cache_key, false);
464            return Ok(BranchFeasibility::Unsat);
465        }
466        if let Some(result) = checked_xor_result(constraints) {
467            let sat = matches!(result, CheckedXorResult::Model(_));
468            trace!(sat, "is_sat: checked XOR specialist");
469            self.cache_sat_result(cache_key.clone(), sat);
470            if let CheckedXorResult::Model(model) = result {
471                self.cache_model_result(cache_key, model);
472            }
473            return Ok(if sat { BranchFeasibility::Sat } else { BranchFeasibility::Unsat });
474        }
475        if !constraints.is_empty()
476            && eval_model_constraints(constraints, &SymbolicModel::default())
477            && !constraints.iter().any(SymBoolExpr::contains_gasleft)
478        {
479            self.cache_sat_result(cache_key, true);
480            return Ok(BranchFeasibility::Sat);
481        }
482        if let Some(model) = fallback_single_var_model(&smt_constraints)
483            && eval_model_constraints(constraints, &model)
484        {
485            self.cache_sat_result(cache_key, true);
486            return Ok(BranchFeasibility::Sat);
487        }
488        if let Some(model) = fallback_bounded_model(&smt_constraints)
489            && eval_model_constraints(constraints, &model)
490        {
491            self.cache_sat_result(cache_key, true);
492            return Ok(BranchFeasibility::Sat);
493        }
494        if checked_mul_guard_branch_model(
495            cx,
496            &smt_constraints,
497            constraints,
498            &self.replayable_storage,
499        )
500        .is_some()
501        {
502            trace!("is_sat: validated constructive checked-multiply guard model");
503            self.cache_sat_result(cache_key, true);
504            return Ok(BranchFeasibility::Sat);
505        }
506        if let Some(vars) = hard_arith_fallback_first_vars(cx, &smt_constraints) {
507            if validated_hard_arith_fallback_model(cx, &smt_constraints, constraints).is_some() {
508                self.heuristic_witnesses += 1;
509                trace!("is_sat: validated hard arithmetic fallback model before solver");
510                self.cache_sat_result(cache_key, true);
511                return Ok(BranchFeasibility::Sat);
512            }
513            // A search widened past `HARD_ARITH_DEFER_MAX_VARS` variables only adds witnesses: a
514            // miss still asks the solver, which may prove the branch infeasible, where deferring
515            // would leave a nested call incomplete.
516            if defer_hard_arith_without_witness && vars <= HARD_ARITH_DEFER_MAX_VARS {
517                trace!("is_sat: deferring hard arithmetic branch without local witness");
518                return Ok(BranchFeasibility::NeedsSolver);
519            }
520        }
521        let output = self.query_normalized(cx, &smt_constraints, false, constraints)?;
522        match output.lines().next().unwrap_or_default().trim() {
523            "sat" => {
524                self.cache_sat_result(cache_key, true);
525                Ok(BranchFeasibility::Sat)
526            }
527            "unsat" => {
528                self.cache_sat_result(cache_key, false);
529                Ok(BranchFeasibility::Unsat)
530            }
531            "unknown" => Err(SymbolicError::SolverUnknown),
532            other => Err(SymbolicError::Solver(format!("unexpected solver response `{other}`"))),
533        }
534    }
535    /// Returns the resolved commands or the stored config error.
536    pub(crate) fn commands(&self) -> Result<&[SolverCommand], SymbolicError> {
537        self.commands
538            .as_ref()
539            .map(Vec::as_slice)
540            .map_err(|err| SymbolicError::Solver(err.to_string()))
541    }
542
543    pub(crate) const fn reserve_query(&self) -> Result<(), SymbolicError> {
544        if self.queries >= self.max_queries {
545            return Err(SymbolicError::SolverQueryLimit(self.max_queries));
546        }
547        Ok(())
548    }
549
550    fn cache_sat_result(&mut self, key: Vec<SymBoolExpr>, result: bool) {
551        cache_result(&mut self.sat_cache, key, result, SYMBOLIC_SOLVER_SAT_CACHE_MAX_ENTRIES);
552    }
553
554    fn cache_model_result(&mut self, key: Vec<SymBoolExpr>, model: SymbolicModel) {
555        cache_result(&mut self.model_cache, key, model, SYMBOLIC_SOLVER_MODEL_CACHE_MAX_ENTRIES);
556    }
557
558    /// Returns whether an already-proved unsat constraint set is a subset of `key`.
559    fn has_cached_unsat_subset(&self, key: &[SymBoolExpr]) -> bool {
560        self.sat_cache
561            .iter()
562            .any(|(cached_key, result)| !*result && sorted_bool_exprs_are_subset(cached_key, key))
563    }
564
565    /// Sends already-normalized constraints to the configured solver portfolio.
566    pub(crate) fn query_normalized(
567        &mut self,
568        cx: &SymCx,
569        smt_constraints: &[SymBoolExpr],
570        model: bool,
571        model_constraints: &[SymBoolExpr],
572    ) -> Result<String, SymbolicError> {
573        self.smt_queries += 1;
574        let build_started = Instant::now();
575        let mut vars = SymbolicVars::default();
576        for constraint in smt_constraints {
577            constraint.collect_vars(&mut vars);
578        }
579
580        let configured_commands = self.commands()?.to_vec();
581        let ordered_commands = self.portfolio_scheduler.ordered_commands(&configured_commands);
582        let commands =
583            ordered_commands.iter().map(|(_, command)| command.clone()).collect::<Vec<_>>();
584
585        let mut smt = String::with_capacity(256 + smt_constraints.len().saturating_mul(192));
586        smt.push_str("(set-logic QF_BV)\n");
587        if commands.iter().all(|command| command.smt_timeout)
588            && let Some(timeout) = self.timeout.filter(|timeout| *timeout > 0)
589        {
590            let _ = writeln!(smt, "(set-option :timeout {})", timeout.saturating_mul(1000));
591        }
592        for var in vars {
593            let name = cx.symbol_name(var);
594            let _ = writeln!(smt, "(declare-fun {name} () (_ BitVec 256))");
595        }
596        write_smt_assertions(cx, &mut smt, smt_constraints)?;
597        smt.push_str("(check-sat)\n");
598        if model {
599            smt.push_str("(get-model)\n");
600        }
601        let smt_bytes = smt.len().try_into().unwrap_or(u64::MAX);
602        self.smt_input_bytes = self.smt_input_bytes.saturating_add(smt_bytes);
603        self.smt_max_query_bytes = self.smt_max_query_bytes.max(smt_bytes);
604        self.smt_build_time += build_started.elapsed();
605        if self.dump_smt {
606            let query = self.queries;
607            let _ = writeln!(std::io::stderr(), "--- symbolic SMT query {query} ---\n{smt}");
608        }
609
610        let started = Instant::now();
611        let result = if let [command] = commands.as_slice()
612            && command.smt_timeout
613            && command.program == "z3"
614            && command.args == ["-in", "-smt2"]
615        {
616            let output = self.query_z3(command, &smt).into_result();
617            SolverCommandRun { output, summaries: Vec::new() }
618        } else {
619            run_solver_commands(
620                cx,
621                &commands,
622                &smt,
623                self.timeout,
624                model.then_some(model_constraints),
625            )
626        };
627        let query_time = started.elapsed();
628        self.solver_time += query_time;
629        self.smt_max_query_time = self.smt_max_query_time.max(query_time);
630        self.portfolio_scheduler.record(&ordered_commands, &result.summaries);
631        if self.dump_smt && !result.summaries.is_empty() {
632            let _ = write!(
633                std::io::stderr(),
634                "{}",
635                format_solver_portfolio_summaries(&result.summaries)
636            );
637        }
638        result.output
639    }
640
641    fn query_z3(&mut self, command: &SolverCommand, smt: &str) -> SolverProcessOutcome {
642        let mut session = match self.z3_session.take() {
643            Some(session) => session,
644            None => match Z3Session::spawn(command) {
645                Ok(session) => session,
646                Err(err) => return SolverProcessOutcome::Error(err),
647            },
648        };
649        let outcome = session.query(command, smt, self.timeout);
650        match outcome {
651            output @ SolverProcessOutcome::Output(_) => {
652                self.z3_session = Some(session);
653                output
654            }
655            SolverProcessOutcome::Error(_) => {
656                drop(session);
657                run_solver_process(command, smt, self.timeout, &AtomicBool::new(false))
658            }
659            other => other,
660        }
661    }
662}
663
664fn cache_result<K, V>(cache: &mut HashMap<K, V>, key: K, value: V, max_entries: usize)
665where
666    K: Eq + std::hash::Hash,
667{
668    let has_capacity = cache.len() < max_entries;
669    match cache.entry(key) {
670        alloy_primitives::map::Entry::Occupied(mut entry) => {
671            entry.insert(value);
672        }
673        alloy_primitives::map::Entry::Vacant(entry) if has_capacity => {
674            entry.insert(value);
675        }
676        alloy_primitives::map::Entry::Vacant(_) => {}
677    }
678}
679
680/// Normalizes satisfiability constraints and removes soundly redundant constraints.
681fn normalize_sat_constraints(
682    cx: &mut SymCx,
683    constraints: &[SymBoolExpr],
684    normalization_cache: &mut NormalizationCache,
685) -> Vec<SymBoolExpr> {
686    let constraints = remove_implied_monotonic_constraints(
687        normalize_constraints_for_solver_cached(cx, constraints, normalization_cache),
688    );
689    remove_witnessed_isolated_hash_constraints(cx, constraints)
690}
691
692/// Removes independently satisfiable constraints over one opaque hash symbol.
693///
694/// SMT treats symbolic hashes as free bit-vector symbols. If a constraint's only SMT symbol is a
695/// hash unused by other constraints, a concrete witness proves that it cannot affect conjunction
696/// satisfiability. The witness is discarded because hash values are not replayable inputs.
697fn remove_witnessed_isolated_hash_constraints(
698    cx: &mut SymCx,
699    constraints: Vec<SymBoolExpr>,
700) -> Vec<SymBoolExpr> {
701    if !constraints.iter().any(|constraint| {
702        constraint.visit_bool(|expr| {
703            matches!(expr.kind(), SymExprKind::Keccak { .. } | SymExprKind::Hash { .. })
704        })
705    }) {
706        return constraints;
707    }
708
709    let mut symbol_constraint_counts = HashMap::<Symbol, usize>::default();
710    let hash_candidates = constraints
711        .iter()
712        .map(|constraint| {
713            let mut symbols = SymbolicVars::default();
714            let contains_hash = collect_solver_vars(constraint, &mut symbols);
715            for symbol in &symbols {
716                *symbol_constraint_counts.entry(*symbol).or_default() += 1;
717            }
718            if contains_hash && symbols.len() == 1 { symbols.first().copied() } else { None }
719        })
720        .collect::<Vec<_>>();
721
722    constraints
723        .into_iter()
724        .zip(hash_candidates)
725        .filter_map(|(constraint, candidate)| {
726            let Some(symbol) =
727                candidate.filter(|symbol| symbol_constraint_counts.get(symbol) == Some(&1))
728            else {
729                return Some(constraint);
730            };
731            let abstracted = constraint.fold_exprs(cx, &mut |cx, expr| match expr.kind() {
732                SymExprKind::Keccak { name, .. } | SymExprKind::Hash { name, .. }
733                    if *name == symbol =>
734                {
735                    SymExpr::get_var(cx, symbol)
736                }
737                _ => expr,
738            });
739            let removable = fallback_single_var_model(std::slice::from_ref(&abstracted)).is_some();
740            (!removable).then_some(constraint)
741        })
742        .collect()
743}
744
745/// Collects variables as the SMT writer sees them, stopping at opaque hash leaves.
746fn collect_solver_vars(constraint: &SymBoolExpr, vars: &mut SymbolicVars) -> bool {
747    fn visit_bool(expr: &SymBoolExpr, vars: &mut SymbolicVars) -> bool {
748        match expr.kind() {
749            SymBoolExprKind::Const(_) => false,
750            SymBoolExprKind::Not(expr) => visit_bool(expr, vars),
751            SymBoolExprKind::And(exprs) => {
752                let mut contains_hash = false;
753                for expr in exprs.iter() {
754                    contains_hash |= visit_bool(expr, vars);
755                }
756                contains_hash
757            }
758            SymBoolExprKind::Cmp(_, left, right) => {
759                visit_word(left, vars) | visit_word(right, vars)
760            }
761        }
762    }
763
764    fn visit_word(expr: &SymExpr, vars: &mut SymbolicVars) -> bool {
765        match expr.kind() {
766            SymExprKind::Const(_) => false,
767            SymExprKind::Var(symbol) | SymExprKind::GasLeft(symbol) => {
768                vars.insert(*symbol);
769                false
770            }
771            SymExprKind::Keccak { name, .. } | SymExprKind::Hash { name, .. } => {
772                vars.insert(*name);
773                true
774            }
775            SymExprKind::Not(expr) => visit_word(expr, vars),
776            SymExprKind::BinOp(_, left, right) => visit_word(left, vars) | visit_word(right, vars),
777            SymExprKind::TernOp(_, left, right, modulus) => {
778                visit_word(left, vars) | visit_word(right, vars) | visit_word(modulus, vars)
779            }
780            SymExprKind::Ite(condition, then_expr, else_expr) => {
781                visit_bool(condition, vars)
782                    | visit_word(then_expr, vars)
783                    | visit_word(else_expr, vars)
784            }
785        }
786    }
787
788    visit_bool(constraint, vars)
789}
790
791/// Returns a hard-arithmetic fallback model only after validating it against original constraints.
792fn validated_hard_arith_fallback_model(
793    cx: &SymCx,
794    normalized_constraints: &[SymBoolExpr],
795    original_constraints: &[SymBoolExpr],
796) -> Option<SymbolicModel> {
797    let model = hard_arith_fallback_model(cx, normalized_constraints)?;
798    eval_model_constraints(original_constraints, &model).then_some(model)
799}
800
801#[derive(Clone, Debug, Default)]
802struct PortfolioScheduler {
803    history: Vec<VecDeque<PortfolioSchedulerSignal>>,
804}
805
806#[derive(Clone, Copy, Debug, PartialEq, Eq)]
807enum PortfolioSchedulerSignal {
808    Winner { speed_bonus: i64 },
809    InvalidModel,
810    Error,
811    Unknown,
812    Neutral,
813}
814
815impl PortfolioSchedulerSignal {
816    /// Returns the scheduler signal represented by one solver run summary.
817    fn from_summary(summary: &SolverRunSummary) -> Self {
818        let speed_bonus = PORTFOLIO_SCHEDULER_MAX_SPEED_BONUS.saturating_sub(
819            summary.elapsed.as_millis().min(PORTFOLIO_SCHEDULER_SPEED_BONUS_CAP_MS) as i64,
820        );
821        match (summary.winner, summary.outcome) {
822            (true, SolverOutcome::SatValid | SolverOutcome::Unsat) => Self::Winner { speed_bonus },
823            (_, SolverOutcome::SatInvalid) => Self::InvalidModel,
824            (_, SolverOutcome::Error | SolverOutcome::Unexpected) => Self::Error,
825            (_, SolverOutcome::Unknown | SolverOutcome::TimeoutOrUnknown) => Self::Unknown,
826            _ => Self::Neutral,
827        }
828    }
829
830    /// Returns the numeric score contribution for adaptive portfolio ordering.
831    const fn score(self) -> i64 {
832        match self {
833            Self::Winner { speed_bonus } => 1_000 + speed_bonus,
834            Self::InvalidModel => -1_000,
835            Self::Error => -750,
836            Self::Unknown => -250,
837            Self::Neutral => 0,
838        }
839    }
840}
841
842impl PortfolioScheduler {
843    /// Returns configured commands ordered by recent portfolio performance.
844    fn ordered_commands(&mut self, commands: &[SolverCommand]) -> Vec<(usize, SolverCommand)> {
845        self.history.resize_with(commands.len(), VecDeque::new);
846        let mut ordered = commands.iter().cloned().enumerate().collect::<Vec<_>>();
847        ordered.sort_by(|(left_index, _), (right_index, _)| {
848            self.score(*right_index)
849                .cmp(&self.score(*left_index))
850                .then_with(|| left_index.cmp(right_index))
851        });
852        ordered
853    }
854
855    /// Records one query's portfolio summaries against original configured solver indexes.
856    fn record(
857        &mut self,
858        ordered_commands: &[(usize, SolverCommand)],
859        summaries: &[SolverRunSummary],
860    ) {
861        for summary in summaries {
862            let Some(run_index) = summary.index else { continue };
863            let Some((configured_index, _)) = ordered_commands.get(run_index) else { continue };
864            let Some(history) = self.history.get_mut(*configured_index) else { continue };
865            let signal = PortfolioSchedulerSignal::from_summary(summary);
866            if matches!(signal, PortfolioSchedulerSignal::Neutral) {
867                continue;
868            }
869            history.push_back(signal);
870            if history.len() > PORTFOLIO_SCHEDULER_HISTORY {
871                history.pop_front();
872            }
873        }
874    }
875
876    /// Returns the recent-performance score for one configured solver index.
877    fn score(&self, index: usize) -> i64 {
878        self.history
879            .get(index)
880            .into_iter()
881            .flatten()
882            .rev()
883            .enumerate()
884            .map(|(age, signal)| {
885                let recency = PORTFOLIO_SCHEDULER_HISTORY
886                    .saturating_sub(age)
887                    .max(PORTFOLIO_SCHEDULER_MIN_RECENCY_WEIGHT as usize)
888                    as i64;
889                recency * signal.score()
890            })
891            .sum()
892    }
893}
894
895/// Returns the subprocess commands for the configured SMT solver setup.
896pub(crate) fn solver_commands_for_config(
897    config: &SymbolicConfig,
898) -> Result<Vec<SolverCommand>, SolverConfigError> {
899    if let Some(command) = config.solver_command.as_deref().filter(|command| !command.is_empty()) {
900        return Ok(vec![SolverCommand::new(split_solver_command(command)?, false)?]);
901    }
902
903    let portfolio = config
904        .solver_portfolio
905        .iter()
906        .map(|entry| entry.trim())
907        .filter(|entry| !entry.is_empty())
908        .collect::<Vec<_>>();
909    if !portfolio.is_empty() {
910        return portfolio.into_iter().map(solver_command_for_portfolio_entry).collect();
911    }
912
913    Ok(vec![named_solver_command(&config.solver)?])
914}
915
916/// Returns the default command for a known solver name.
917pub(crate) fn named_solver_command(solver: &str) -> Result<SolverCommand, SolverConfigError> {
918    let (parts, smt_timeout) = match solver {
919        "z3" => (vec!["z3", "-in", "-smt2"], true),
920        "yices" => (vec!["yices-smt2", "--bvconst-in-decimal"], false),
921        "cvc5" => (
922            vec![
923                "cvc5",
924                "--produce-models",
925                "--lang",
926                "smt2",
927                "--bv-print-consts-as-indexed-symbols",
928            ],
929            false,
930        ),
931        "cvc5-int" => (
932            vec![
933                "cvc5",
934                "--produce-models",
935                "--lang",
936                "smt2",
937                "--bv-print-consts-as-indexed-symbols",
938                "--solve-bv-as-int=iand",
939                "--iand-mode=bitwise",
940            ],
941            false,
942        ),
943        "bitwuzla" => (vec!["bitwuzla", "--produce-models"], false),
944        "bitwuzla-abs" => (vec!["bitwuzla", "--produce-models", "--abstraction"], false),
945        // Preserve existing behavior for custom z3-compatible executable names/paths.
946        custom => (vec![custom, "-in", "-smt2"], true),
947    };
948    let parts = parts.into_iter().map(str::to_string).collect::<Vec<_>>();
949    SolverCommand::new(parts, smt_timeout)
950}
951
952/// Returns the command for one configured portfolio entry.
953pub(crate) fn solver_command_for_portfolio_entry(
954    entry: &str,
955) -> Result<SolverCommand, SolverConfigError> {
956    if entry.chars().any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '\\')) {
957        SolverCommand::new(split_solver_command(entry)?, false)
958    } else {
959        named_solver_command(entry)
960    }
961}
962
963/// Splits a shell-like solver command into argv parts.
964pub(crate) fn split_solver_command(command: &str) -> Result<Vec<String>, SolverConfigError> {
965    let parts = shlex::split(command).ok_or(SolverConfigError::InvalidShellQuoting)?;
966    if parts.is_empty() {
967        return Err(SolverConfigError::EmptyCommand);
968    }
969
970    Ok(parts)
971}
972
973#[derive(Debug)]
974enum SolverProcessOutcome {
975    Output(String),
976    Unknown,
977    Cancelled,
978    Error(String),
979}
980
981impl SolverProcessOutcome {
982    fn into_result(self) -> Result<String, SymbolicError> {
983        match self {
984            Self::Output(output) => Ok(output),
985            Self::Unknown => Err(SymbolicError::SolverUnknown),
986            Self::Cancelled => {
987                warn!("solver query was cancelled");
988                Err(SymbolicError::Solver("solver query was cancelled".to_string()))
989            }
990            Self::Error(err) => Err(SymbolicError::Solver(err)),
991        }
992    }
993}
994
995#[derive(Debug)]
996struct SolverProcessResult {
997    index: usize,
998    display: String,
999    scheduled_after: Duration,
1000    started_after: Duration,
1001    elapsed: Duration,
1002    outcome: SolverProcessOutcome,
1003}
1004
1005#[derive(Debug)]
1006struct ScheduledSolver {
1007    index: usize,
1008    command: SolverCommand,
1009    launch_after: Duration,
1010}
1011
1012#[derive(Debug)]
1013struct SolverCommandRun {
1014    output: Result<String, SymbolicError>,
1015    summaries: Vec<SolverRunSummary>,
1016}
1017
1018#[derive(Debug)]
1019pub(crate) struct SolverRunSummary {
1020    index: Option<usize>,
1021    display: String,
1022    scheduled_after: Option<Duration>,
1023    started_after: Option<Duration>,
1024    elapsed: Duration,
1025    outcome: SolverOutcome,
1026    detail: Option<String>,
1027    winner: bool,
1028}
1029
1030impl SolverRunSummary {
1031    /// Builds a portfolio run summary with no detail or winner marker.
1032    pub(crate) const fn new(display: String, elapsed: Duration, outcome: SolverOutcome) -> Self {
1033        Self {
1034            index: None,
1035            display,
1036            scheduled_after: None,
1037            started_after: None,
1038            elapsed,
1039            outcome,
1040            detail: None,
1041            winner: false,
1042        }
1043    }
1044
1045    /// Attaches the configured portfolio order and launch delay to this summary.
1046    pub(crate) const fn with_schedule(
1047        mut self,
1048        index: usize,
1049        scheduled_after: Duration,
1050        started_after: Option<Duration>,
1051    ) -> Self {
1052        self.index = Some(index);
1053        self.scheduled_after = Some(scheduled_after);
1054        self.started_after = started_after;
1055        self
1056    }
1057
1058    fn with_detail(mut self, detail: String) -> Self {
1059        self.detail = Some(detail);
1060        self
1061    }
1062
1063    /// Marks this solver run as the portfolio result winner.
1064    pub(crate) const fn winner(mut self) -> Self {
1065        self.winner = true;
1066        self
1067    }
1068}
1069
1070/// Runs one or more solver commands and returns the first decisive SMT-LIB response.
1071fn run_solver_commands(
1072    cx: &SymCx,
1073    commands: &[SolverCommand],
1074    smt: &str,
1075    timeout: Option<u32>,
1076    model_constraints: Option<&[SymBoolExpr]>,
1077) -> SolverCommandRun {
1078    if commands.is_empty() {
1079        return SolverCommandRun {
1080            output: Err(SymbolicError::Solver("symbolic solver portfolio is empty".to_string())),
1081            summaries: Vec::new(),
1082        };
1083    }
1084    if commands.len() == 1 {
1085        let output =
1086            run_solver_process(&commands[0], smt, timeout, &AtomicBool::new(false)).into_result();
1087        return SolverCommandRun { output, summaries: Vec::new() };
1088    }
1089
1090    let cancel = Arc::new(AtomicBool::new(false));
1091    let (tx, rx) = mpsc::channel();
1092    thread::scope(|scope| {
1093        let started_at = Instant::now();
1094        let mut pending = scheduled_portfolio(commands);
1095        let mut running = 0usize;
1096
1097        let mut saw_unknown = false;
1098        let mut saw_unsat = false;
1099        let mut saw_invalid_sat_model = false;
1100        let mut errors = Vec::new();
1101        let mut decisive = None;
1102        let mut summaries = Vec::new();
1103
1104        while running > 0 || !pending.is_empty() {
1105            if decisive.is_none() {
1106                let now = started_at.elapsed();
1107                let mut launched = false;
1108                while pending
1109                    .front()
1110                    .is_some_and(|solver| solver.launch_after <= now || (running == 0 && !launched))
1111                {
1112                    let solver = pending.pop_front().expect("pending solver exists");
1113                    let tx = tx.clone();
1114                    let cancel = Arc::clone(&cancel);
1115                    let started_after = started_at.elapsed();
1116                    running += 1;
1117                    launched = true;
1118                    scope.spawn(move || {
1119                        let start = Instant::now();
1120                        let outcome = run_solver_process(&solver.command, smt, timeout, &cancel);
1121                        let _ = tx.send(SolverProcessResult {
1122                            index: solver.index,
1123                            display: solver.command.display,
1124                            scheduled_after: solver.launch_after,
1125                            started_after,
1126                            elapsed: start.elapsed(),
1127                            outcome,
1128                        });
1129                    });
1130                }
1131            }
1132
1133            if running == 0 {
1134                continue;
1135            }
1136
1137            let result = if decisive.is_none() {
1138                next_portfolio_launch_wait(started_at, &pending)
1139                    .map_or_else(|| rx.recv().ok(), |wait| rx.recv_timeout(wait).ok())
1140            } else {
1141                rx.recv().ok()
1142            };
1143            let Some(result) = result else {
1144                continue;
1145            };
1146            running = running.saturating_sub(1);
1147            let SolverProcessResult {
1148                index,
1149                display,
1150                scheduled_after,
1151                started_after,
1152                elapsed,
1153                outcome,
1154            } = result;
1155            if decisive.is_some() {
1156                summaries.push(summary_for_cancelled_solver_result(
1157                    index,
1158                    display,
1159                    scheduled_after,
1160                    started_after,
1161                    elapsed,
1162                    outcome,
1163                ));
1164                continue;
1165            }
1166            match outcome {
1167                SolverProcessOutcome::Output(output)
1168                    if output.lines().next().unwrap_or_default().trim() == "sat" =>
1169                {
1170                    if let Some(constraints) = model_constraints
1171                        && let Err(err) = validate_solver_model_output(cx, &output, constraints)
1172                    {
1173                        summaries.push(
1174                            SolverRunSummary::new(
1175                                display.clone(),
1176                                elapsed,
1177                                SolverOutcome::SatInvalid,
1178                            )
1179                            .with_schedule(index, scheduled_after, Some(started_after))
1180                            .with_detail(err.to_string()),
1181                        );
1182                        saw_invalid_sat_model = true;
1183                        errors.push(format!("{display}: {err}"));
1184                        continue;
1185                    }
1186                    summaries.push(
1187                        SolverRunSummary::new(display, elapsed, SolverOutcome::SatValid)
1188                            .with_schedule(index, scheduled_after, Some(started_after))
1189                            .winner(),
1190                    );
1191                    decisive = Some(output);
1192                    cancel.store(true, Ordering::SeqCst);
1193                    while let Some(solver) = pending.pop_front() {
1194                        summaries.push(summary_for_unstarted_solver(solver));
1195                    }
1196                }
1197                SolverProcessOutcome::Output(output)
1198                    if output.lines().next().unwrap_or_default().trim() == "unsat" =>
1199                {
1200                    summaries.push(
1201                        SolverRunSummary::new(display, elapsed, SolverOutcome::Unsat)
1202                            .with_schedule(index, scheduled_after, Some(started_after)),
1203                    );
1204                    saw_unsat = true;
1205                }
1206                SolverProcessOutcome::Output(output)
1207                    if output.lines().next().unwrap_or_default().trim() == "unknown" =>
1208                {
1209                    summaries.push(
1210                        SolverRunSummary::new(display, elapsed, SolverOutcome::Unknown)
1211                            .with_schedule(index, scheduled_after, Some(started_after)),
1212                    );
1213                    saw_unknown = true;
1214                }
1215                SolverProcessOutcome::Output(output) => {
1216                    let first_line = output.lines().next().unwrap_or_default().trim().to_string();
1217                    summaries.push(
1218                        SolverRunSummary::new(display.clone(), elapsed, SolverOutcome::Unexpected)
1219                            .with_schedule(index, scheduled_after, Some(started_after))
1220                            .with_detail(first_line.clone()),
1221                    );
1222                    errors.push(format!("{display}: unexpected solver response `{first_line}`"));
1223                }
1224                SolverProcessOutcome::Unknown => {
1225                    summaries.push(
1226                        SolverRunSummary::new(display, elapsed, SolverOutcome::TimeoutOrUnknown)
1227                            .with_schedule(index, scheduled_after, Some(started_after)),
1228                    );
1229                    saw_unknown = true;
1230                }
1231                SolverProcessOutcome::Cancelled => {
1232                    summaries.push(
1233                        SolverRunSummary::new(display, elapsed, SolverOutcome::Cancelled)
1234                            .with_schedule(index, scheduled_after, Some(started_after)),
1235                    );
1236                }
1237                SolverProcessOutcome::Error(err) => {
1238                    summaries.push(
1239                        SolverRunSummary::new(display.clone(), elapsed, SolverOutcome::Error)
1240                            .with_schedule(index, scheduled_after, Some(started_after))
1241                            .with_detail(err.clone()),
1242                    );
1243                    errors.push(format!("{display}: {err}"));
1244                }
1245            }
1246        }
1247
1248        if decisive.is_none()
1249            && saw_unsat
1250            && let Some(summary) =
1251                summaries.iter_mut().find(|summary| summary.outcome == SolverOutcome::Unsat)
1252        {
1253            summary.winner = true;
1254        }
1255
1256        let output = if let Some(output) = decisive {
1257            Ok(output)
1258        } else if saw_invalid_sat_model {
1259            Err(SymbolicError::Solver(errors.join("; ")))
1260        } else if saw_unsat {
1261            Ok("unsat\n".to_string())
1262        } else if saw_unknown {
1263            Err(SymbolicError::SolverUnknown)
1264        } else {
1265            Err(SymbolicError::Solver(errors.join("; ")))
1266        };
1267
1268        SolverCommandRun { output, summaries }
1269    })
1270}
1271
1272/// Returns the staged launch plan for a configured portfolio.
1273fn scheduled_portfolio(commands: &[SolverCommand]) -> VecDeque<ScheduledSolver> {
1274    commands
1275        .iter()
1276        .cloned()
1277        .enumerate()
1278        .map(|(index, command)| ScheduledSolver {
1279            index,
1280            command,
1281            launch_after: portfolio_launch_delay(index),
1282        })
1283        .collect()
1284}
1285
1286/// Returns when the solver at `index` should be started, relative to query start.
1287const fn portfolio_launch_delay(index: usize) -> Duration {
1288    match index {
1289        0 => Duration::ZERO,
1290        1 => SECOND_PORTFOLIO_SOLVER_DELAY,
1291        index => RESCUE_PORTFOLIO_SOLVER_DELAY.saturating_mul(index.saturating_sub(1) as u32),
1292    }
1293}
1294
1295/// Returns how long the supervisor can wait before the next pending solver is due.
1296fn next_portfolio_launch_wait(
1297    started_at: Instant,
1298    pending: &VecDeque<ScheduledSolver>,
1299) -> Option<Duration> {
1300    pending.front().map(|solver| {
1301        solver.launch_after.checked_sub(started_at.elapsed()).unwrap_or(Duration::ZERO)
1302    })
1303}
1304
1305/// Summarizes a solver that was never launched because the portfolio already won.
1306fn summary_for_unstarted_solver(solver: ScheduledSolver) -> SolverRunSummary {
1307    SolverRunSummary::new(solver.command.display, Duration::ZERO, SolverOutcome::NotStarted)
1308        .with_schedule(solver.index, solver.launch_after, None)
1309}
1310
1311/// Summarizes a solver result received after a portfolio winner was chosen.
1312fn summary_for_cancelled_solver_result(
1313    index: usize,
1314    display: String,
1315    scheduled_after: Duration,
1316    started_after: Duration,
1317    elapsed: Duration,
1318    outcome: SolverProcessOutcome,
1319) -> SolverRunSummary {
1320    let summary = match outcome {
1321        SolverProcessOutcome::Output(output)
1322            if output.lines().next().unwrap_or_default().trim() == "sat" =>
1323        {
1324            SolverRunSummary::new(display, elapsed, SolverOutcome::SatAfterWinner)
1325        }
1326        SolverProcessOutcome::Output(output)
1327            if output.lines().next().unwrap_or_default().trim() == "unsat" =>
1328        {
1329            SolverRunSummary::new(display, elapsed, SolverOutcome::UnsatAfterWinner)
1330        }
1331        SolverProcessOutcome::Output(output)
1332            if output.lines().next().unwrap_or_default().trim() == "unknown" =>
1333        {
1334            SolverRunSummary::new(display, elapsed, SolverOutcome::UnknownAfterWinner)
1335        }
1336        SolverProcessOutcome::Output(output) => {
1337            SolverRunSummary::new(display, elapsed, SolverOutcome::Unexpected)
1338                .with_detail(output.lines().next().unwrap_or_default().trim().to_string())
1339        }
1340        SolverProcessOutcome::Unknown => {
1341            SolverRunSummary::new(display, elapsed, SolverOutcome::TimeoutOrUnknown)
1342        }
1343        SolverProcessOutcome::Cancelled => {
1344            SolverRunSummary::new(display, elapsed, SolverOutcome::Cancelled)
1345        }
1346        SolverProcessOutcome::Error(err) => {
1347            SolverRunSummary::new(display, elapsed, SolverOutcome::Error).with_detail(err)
1348        }
1349    };
1350    summary.with_schedule(index, scheduled_after, Some(started_after))
1351}
1352
1353/// Formats solver portfolio outcome diagnostics.
1354fn format_solver_portfolio_summaries(summaries: &[SolverRunSummary]) -> String {
1355    let mut output = String::new();
1356    let _ = writeln!(output, "--- symbolic solver portfolio outcomes ---");
1357    for summary in summaries {
1358        let marker = if summary.winner { " winner" } else { "" };
1359        let schedule = summary.index.zip(summary.scheduled_after).map(|(index, delay)| {
1360            let started = summary
1361                .started_after
1362                .map(|started| format!(" started +{started:.3?}"))
1363                .unwrap_or_default();
1364            format!("#{} scheduled +{delay:.3?}{started} ", index + 1)
1365        });
1366        let _ = write!(
1367            output,
1368            "{}{}: {} in {:.3?}{}",
1369            schedule.as_deref().unwrap_or_default(),
1370            summary.display,
1371            summary.outcome,
1372            summary.elapsed,
1373            marker
1374        );
1375        if let Some(detail) = summary.detail.as_deref().filter(|detail| !detail.is_empty()) {
1376            let _ = write!(output, " ({detail})");
1377        }
1378        let _ = writeln!(output);
1379    }
1380    output
1381}
1382
1383struct Z3Session {
1384    child: SolverChild,
1385    stdin: ChildStdin,
1386    stdout: Receiver<Result<String, String>>,
1387    stderr: Receiver<String>,
1388    stdout_thread: Option<JoinHandle<()>>,
1389    stderr_thread: Option<JoinHandle<()>>,
1390}
1391
1392impl Z3Session {
1393    fn spawn(command: &SolverCommand) -> Result<Self, String> {
1394        let mut child = spawn_solver_process(command)?;
1395        let stdin = child.child_mut().stdin.take().expect("piped solver stdin is available");
1396        let stdout = child.child_mut().stdout.take().expect("piped solver stdout is available");
1397        let stderr = child.child_mut().stderr.take().expect("piped solver stderr is available");
1398
1399        let (stdout_tx, stdout_rx) = mpsc::channel();
1400        let stdout_thread = thread::spawn(move || {
1401            for line in BufReader::new(stdout).lines() {
1402                let line = line.map_err(|err| format!("failed to read solver output: {err}"));
1403                let failed = line.is_err();
1404                if stdout_tx.send(line).is_err() || failed {
1405                    break;
1406                }
1407            }
1408        });
1409        let (stderr_tx, stderr_rx) = mpsc::channel();
1410        let stderr_thread = thread::spawn(move || {
1411            let mut stderr = BufReader::new(stderr);
1412            let mut output = String::new();
1413            let _ = stderr.read_to_string(&mut output);
1414            let _ = stderr_tx.send(output);
1415        });
1416
1417        Ok(Self {
1418            child,
1419            stdin,
1420            stdout: stdout_rx,
1421            stderr: stderr_rx,
1422            stdout_thread: Some(stdout_thread),
1423            stderr_thread: Some(stderr_thread),
1424        })
1425    }
1426
1427    fn query(
1428        &mut self,
1429        command: &SolverCommand,
1430        smt: &str,
1431        timeout: Option<u32>,
1432    ) -> SolverProcessOutcome {
1433        if let Err(err) = self
1434            .stdin
1435            .write_all(b"(reset)\n")
1436            .and_then(|_| self.stdin.write_all(smt.as_bytes()))
1437            .and_then(|_| writeln!(self.stdin, "(echo \"{Z3_QUERY_END}\")"))
1438            .and_then(|_| self.stdin.flush())
1439        {
1440            return SolverProcessOutcome::Error(format!("failed to write solver query: {err}"));
1441        }
1442
1443        let started_at = Instant::now();
1444        let timeout = timeout
1445            .filter(|seconds| *seconds > 0)
1446            .map(|seconds| Duration::from_secs(seconds.into()));
1447        let mut output = String::new();
1448        loop {
1449            let Some(wait) = solver_wait_duration(started_at.elapsed(), timeout) else {
1450                return SolverProcessOutcome::Unknown;
1451            };
1452            match self.stdout.recv_timeout(wait) {
1453                Ok(Ok(line)) if line == Z3_QUERY_END => {
1454                    return SolverProcessOutcome::Output(output);
1455                }
1456                Ok(Ok(line)) => {
1457                    output.push_str(&line);
1458                    output.push('\n');
1459                }
1460                Ok(Err(err)) => return SolverProcessOutcome::Error(err),
1461                Err(RecvTimeoutError::Timeout) => {}
1462                Err(RecvTimeoutError::Disconnected) => {
1463                    let stderr =
1464                        self.stderr.recv_timeout(SOLVER_CANCEL_CHECK_INTERVAL).unwrap_or_default();
1465                    return match self.child.child_mut().try_wait() {
1466                        Ok(Some(status)) => SolverProcessOutcome::Error(solver_exit_error(
1467                            command, status, &output, &stderr,
1468                        )),
1469                        Ok(None) => SolverProcessOutcome::Error(
1470                            "solver stdout closed before the query completed".to_string(),
1471                        ),
1472                        Err(err) => SolverProcessOutcome::Error(format!(
1473                            "failed to query solver process status: {err}"
1474                        )),
1475                    };
1476                }
1477            }
1478        }
1479    }
1480}
1481
1482impl Drop for Z3Session {
1483    fn drop(&mut self) {
1484        self.child.terminate();
1485        if let Some(thread) = self.stdout_thread.take() {
1486            let _ = thread.join();
1487        }
1488        if let Some(thread) = self.stderr_thread.take() {
1489            let _ = thread.join();
1490        }
1491    }
1492}
1493
1494fn spawn_solver_process(command: &SolverCommand) -> Result<SolverChild, String> {
1495    Command::new(&command.program)
1496        .args(&command.args)
1497        .stdin(Stdio::piped())
1498        .stdout(Stdio::piped())
1499        .stderr(Stdio::piped())
1500        .spawn()
1501        .map(SolverChild::new)
1502        .map_err(|err| format!("failed to spawn `{}`: {err}", command.display))
1503}
1504
1505/// Runs one solver process to completion, timeout, or cooperative cancellation.
1506fn run_solver_process(
1507    command: &SolverCommand,
1508    smt: &str,
1509    timeout: Option<u32>,
1510    cancel: &AtomicBool,
1511) -> SolverProcessOutcome {
1512    let mut child = match spawn_solver_process(command) {
1513        Ok(child) => child,
1514        Err(err) => return SolverProcessOutcome::Error(err),
1515    };
1516
1517    if let Some(mut stdin) = child.child_mut().stdin.take()
1518        && let Err(err) = stdin.write_all(smt.as_bytes())
1519    {
1520        return SolverProcessOutcome::Error(format!("failed to write solver query: {err}"));
1521    }
1522
1523    let started_at = Instant::now();
1524    let timeout =
1525        timeout.filter(|seconds| *seconds > 0).map(|seconds| Duration::from_secs(seconds.into()));
1526    loop {
1527        if cancel.load(Ordering::SeqCst) {
1528            return SolverProcessOutcome::Cancelled;
1529        }
1530
1531        let Some(wait) = solver_wait_duration(started_at.elapsed(), timeout) else {
1532            return SolverProcessOutcome::Unknown;
1533        };
1534
1535        match child.child_mut().wait_timeout(wait) {
1536            Ok(Some(_)) => break,
1537            Ok(None) => {}
1538            Err(err) => {
1539                return SolverProcessOutcome::Error(format!(
1540                    "failed to wait for solver process: {err}"
1541                ));
1542            }
1543        }
1544    }
1545
1546    let output = match child.wait_with_output() {
1547        Ok(output) => output,
1548        Err(err) => {
1549            return SolverProcessOutcome::Error(format!("failed to read solver output: {err}"));
1550        }
1551    };
1552    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
1553    if !output.status.success() {
1554        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
1555        return SolverProcessOutcome::Error(solver_exit_error(
1556            command,
1557            output.status,
1558            &stdout,
1559            &stderr,
1560        ));
1561    }
1562    SolverProcessOutcome::Output(stdout)
1563}
1564
1565fn solver_wait_duration(elapsed: Duration, timeout: Option<Duration>) -> Option<Duration> {
1566    let Some(timeout) = timeout else {
1567        return Some(SOLVER_CANCEL_CHECK_INTERVAL);
1568    };
1569    let remaining = timeout.checked_sub(elapsed)?;
1570    if remaining.is_zero() { None } else { Some(remaining.min(SOLVER_CANCEL_CHECK_INTERVAL)) }
1571}
1572
1573struct SolverChild {
1574    child: Option<Child>,
1575}
1576
1577impl SolverChild {
1578    const fn new(child: Child) -> Self {
1579        Self { child: Some(child) }
1580    }
1581
1582    const fn child_mut(&mut self) -> &mut Child {
1583        self.child.as_mut().expect("solver child exists")
1584    }
1585
1586    fn wait_with_output(mut self) -> std::io::Result<Output> {
1587        self.child.take().expect("solver child exists").wait_with_output()
1588    }
1589
1590    fn terminate(&mut self) {
1591        if let Some(mut child) = self.child.take() {
1592            let _ = child.kill();
1593            let _ = child.wait();
1594        }
1595    }
1596}
1597
1598impl Drop for SolverChild {
1599    fn drop(&mut self) {
1600        self.terminate();
1601    }
1602}
1603
1604fn solver_exit_error(
1605    command: &SolverCommand,
1606    status: std::process::ExitStatus,
1607    stdout: &str,
1608    stderr: &str,
1609) -> String {
1610    let mut message = format!("`{}` exited with {status}", command.display);
1611    if !stderr.trim().is_empty() {
1612        message.push_str(": ");
1613        message.push_str(stderr.trim());
1614    }
1615    if !stdout.trim().is_empty() {
1616        message.push_str("; stdout: ");
1617        message.push_str(stdout.trim());
1618    }
1619    message
1620}
1621
1622pub(crate) fn parse_and_validate_model(
1623    cx: &SymCx,
1624    output: &str,
1625    constraints: &[SymBoolExpr],
1626) -> Result<SymbolicModel, SymbolicError> {
1627    let symbols = model_symbols_for_constraints(cx, constraints);
1628    let model = parse_model_with_symbols(output, &symbols)?;
1629    if eval_model_constraints(constraints, &model) {
1630        Ok(model)
1631    } else {
1632        let reason = if constraints.iter().any(SymBoolExpr::contains_keccak) {
1633            "solver model does not satisfy path constraints involving symbolic Keccak heuristic"
1634        } else {
1635            "solver model does not satisfy path constraints"
1636        };
1637        debug!(
1638            constraint_count = constraints.len(),
1639            reason, "solver model does not satisfy path constraints"
1640        );
1641        Err(SymbolicError::Solver(reason.to_string()))
1642    }
1643}
1644
1645pub(crate) fn validate_solver_model_output(
1646    cx: &SymCx,
1647    output: &str,
1648    constraints: &[SymBoolExpr],
1649) -> Result<(), SymbolicError> {
1650    parse_and_validate_model(cx, output, constraints).map(|_| ())
1651}
1652
1653fn parse_model_with_symbols(
1654    output: &str,
1655    symbols: &HashMap<String, Symbol>,
1656) -> Result<SymbolicModel, SymbolicError> {
1657    parse_model_with_symbol(output, |name| symbols.get(name).copied())
1658}
1659
1660fn parse_model_with_symbol(
1661    output: &str,
1662    mut symbol_for: impl FnMut(&str) -> Option<Symbol>,
1663) -> Result<SymbolicModel, SymbolicError> {
1664    let mut values = SymbolicModel::default();
1665    parse_model_values(output, |name, value| {
1666        if let Some(symbol) = symbol_for(name) {
1667            values.insert(symbol, value);
1668        }
1669    })?;
1670    Ok(values)
1671}
1672
1673fn parse_model_values(
1674    output: &str,
1675    mut insert_value: impl FnMut(&str, U256),
1676) -> Result<(), SymbolicError> {
1677    let mut tokens = Vec::new();
1678    let mut atom_start = None;
1679    for (idx, c) in output.char_indices() {
1680        if c.is_whitespace() || matches!(c, '(' | ')') {
1681            if let Some(start) = atom_start.take() {
1682                tokens.push(&output[start..idx]);
1683            }
1684            if !c.is_whitespace() {
1685                tokens.push(&output[idx..idx + c.len_utf8()]);
1686            }
1687        } else if atom_start.is_none() {
1688            atom_start = Some(idx);
1689        }
1690    }
1691    if let Some(start) = atom_start {
1692        tokens.push(&output[start..]);
1693    }
1694    let mut tokens = tokens.into_iter();
1695    while let Some(sexp) = ModelSexp::parse(&mut tokens) {
1696        sexp.visit_definitions(&mut insert_value)?;
1697    }
1698    Ok(())
1699}
1700
1701/// A model S-expression: solvers print each value as `(define-fun <name> () <sort> <term>)`.
1702enum ModelSexp<'a> {
1703    Atom(&'a str),
1704    List(Vec<Self>),
1705}
1706
1707impl<'a> ModelSexp<'a> {
1708    /// Parses one S-expression; returns `None` at the end of the tokens or at a closing paren.
1709    fn parse(tokens: &mut impl Iterator<Item = &'a str>) -> Option<Self> {
1710        match tokens.next()? {
1711            "(" => {
1712                let mut items = Vec::new();
1713                while let Some(item) = Self::parse(tokens) {
1714                    items.push(item);
1715                }
1716                Some(Self::List(items))
1717            }
1718            ")" => None,
1719            atom => Some(Self::Atom(atom)),
1720        }
1721    }
1722
1723    /// Inserts the value of each constant definition whose term evaluates to a literal.
1724    ///
1725    /// Solvers echo the query's helper definitions, whose terms are not literals, and share
1726    /// subterms through `let`; neither may take the value of the next definition.
1727    fn visit_definitions(
1728        &self,
1729        insert_value: &mut impl FnMut(&str, U256),
1730    ) -> Result<(), SymbolicError> {
1731        let Self::List(items) = self else { return Ok(()) };
1732        if let [Self::Atom("define-fun"), Self::Atom(name), Self::List(args), _sort, term] =
1733            items.as_slice()
1734            && args.is_empty()
1735        {
1736            if let Some(value) = term.value(&mut HashMap::default())? {
1737                insert_value(name, value);
1738            }
1739            return Ok(());
1740        }
1741        for item in items {
1742            item.visit_definitions(insert_value)?;
1743        }
1744        Ok(())
1745    }
1746
1747    /// Evaluates a literal, a `let`-bound name, or a `let` over such terms.
1748    fn value(&self, bindings: &mut HashMap<&'a str, U256>) -> Result<Option<U256>, SymbolicError> {
1749        match self {
1750            Self::Atom(atom) => {
1751                if let Some(hex) = atom.strip_prefix("#x") {
1752                    if hex.len() > 64 {
1753                        return Err(SymbolicError::Solver(
1754                            "solver hex model value exceeds 256 bits".to_string(),
1755                        ));
1756                    }
1757                    let mut bytes = [0u8; 32];
1758                    let decoded = alloy_primitives::hex::decode(hex).map_err(|err| {
1759                        SymbolicError::Solver(format!("invalid solver hex model value: {err}"))
1760                    })?;
1761                    let start = 32usize.saturating_sub(decoded.len());
1762                    bytes[start..start + decoded.len()].copy_from_slice(&decoded);
1763                    return Ok(Some(U256::from_be_bytes(bytes)));
1764                }
1765                if let Some(binary) = atom.strip_prefix("#b") {
1766                    if binary.len() > 256 {
1767                        return Err(SymbolicError::Solver(
1768                            "solver binary model value exceeds 256 bits".to_string(),
1769                        ));
1770                    }
1771                    let parsed = U256::from_str_radix(binary, 2).map_err(|err| {
1772                        SymbolicError::Solver(format!("invalid solver binary model value: {err}"))
1773                    })?;
1774                    return Ok(Some(parsed));
1775                }
1776                Ok(bindings.get(atom).copied())
1777            }
1778            Self::List(items) => match items.as_slice() {
1779                [Self::Atom("_"), Self::Atom(bv), _width] if bv.starts_with("bv") => {
1780                    let parsed = U256::from_str_radix(&bv[2..], 10).map_err(|err| {
1781                        SymbolicError::Solver(format!("invalid solver decimal model value: {err}"))
1782                    })?;
1783                    Ok(Some(parsed))
1784                }
1785                [Self::Atom("let"), Self::List(pairs), body] => {
1786                    for pair in pairs {
1787                        if let Self::List(pair) = pair
1788                            && let [Self::Atom(name), term] = pair.as_slice()
1789                            && let Some(value) = term.value(bindings)?
1790                        {
1791                            bindings.insert(name, value);
1792                        }
1793                    }
1794                    body.value(bindings)
1795                }
1796                _ => Ok(None),
1797            },
1798        }
1799    }
1800}
1801
1802fn model_symbols_for_constraints(
1803    cx: &SymCx,
1804    constraints: &[SymBoolExpr],
1805) -> HashMap<String, Symbol> {
1806    let mut vars = SymbolicVars::default();
1807    for constraint in constraints {
1808        constraint.collect_vars(&mut vars);
1809    }
1810    vars.into_iter().map(|symbol| (cx.symbol_name(symbol).to_owned(), symbol)).collect()
1811}