logicaffeine_proof/bmc.rs
1//! Bounded model checking, k-induction, and vacuity over `ProofExpr` — pure-Rust, certified,
2//! Z3-free, browser-ready.
3//!
4//! A transition system is given as three closures over `signal@t` atoms:
5//! - `init` — the constraint at `t = 0`,
6//! - `trans(t)` — relates state `@t` to `@t+1`,
7//! - `property(t)` — the safety property that must hold at `@t`.
8//!
9//! Every question reduces to one unsatisfiability query discharged by
10//! [`crate::sat::prove_unsat`] (CDCL + RUP certification):
11//! - **BMC** ([`find_counterexample`]) — is a violating state reachable within `k` steps?
12//! `init ∧ ⋀ trans ∧ ¬property(k)` satisfiable ⇒ a counterexample trace.
13//! - **k-induction** ([`prove_invariant`]) — base (no violation in the first `k` steps) +
14//! step (`property` is `k`-inductive); both certified-UNSAT ⇒ the property holds for ALL
15//! reachable states (an unbounded proof, not merely bounded).
16//! - **Vacuity** ([`check_vacuity`]) — can the antecedent ever fire? Unsatisfiable ⇒ a dead
17//! trigger and a vacuously-true property.
18
19use crate::cdcl::SolveResult;
20use crate::cnf::Cnf;
21use crate::sat::{decode_model, prove_unsat, UnsatOutcome};
22use crate::ProofExpr;
23
24fn not(e: ProofExpr) -> ProofExpr {
25 ProofExpr::Not(Box::new(e))
26}
27
28/// Conjoin a list of obligations. An empty list is the constant `true` (a tautology over a
29/// reserved atom, since `ProofExpr` has no Boolean literal).
30fn conj(mut parts: Vec<ProofExpr>) -> ProofExpr {
31 match parts.len() {
32 0 => {
33 let c = ProofExpr::Atom("__bmc_true".to_string());
34 ProofExpr::Or(Box::new(c.clone()), Box::new(not(c)))
35 }
36 1 => parts.pop().unwrap(),
37 _ => {
38 let mut acc = parts.pop().unwrap();
39 while let Some(p) = parts.pop() {
40 acc = ProofExpr::And(Box::new(p), Box::new(acc));
41 }
42 acc
43 }
44 }
45}
46
47/// `init ∧ trans(0) ∧ … ∧ trans(k-1)` — the symbolic paths of length `k` from an initial
48/// state.
49fn unrolled_path(init: &ProofExpr, trans: &dyn Fn(u32) -> ProofExpr, k: u32) -> Vec<ProofExpr> {
50 let mut parts = vec![init.clone()];
51 for i in 0..k {
52 parts.push(trans(i));
53 }
54 parts
55}
56
57/// The verdict of bounded model checking.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub enum BmcOutcome {
60 /// A reachable state at depth `k` violates the property, with a witnessing trace.
61 CounterexampleAt { k: u32, trace: Vec<(String, bool)> },
62 /// No violating state is reachable within `max_k` transitions (a bounded guarantee).
63 NoneWithin(u32),
64 /// An obligation left the propositional fragment — escalate (e.g. bit-blast).
65 Unsupported,
66}
67
68/// Bounded model checking: search for a reachable state violating `property` within `max_k`
69/// transitions, returning the shallowest counterexample (and its trace) if one exists.
70pub fn find_counterexample(
71 init: &ProofExpr,
72 trans: &dyn Fn(u32) -> ProofExpr,
73 property: &dyn Fn(u32) -> ProofExpr,
74 max_k: u32,
75) -> BmcOutcome {
76 for k in 0..=max_k {
77 let mut parts = unrolled_path(init, trans, k);
78 parts.push(not(property(k)));
79 match prove_unsat(&conj(parts)) {
80 UnsatOutcome::Sat(trace) => return BmcOutcome::CounterexampleAt { k, trace },
81 UnsatOutcome::Refuted => continue,
82 UnsatOutcome::Unsupported => return BmcOutcome::Unsupported,
83 }
84 }
85 BmcOutcome::NoneWithin(max_k)
86}
87
88/// Bounded model checking, **incrementally**: the unrolling is clausified ONCE into a single
89/// persistent solver, and each depth's violation `¬property(k)` is checked by
90/// [`crate::cdcl::Solver::solve_under_assumptions`]. Every clause learned while ruling out a
91/// shallow depth is reused at the next — the IPASIR amortisation that makes deep BMC fast.
92///
93/// All transitions are asserted up front, so this is sound for **total** transition relations
94/// — every hardware next-state function is total (a prefix always extends to a full path), so
95/// the result matches the one-clause-per-call [`find_counterexample`]. For a partial /
96/// over-constrained transition relation, prefer [`find_counterexample`].
97pub fn find_counterexample_incremental(
98 init: &ProofExpr,
99 trans: &dyn Fn(u32) -> ProofExpr,
100 property: &dyn Fn(u32) -> ProofExpr,
101 max_k: u32,
102) -> BmcOutcome {
103 let mut cnf = Cnf::new();
104 if cnf.assert(init).is_none() {
105 return BmcOutcome::Unsupported;
106 }
107 for i in 0..max_k {
108 if cnf.assert(&trans(i)).is_none() {
109 return BmcOutcome::Unsupported;
110 }
111 }
112 // Encode each depth's violation to an activation literal (defining clauses only — the
113 // violation is asserted per query, via the assumption), and remember the exprs whose
114 // atoms make up a decoded trace.
115 let mut bad = Vec::with_capacity(max_k as usize + 1);
116 let mut atom_exprs: Vec<ProofExpr> = vec![init.clone()];
117 for i in 0..max_k {
118 atom_exprs.push(trans(i));
119 }
120 for k in 0..=max_k {
121 let violation = not(property(k));
122 match cnf.encode(&violation) {
123 Some(lit) => bad.push(lit),
124 None => return BmcOutcome::Unsupported,
125 }
126 atom_exprs.push(violation);
127 }
128
129 let decode_cnf = cnf.clone();
130 let mut solver = cnf.into_solver();
131 let refs: Vec<&ProofExpr> = atom_exprs.iter().collect();
132 for (k, &activation) in bad.iter().enumerate() {
133 match solver.solve_under_assumptions(&[activation]) {
134 SolveResult::Sat(model) => {
135 return BmcOutcome::CounterexampleAt {
136 k: k as u32,
137 trace: decode_model(&decode_cnf, &model, &refs),
138 }
139 }
140 SolveResult::Unsat => continue,
141 }
142 }
143 BmcOutcome::NoneWithin(max_k)
144}
145
146// ── Temporal symmetry ──────────────────────────────────────────────────────────────────────────
147//
148// A `signal@t` atom names a base signal observed at a time frame. A permutation of the BASE signals
149// that preserves the initial constraint, the (uniform) transition relation, and the property is a
150// symmetry of the system at EVERY frame — so applying it uniformly across the whole unrolling is an
151// automorphism of the BMC formula. Detecting it on the three single-frame obligations (not the giant
152// flat unrolling) is the temporal, model-checking-specific move; breaking it at the initial frame
153// prunes symmetric trajectories without changing whether a counterexample exists.
154
155/// Split a `signal@t` atom into `(base, frame)`; `None` for atoms carrying no frame.
156fn split_frame(a: &str) -> Option<(&str, &str)> {
157 a.rsplit_once('@')
158}
159
160/// Rename a formula by swapping two base signals, preserving each atom's time frame.
161fn swap_signals(e: &ProofExpr, a: &str, b: &str) -> ProofExpr {
162 match e {
163 ProofExpr::Atom(s) => match split_frame(s) {
164 Some((base, frame)) => {
165 let nb = if base == a {
166 b
167 } else if base == b {
168 a
169 } else {
170 base
171 };
172 ProofExpr::Atom(format!("{nb}@{frame}"))
173 }
174 None => e.clone(),
175 },
176 ProofExpr::Not(x) => not(swap_signals(x, a, b)),
177 ProofExpr::And(x, y) => ProofExpr::And(
178 Box::new(swap_signals(x, a, b)),
179 Box::new(swap_signals(y, a, b)),
180 ),
181 ProofExpr::Or(x, y) => ProofExpr::Or(
182 Box::new(swap_signals(x, a, b)),
183 Box::new(swap_signals(y, a, b)),
184 ),
185 ProofExpr::Iff(x, y) => ProofExpr::Iff(
186 Box::new(swap_signals(x, a, b)),
187 Box::new(swap_signals(y, a, b)),
188 ),
189 ProofExpr::Implies(x, y) => ProofExpr::Implies(
190 Box::new(swap_signals(x, a, b)),
191 Box::new(swap_signals(y, a, b)),
192 ),
193 other => other.clone(),
194 }
195}
196
197/// Are two propositional obligations logically equivalent? (Their XOR is certified-UNSAT.) Semantic, so
198/// it recognises symmetries a purely syntactic clause-set comparison would miss.
199fn equivalent(e: &ProofExpr, f: &ProofExpr) -> bool {
200 let xor = ProofExpr::Or(
201 Box::new(ProofExpr::And(
202 Box::new(e.clone()),
203 Box::new(not(f.clone())),
204 )),
205 Box::new(ProofExpr::And(
206 Box::new(f.clone()),
207 Box::new(not(e.clone())),
208 )),
209 );
210 matches!(prove_unsat(&xor), UnsatOutcome::Refuted)
211}
212
213/// Accumulate the base signals appearing in a formula.
214fn base_signals(e: &ProofExpr, out: &mut std::collections::BTreeSet<String>) {
215 match e {
216 ProofExpr::Atom(s) => {
217 if let Some((base, _)) = split_frame(s) {
218 out.insert(base.to_string());
219 }
220 }
221 ProofExpr::Not(x) => base_signals(x, out),
222 ProofExpr::And(x, y)
223 | ProofExpr::Or(x, y)
224 | ProofExpr::Iff(x, y)
225 | ProofExpr::Implies(x, y) => {
226 base_signals(x, out);
227 base_signals(y, out);
228 }
229 _ => {}
230 }
231}
232
233/// The **temporal symmetries** of a transition system: pairs of base signals interchangeable across all
234/// time — a swap that preserves the initial constraint, the transition relation (checked on the generic
235/// frame `trans(0)`, hence on every frame by uniformity), and the property. Each surviving pair is a
236/// genuine system automorphism when lifted uniformly through the unrolling.
237pub fn temporal_symmetry_pairs(
238 init: &ProofExpr,
239 trans0: &ProofExpr,
240 property0: &ProofExpr,
241) -> Vec<(String, String)> {
242 let mut set = std::collections::BTreeSet::new();
243 base_signals(init, &mut set);
244 base_signals(trans0, &mut set);
245 base_signals(property0, &mut set);
246 let sigs: Vec<String> = set.into_iter().collect();
247 let mut pairs = Vec::new();
248 for i in 0..sigs.len() {
249 for j in (i + 1)..sigs.len() {
250 let (a, b) = (sigs[i].as_str(), sigs[j].as_str());
251 if equivalent(init, &swap_signals(init, a, b))
252 && equivalent(trans0, &swap_signals(trans0, a, b))
253 && equivalent(property0, &swap_signals(property0, a, b))
254 {
255 pairs.push((a.to_string(), b.to_string()));
256 }
257 }
258 }
259 pairs
260}
261
262/// Bounded model checking with **temporal symmetry breaking**. Interchangeable signals
263/// ([`temporal_symmetry_pairs`]) give a system automorphism that holds at every frame, so a swap lifted
264/// uniformly through the unrolling permutes counterexample trajectories. We order each pair at the initial
265/// frame (`a@0 ≤ b@0`, i.e. `¬a@0 ∨ b@0`): a sound partial lex-leader that keeps at least one trajectory
266/// per symmetry orbit. Hence a counterexample exists under the ordering iff one exists at all, and the
267/// shallowest violating depth is unchanged — the verdict matches [`find_counterexample`], with the
268/// symmetric search space pruned.
269pub fn find_counterexample_symmetric(
270 init: &ProofExpr,
271 trans: &dyn Fn(u32) -> ProofExpr,
272 property: &dyn Fn(u32) -> ProofExpr,
273 max_k: u32,
274) -> BmcOutcome {
275 let pairs = temporal_symmetry_pairs(init, &trans(0), &property(0));
276 let breaks: Vec<ProofExpr> = pairs
277 .iter()
278 .map(|(a, b)| {
279 ProofExpr::Or(
280 Box::new(not(ProofExpr::Atom(format!("{a}@0")))),
281 Box::new(ProofExpr::Atom(format!("{b}@0"))),
282 )
283 })
284 .collect();
285 for k in 0..=max_k {
286 let mut parts = unrolled_path(init, trans, k);
287 parts.push(not(property(k)));
288 parts.extend(breaks.iter().cloned());
289 match prove_unsat(&conj(parts)) {
290 UnsatOutcome::Sat(trace) => return BmcOutcome::CounterexampleAt { k, trace },
291 UnsatOutcome::Refuted => continue,
292 UnsatOutcome::Unsupported => return BmcOutcome::Unsupported,
293 }
294 }
295 BmcOutcome::NoneWithin(max_k)
296}
297
298/// The verdict of k-induction.
299#[derive(Clone, Debug, PartialEq, Eq)]
300pub enum InductionOutcome {
301 /// Base and step both certified — the property holds for ALL reachable states (unbounded).
302 Proven,
303 /// The base case found a real violation within the first `k` steps.
304 CounterexampleAt { k: u32, trace: Vec<(String, bool)> },
305 /// The base holds but the property is not `k`-inductive — try a larger `k` (or strengthen).
306 NotInductive,
307 /// An obligation left the propositional fragment — escalate.
308 Unsupported,
309}
310
311/// k-induction: prove `property` is an invariant of the transition system.
312///
313/// - **Base**: for each `j < k`, `init ∧ path(j) ∧ ¬property(j)` is certified-UNSAT (no
314/// violation in the first `k` steps; a SAT here is a genuine counterexample).
315/// - **Step**: `property(0..k) ∧ trans(0..k) ∧ ¬property(k)` is certified-UNSAT (the property
316/// is `k`-inductive).
317///
318/// Both certified ⇒ [`InductionOutcome::Proven`] for the unbounded system.
319pub fn prove_invariant(
320 init: &ProofExpr,
321 trans: &dyn Fn(u32) -> ProofExpr,
322 property: &dyn Fn(u32) -> ProofExpr,
323 k: u32,
324) -> InductionOutcome {
325 // Base case: no violation reachable in the first k steps.
326 for j in 0..k {
327 let mut parts = unrolled_path(init, trans, j);
328 parts.push(not(property(j)));
329 match prove_unsat(&conj(parts)) {
330 UnsatOutcome::Refuted => {}
331 UnsatOutcome::Sat(trace) => return InductionOutcome::CounterexampleAt { k: j, trace },
332 UnsatOutcome::Unsupported => return InductionOutcome::Unsupported,
333 }
334 }
335
336 // Step case: property holds for k consecutive states ⇒ it holds at the next.
337 let mut parts = Vec::new();
338 for i in 0..k {
339 parts.push(property(i));
340 parts.push(trans(i));
341 }
342 parts.push(not(property(k)));
343 match prove_unsat(&conj(parts)) {
344 UnsatOutcome::Refuted => InductionOutcome::Proven,
345 UnsatOutcome::Sat(_) => InductionOutcome::NotInductive,
346 UnsatOutcome::Unsupported => InductionOutcome::Unsupported,
347 }
348}
349
350/// The verdict of a vacuity check.
351#[derive(Clone, Debug, PartialEq, Eq)]
352pub enum VacuityOutcome {
353 /// The antecedent is unsatisfiable — a dead trigger; the property holds vacuously.
354 Vacuous,
355 /// The antecedent can fire, with a witnessing assignment.
356 Reachable(Vec<(String, bool)>),
357 /// Not propositional — escalate.
358 Unsupported,
359}
360
361/// Vacuity: can `antecedent` ever be satisfied? An unsatisfiable antecedent means the
362/// property is never actually exercised (a vacuous pass / dead trigger).
363pub fn check_vacuity(antecedent: &ProofExpr) -> VacuityOutcome {
364 match prove_unsat(antecedent) {
365 UnsatOutcome::Refuted => VacuityOutcome::Vacuous,
366 UnsatOutcome::Sat(witness) => VacuityOutcome::Reachable(witness),
367 UnsatOutcome::Unsupported => VacuityOutcome::Unsupported,
368 }
369}
370
371#[cfg(test)]
372#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/bmc/tests.rs"]
373mod tests;