Skip to main content

logicaffeine_verify/
abstraction.rs

1//! Predicate Abstraction with CEGAR Refinement
2//!
3//! Predicate abstraction reduces an infinite-state system to a finite-state
4//! boolean system over abstract predicate variables. Each concrete predicate
5//! (e.g., `x >= 0`) becomes an abstract boolean. The abstract transition encodes
6//! how predicate truth values evolve under the concrete transition relation.
7//!
8//! CEGAR (Counterexample-Guided Abstraction Refinement) iterates:
9//! 1. Abstract: build finite-state model from current predicates
10//! 2. Verify: check property on abstract model (k-induction)
11//! 3. If safe: done
12//! 4. If counterexample: check if realizable on concrete model
13//! 5. If real: return Unsafe
14//! 6. If spurious: extract new predicates from the infeasibility proof, refine
15
16use crate::equivalence::Trace;
17use crate::ir::{VerifyExpr, VerifyOp};
18use crate::kinduction;
19use std::collections::{HashMap, HashSet};
20use z3::{ast::Bool, SatResult};
21
22#[derive(Debug, Clone)]
23pub struct AbstractModel {
24    pub predicates: Vec<VerifyExpr>,
25    pub abstract_init: VerifyExpr,
26    pub abstract_transition: VerifyExpr,
27}
28
29#[derive(Debug)]
30pub enum AbstractionResult {
31    Safe,
32    Unsafe { concrete_trace: Trace },
33    SpuriousRefined { new_predicates: Vec<VerifyExpr> },
34    Unknown,
35}
36
37/// Create an abstract model from initial state and predicates (legacy 2-arg API).
38///
39/// Without the transition relation, the abstract transition cannot be computed
40/// properly, so it defaults to the conjunction of predicates as a conservative
41/// overapproximation.
42pub fn abstract_model(init: &VerifyExpr, predicates: &[VerifyExpr]) -> AbstractModel {
43    let abstract_init = if predicates.is_empty() {
44        init.clone()
45    } else {
46        let mut abs = init.clone();
47        for pred in predicates {
48            abs = VerifyExpr::and(abs, pred.clone());
49        }
50        abs
51    };
52
53    AbstractModel {
54        predicates: predicates.to_vec(),
55        abstract_init,
56        abstract_transition: VerifyExpr::bool(true),
57    }
58}
59
60/// Create an abstract model with Cartesian predicate abstraction.
61///
62/// Given concrete init, transition, and a set of predicates, this computes:
63///
64/// - `abstract_init`: init AND conjunction of all predicates
65/// - `abstract_transition`: concrete transition AND inductive predicate implications
66///
67/// For each predicate p_i, we check via Z3 whether p_i is inductive relative to
68/// the transition: `(p_i@t AND T(t, t1)) => p_i@t1`. If valid (UNSAT negation),
69/// the implication is included in the abstract transition. If not valid, the
70/// predicate may take any value in the next state (overapproximation).
71///
72/// This is Cartesian predicate abstraction: each predicate is checked independently.
73pub fn abstract_model_full(
74    init: &VerifyExpr,
75    transition: &VerifyExpr,
76    predicates: &[VerifyExpr],
77) -> AbstractModel {
78    if predicates.is_empty() {
79        return AbstractModel {
80            predicates: vec![],
81            abstract_init: init.clone(),
82            abstract_transition: transition.clone(),
83        };
84    }
85
86    // Abstract init: init AND each predicate
87    let mut abstract_init = init.clone();
88    for pred in predicates {
89        abstract_init = VerifyExpr::and(abstract_init, pred.clone());
90    }
91
92    // Abstract transition: start with the concrete transition, then add
93    // inductive predicate implications.
94    let mut abstract_trans_parts: Vec<VerifyExpr> = Vec::new();
95    abstract_trans_parts.push(transition.clone());
96
97    for pred in predicates {
98        let pred_next = replace_t_with_t1(pred);
99
100        // Check inductiveness: is (pred@t AND T) => pred@t1 valid?
101        // Equivalently: is (pred@t AND T AND NOT pred@t1) unsatisfiable?
102        let check = VerifyExpr::and(
103            pred.clone(),
104            VerifyExpr::and(transition.clone(), VerifyExpr::not(pred_next.clone())),
105        );
106
107        // Instantiate at step 0 for the Z3 check
108        let check_inst =
109            kinduction::instantiate_transition(&kinduction::instantiate_at(&check, 0), 0);
110
111        let is_inductive = {
112            let solver = crate::solver::new_solver();
113            let encoded = encode_bool(&check_inst);
114            solver.assert(&encoded);
115            matches!(solver.check(), SatResult::Unsat)
116        };
117
118        if is_inductive {
119            // Predicate is preserved by transition: include as hard constraint
120            let implication =
121                VerifyExpr::implies(VerifyExpr::and(pred.clone(), transition.clone()), pred_next);
122            abstract_trans_parts.push(implication);
123        } else {
124            // Predicate is NOT inductive: include a weaker constraint.
125            // Record that this predicate participates in the abstraction
126            // by including it as a disjunction: pred@t1 OR NOT pred@t1
127            // (i.e., the predicate can take any value, but we record its presence).
128            //
129            // We use a softer form: (pred@t AND transition) => (pred@t1 OR NOT pred@t)
130            // This is always valid and documents the predicate's participation
131            // without constraining the abstract system.
132            let soft = VerifyExpr::implies(
133                pred.clone(),
134                VerifyExpr::or(pred_next.clone(), VerifyExpr::not(pred_next)),
135            );
136            abstract_trans_parts.push(soft);
137        }
138    }
139
140    let mut abstract_transition = abstract_trans_parts[0].clone();
141    for part in &abstract_trans_parts[1..] {
142        abstract_transition = VerifyExpr::and(abstract_transition, part.clone());
143    }
144
145    AbstractModel {
146        predicates: predicates.to_vec(),
147        abstract_init,
148        abstract_transition,
149    }
150}
151
152/// Replace @t with @t1 in all variable names of an expression.
153fn replace_t_with_t1(expr: &VerifyExpr) -> VerifyExpr {
154    match expr {
155        VerifyExpr::Var(name) => {
156            if name.ends_with("@t") {
157                let base = &name[..name.len() - 2];
158                VerifyExpr::Var(format!("{}@t1", base))
159            } else {
160                VerifyExpr::Var(name.clone())
161            }
162        }
163        VerifyExpr::Binary { op, left, right } => {
164            VerifyExpr::binary(*op, replace_t_with_t1(left), replace_t_with_t1(right))
165        }
166        VerifyExpr::Not(inner) => VerifyExpr::not(replace_t_with_t1(inner)),
167        VerifyExpr::Bool(b) => VerifyExpr::Bool(*b),
168        VerifyExpr::Int(n) => VerifyExpr::Int(*n),
169        VerifyExpr::Iff(l, r) => VerifyExpr::iff(replace_t_with_t1(l), replace_t_with_t1(r)),
170        VerifyExpr::ForAll { vars, body } => {
171            VerifyExpr::forall(vars.clone(), replace_t_with_t1(body))
172        }
173        VerifyExpr::Exists { vars, body } => {
174            VerifyExpr::exists(vars.clone(), replace_t_with_t1(body))
175        }
176        VerifyExpr::ApplyInt { name, args } => VerifyExpr::apply_int(
177            name.clone(),
178            args.iter().map(|a| replace_t_with_t1(a)).collect(),
179        ),
180        VerifyExpr::Apply { name, args } => VerifyExpr::apply(
181            name.clone(),
182            args.iter().map(|a| replace_t_with_t1(a)).collect(),
183        ),
184        VerifyExpr::BitVecConst { width, value } => VerifyExpr::bv_const(*width, *value),
185        VerifyExpr::BitVecBinary { op, left, right } => {
186            VerifyExpr::bv_binary(*op, replace_t_with_t1(left), replace_t_with_t1(right))
187        }
188        VerifyExpr::BitVecExtract { high, low, operand } => VerifyExpr::BitVecExtract {
189            high: *high,
190            low: *low,
191            operand: Box::new(replace_t_with_t1(operand)),
192        },
193        VerifyExpr::BitVecConcat(l, r) => VerifyExpr::BitVecConcat(
194            Box::new(replace_t_with_t1(l)),
195            Box::new(replace_t_with_t1(r)),
196        ),
197        VerifyExpr::Select { array, index } => VerifyExpr::Select {
198            array: Box::new(replace_t_with_t1(array)),
199            index: Box::new(replace_t_with_t1(index)),
200        },
201        VerifyExpr::Store {
202            array,
203            index,
204            value,
205        } => VerifyExpr::Store {
206            array: Box::new(replace_t_with_t1(array)),
207            index: Box::new(replace_t_with_t1(index)),
208            value: Box::new(replace_t_with_t1(value)),
209        },
210        VerifyExpr::AtState { state, expr } => VerifyExpr::AtState {
211            state: Box::new(replace_t_with_t1(state)),
212            expr: Box::new(replace_t_with_t1(expr)),
213        },
214        VerifyExpr::Transition { from, to } => VerifyExpr::Transition {
215            from: Box::new(replace_t_with_t1(from)),
216            to: Box::new(replace_t_with_t1(to)),
217        },
218    }
219}
220
221/// CEGAR verification loop: abstract, check, refine.
222///
223/// 1. Build abstract model from current predicates
224/// 2. Check abstract model with k-induction
225/// 3. If abstract model is safe, return Safe
226/// 4. If abstract counterexample found, check concreteness via BMC
227/// 5. If concrete, return Unsafe
228/// 6. If spurious, extract new predicates from the counterexample and refine
229pub fn cegar_verify(
230    init: &VerifyExpr,
231    transition: &VerifyExpr,
232    property: &VerifyExpr,
233    initial_predicates: &[VerifyExpr],
234    max_refinements: u32,
235) -> AbstractionResult {
236    let mut predicates = initial_predicates.to_vec();
237
238    for _iteration in 0..max_refinements {
239        // Build the abstract model
240        let abs_model = abstract_model_full(init, transition, &predicates);
241
242        // Verify the abstract model using k-induction.
243        let abs_result = kinduction::k_induction(
244            &abs_model.abstract_init,
245            &abs_model.abstract_transition,
246            property,
247            &[],
248            10,
249        );
250
251        match abs_result {
252            kinduction::KInductionResult::Proven { .. } => {
253                // Abstract model proved property safe. Since predicate abstraction
254                // is an overapproximation (when inductive predicates are used as
255                // strengthening), safety of the abstract model implies safety of
256                // the concrete model.
257                return AbstractionResult::Safe;
258            }
259            kinduction::KInductionResult::Counterexample { trace: _, k } => {
260                // Abstract counterexample found. Check if it is concrete
261                // by running k-induction on the concrete model.
262                let concrete_result =
263                    kinduction::k_induction(init, transition, property, &[], k.max(10));
264
265                match concrete_result {
266                    kinduction::KInductionResult::Counterexample { trace: ctrace, .. } => {
267                        return AbstractionResult::Unsafe {
268                            concrete_trace: ctrace,
269                        };
270                    }
271                    kinduction::KInductionResult::Proven { .. } => {
272                        // Spurious. Refine.
273                        let new_preds = extract_refinement_predicates(
274                            init,
275                            transition,
276                            property,
277                            &predicates,
278                            k,
279                        );
280                        if new_preds.is_empty() {
281                            return AbstractionResult::SpuriousRefined {
282                                new_predicates: predicates,
283                            };
284                        }
285                        predicates.extend(new_preds);
286                    }
287                    _ => {
288                        // Inconclusive — try refining.
289                        let new_preds = extract_refinement_predicates(
290                            init,
291                            transition,
292                            property,
293                            &predicates,
294                            k,
295                        );
296                        if new_preds.is_empty() {
297                            return AbstractionResult::SpuriousRefined {
298                                new_predicates: predicates,
299                            };
300                        }
301                        predicates.extend(new_preds);
302                    }
303                }
304            }
305            kinduction::KInductionResult::InductionFailed { k, .. } => {
306                // k-induction couldn't prove or disprove on abstract model.
307                // Fall back to concrete check.
308                let concrete_result =
309                    kinduction::k_induction(init, transition, property, &[], k.max(10));
310                match concrete_result {
311                    kinduction::KInductionResult::Proven { .. } => {
312                        return AbstractionResult::Safe;
313                    }
314                    kinduction::KInductionResult::Counterexample { trace, .. } => {
315                        return AbstractionResult::Unsafe {
316                            concrete_trace: trace,
317                        };
318                    }
319                    _ => {
320                        let new_preds = extract_refinement_predicates(
321                            init,
322                            transition,
323                            property,
324                            &predicates,
325                            k,
326                        );
327                        if new_preds.is_empty() {
328                            return AbstractionResult::Unknown;
329                        }
330                        predicates.extend(new_preds);
331                    }
332                }
333            }
334            kinduction::KInductionResult::Unknown => {
335                return AbstractionResult::Unknown;
336            }
337        }
338    }
339
340    // Exhausted refinement budget — try one final concrete check
341    let final_result = kinduction::k_induction(init, transition, property, &[], 10);
342    match final_result {
343        kinduction::KInductionResult::Proven { .. } => AbstractionResult::Safe,
344        kinduction::KInductionResult::Counterexample { trace, .. } => AbstractionResult::Unsafe {
345            concrete_trace: trace,
346        },
347        _ => AbstractionResult::Unknown,
348    }
349}
350
351/// Extract refinement predicates from a spurious counterexample.
352///
353/// When an abstract counterexample is spurious, we need new predicates to
354/// eliminate it. The strategy:
355///
356/// 1. Collect all subexpressions of the transition and property that are
357///    comparison predicates (>=, <=, >, <, ==, !=).
358/// 2. Filter out predicates already in the set.
359/// 3. Return the new ones as refinement candidates.
360///
361/// This is a simplified form of Craig interpolation — we extract predicates
362/// from the structure of the transition relation and property.
363fn extract_refinement_predicates(
364    init: &VerifyExpr,
365    transition: &VerifyExpr,
366    property: &VerifyExpr,
367    existing_predicates: &[VerifyExpr],
368    _depth: u32,
369) -> Vec<VerifyExpr> {
370    let mut candidates = Vec::new();
371
372    // Collect comparison subexpressions from transition, init, property
373    collect_comparison_predicates(transition, &mut candidates);
374    collect_comparison_predicates(init, &mut candidates);
375    collect_comparison_predicates(property, &mut candidates);
376
377    // Also generate weakened/strengthened versions of existing predicates
378    for pred in existing_predicates {
379        if let VerifyExpr::Binary { op, left, right } = pred {
380            match op {
381                VerifyOp::Gte | VerifyOp::Gt | VerifyOp::Lte | VerifyOp::Lt => {
382                    if let VerifyExpr::Int(n) = right.as_ref() {
383                        candidates.push(VerifyExpr::binary(
384                            *op,
385                            *left.clone(),
386                            VerifyExpr::int(n + 1),
387                        ));
388                        candidates.push(VerifyExpr::binary(
389                            *op,
390                            *left.clone(),
391                            VerifyExpr::int(n - 1),
392                        ));
393                    }
394                }
395                _ => {}
396            }
397        }
398    }
399
400    // Deduplicate and remove existing predicates (and remove the property itself)
401    let existing_dbg: HashSet<String> = existing_predicates
402        .iter()
403        .map(|p| format!("{:?}", p))
404        .collect();
405
406    let mut seen = HashSet::new();
407    let mut result = Vec::new();
408    for candidate in candidates {
409        let dbg = format!("{:?}", candidate);
410        if !existing_dbg.contains(&dbg) && seen.insert(dbg) {
411            result.push(candidate);
412        }
413    }
414
415    result
416}
417
418/// Collect all comparison subexpressions from an expression.
419fn collect_comparison_predicates(expr: &VerifyExpr, out: &mut Vec<VerifyExpr>) {
420    match expr {
421        VerifyExpr::Binary { op, left, right } => {
422            match op {
423                VerifyOp::Gte
424                | VerifyOp::Gt
425                | VerifyOp::Lte
426                | VerifyOp::Lt
427                | VerifyOp::Eq
428                | VerifyOp::Neq => {
429                    out.push(expr.clone());
430                }
431                _ => {}
432            }
433            collect_comparison_predicates(left, out);
434            collect_comparison_predicates(right, out);
435        }
436        VerifyExpr::Not(inner) => collect_comparison_predicates(inner, out),
437        VerifyExpr::Iff(l, r) => {
438            collect_comparison_predicates(l, out);
439            collect_comparison_predicates(r, out);
440        }
441        VerifyExpr::ForAll { body, .. } | VerifyExpr::Exists { body, .. } => {
442            collect_comparison_predicates(body, out);
443        }
444        _ => {}
445    }
446}
447
448/// Encode a VerifyExpr to Z3 Bool (local helper, similar to ic3's encode_bool).
449fn encode_bool(expr: &VerifyExpr) -> Bool {
450    let mut bool_vars = HashMap::new();
451    let mut int_vars = HashMap::new();
452    let mut all_vars = HashSet::new();
453    crate::equivalence::collect_vars_pub(expr, &mut all_vars);
454    for name in &all_vars {
455        bool_vars.insert(name.clone(), Bool::new_const(name.as_str()));
456    }
457    crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
458    kinduction::encode_expr_bool(expr, &bool_vars, &int_vars)
459}