Skip to main content

rucc_verify/
solver.rs

1//! Running the solver.
2//!
3//! The solver is a program found on PATH, not a crate. A bitvector solver taken as a dependency
4//! would be the largest thing in the tree by a wide margin, it would have to hold the 1.85
5//! minimum the workspace holds, and `spec/18-package-layout.md` section 18.3 asks for a reason
6//! before anything is added at all. Shelling out costs a process per rule, which is nothing
7//! against the solving, and it means the version in use is the version CI installed and can say.
8
9use std::io::Write;
10use std::process::{Command, Stdio};
11
12/// How long one query gets before the answer is [`Answer::Unknown`], in seconds.
13///
14/// Five minutes, and the number is measured rather than picked. Of the 571 rules the gate is
15/// given, all but five are settled in well under a second each, and whole files of them come back
16/// in under a second together. Four of the five are in `crates/rucc-opt/rules/safety.rules` and
17/// ask about a walk over an object at sixty four bits: five seconds each for `swept` and
18/// `swept.sym`, twenty for `reached`, and fifty four for `swept.down.sym`, which is the largest
19/// claim in the tree. That is z3 5.1.0 on a laptop with nothing else running. The fifth is the
20/// multiply against division in `crates/rucc-codegen/rules/x86-64.rules`, which no budget settles
21/// and which carries a written reason for the bounded proof it gets instead.
22///
23/// The same solver on a six core Linux box, which is the class of machine CI runs on, costs
24/// twenty four seconds for `reached` and between seventy five and eighty three for the downward
25/// sweep. Eighty three against the ninety this used to be is not a budget, it is a race the
26/// slower machine sometimes loses, and losing it reads as a rule nobody has proved. That is how
27/// the same tree proved and failed to prove minutes apart. tamnd/rucc#949.
28///
29/// The cost of a limit this loose is paid only by a rule that is genuinely not going to settle,
30/// and that rule stops the build either way. The cost of one too tight is a rule that is fine
31/// being reported as unproved, which reads as a real problem and is not one.
32const DEFAULT: u32 = 300;
33
34/// A solver that was found.
35#[derive(Debug, Clone)]
36pub struct Solver {
37    program: String,
38    seconds: u32,
39}
40
41/// What the verifier is allowed to want of a solver.
42///
43/// [`Solver`] is the implementation that is a solver, and it is the one the gate runs. The reason
44/// there is a trait over it at all is the other kind: a test about what happens after the solver
45/// gives up has no way to make the real one give up except by starving it of time, and a test
46/// whose meaning depends on how fast the machine is says something slightly different everywhere
47/// it runs. That is tamnd/rucc#1123. A stub that answers unknown to the one question no solver
48/// settles says the thing the test is about.
49///
50/// Two methods, because two is what [`fn@crate::verify`] calls. This is a test double and not an
51/// abstraction anybody else has to hold: nothing outside this crate implements it, and a second
52/// real solver would be another [`Solver::find`] rather than another implementation of this.
53pub trait Ask {
54    /// Put one question, and allow it this many seconds.
55    ///
56    /// The budget is a parameter rather than a property of the solver because a rule that already
57    /// carries a written reason is given a look rather than the whole of it, and that decision
58    /// belongs to the caller who knows which rule it is.
59    ///
60    /// # Errors
61    ///
62    /// Anything that stops the solver from running or from being talked to.
63    fn ask(&self, query: &str, seconds: u32) -> std::io::Result<Answer>;
64
65    /// How long a question gets when nothing has narrowed it.
66    ///
67    /// A run that says what the budget was is a run whose shrug can be read. Without it, a rule
68    /// reported as unproved is either a rule that is false or a rule that ran out of a number
69    /// nobody printed, and telling those apart is the whole difficulty of tamnd/rucc#949.
70    fn seconds(&self) -> u32;
71}
72
73/// What the solver said about one query.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Answer {
76    /// No model exists, which is the answer a discharged rule gets: nothing makes the claim
77    /// false.
78    Unsat,
79    /// A model exists, and here is what the solver printed of it. The rule is wrong.
80    Sat(String),
81    /// The solver gave up, usually on time. Not a failure of the rule and not a pass either.
82    Unknown,
83}
84
85impl Solver {
86    /// Look for a solver on PATH.
87    ///
88    /// Returns nothing when there is none, which is what lets the tests skip rather than fail on
89    /// a machine that has not got one. CI has one, and that is where the answer matters.
90    #[must_use]
91    pub fn find() -> Option<Solver> {
92        for program in ["z3", "cvc5"] {
93            let found = Command::new(program).arg("--version").output();
94            if found.is_ok_and(|out| out.status.success()) {
95                return Some(Solver { program: program.to_owned(), seconds: DEFAULT });
96            }
97        }
98        None
99    }
100
101    /// How long a single query may take before the answer is [`Answer::Unknown`].
102    ///
103    /// This is the number [`Ask::seconds`] reports, so it is what a rule gets unless the caller
104    /// narrows it for that rule.
105    #[must_use]
106    pub fn within(self, seconds: u32) -> Solver {
107        Solver { seconds, ..self }
108    }
109
110    /// What the solver is called, for a report that has to name it.
111    #[must_use]
112    pub fn name(&self) -> &str {
113        &self.program
114    }
115}
116
117impl Ask for Solver {
118    fn seconds(&self) -> u32 {
119        self.seconds
120    }
121
122    fn ask(&self, query: &str, seconds: u32) -> std::io::Result<Answer> {
123        let timeout = match self.program.as_str() {
124            "cvc5" => format!("--tlimit={}", seconds * 1000),
125            _ => format!("-T:{seconds}"),
126        };
127        let stdin = if self.program == "cvc5" { "-" } else { "-in" };
128
129        let mut child = Command::new(&self.program)
130            .arg(stdin)
131            .arg(timeout)
132            .stdin(Stdio::piped())
133            .stdout(Stdio::piped())
134            .stderr(Stdio::piped())
135            .spawn()?;
136        let Some(mut pipe) = child.stdin.take() else {
137            return Err(std::io::Error::other("the solver has no standard input"));
138        };
139        pipe.write_all(query.as_bytes())?;
140        drop(pipe);
141        let out = child.wait_with_output()?;
142        let said = String::from_utf8_lossy(&out.stdout);
143
144        // The first line is the verdict and anything after it is the model, which is only asked
145        // for when the verdict is `sat` and is the whole value of a refutation.
146        let mut lines = said.lines();
147        Ok(match lines.next().map(str::trim) {
148            Some("unsat") => Answer::Unsat,
149            Some("sat") => Answer::Sat(lines.collect::<Vec<_>>().join("\n")),
150            _ => Answer::Unknown,
151        })
152    }
153}