Skip to main content

logicaffeine_verify/
consistency.rs

1//! Multi-Property Consistency Checking
2//!
3//! Check if a set of properties can all hold simultaneously.
4//! Conjoin all properties, check Z3 satisfiability.
5//! If UNSAT → extract minimal unsatisfiable subset (MUS).
6//! If SAT → check for vacuity and redundancy.
7
8use crate::equivalence::Trace;
9use crate::ir::{VerifyExpr, VerifyOp};
10use std::collections::{HashMap, HashSet};
11use z3::{ast::Bool, ast::Int, SatResult, Solver};
12
13// ═══════════════════════════════════════════════════════════════════════════
14// LEGACY API (backward compatibility)
15// ═══════════════════════════════════════════════════════════════════════════
16
17/// Result of consistency checking (legacy API).
18#[derive(Debug)]
19pub enum ConsistencyResult {
20    /// All properties can hold simultaneously.
21    Consistent,
22    /// At least two properties conflict. Returns the conflicting pair indices
23    /// and a witness trace showing the contradiction.
24    Inconsistent {
25        conflicting: Vec<(usize, usize)>,
26        witness: Trace,
27    },
28    /// Z3 returned unknown.
29    Unknown,
30}
31
32/// Check if a set of properties can all hold simultaneously (legacy API).
33///
34/// Conjoins all properties and checks Z3 satisfiability.
35/// If UNSAT, identifies the conflicting pair(s).
36pub fn check_consistency(
37    props: &[VerifyExpr],
38    signals: &[String],
39    bound: usize,
40) -> ConsistencyResult {
41    if props.is_empty() {
42        return ConsistencyResult::Consistent;
43    }
44
45    let solver = crate::solver::new_solver();
46
47    // Declare all signal@timestep variables
48    let mut var_map: HashMap<String, Bool> = HashMap::new();
49    for sig in signals {
50        for t in 0..=bound {
51            let var_name = format!("{}@{}", sig, t);
52            var_map.insert(var_name.clone(), Bool::new_const(var_name.as_str()));
53        }
54    }
55
56    // Collect all variables from all properties
57    let mut all_vars: HashSet<String> = HashSet::new();
58    for prop in props {
59        crate::equivalence::collect_vars_pub(prop, &mut all_vars);
60    }
61    for var_name in &all_vars {
62        if !var_map.contains_key(var_name) {
63            var_map.insert(var_name.clone(), Bool::new_const(var_name.as_str()));
64        }
65    }
66
67    // Encode and conjoin all properties
68    let empty_int_vars = HashMap::new();
69    let empty_bv_vars = HashMap::new();
70    let empty_array_vars = HashMap::new();
71    let encoder = crate::equivalence::EquivEncoder::new(
72        &var_map,
73        &empty_int_vars,
74        &empty_bv_vars,
75        &empty_array_vars,
76    );
77    for prop in props {
78        let encoded = encoder.encode_as_bool(prop);
79        solver.assert(&encoded);
80    }
81
82    match solver.check() {
83        SatResult::Sat => ConsistencyResult::Consistent,
84        SatResult::Unsat => {
85            // Find conflicting pairs by checking each pair
86            let mut conflicting = Vec::new();
87            for i in 0..props.len() {
88                for j in (i + 1)..props.len() {
89                    let pair_solver = crate::solver::new_solver();
90                    let ei = encoder.encode_as_bool(&props[i]);
91                    let ej = encoder.encode_as_bool(&props[j]);
92                    pair_solver.assert(&ei);
93                    pair_solver.assert(&ej);
94                    if pair_solver.check() == SatResult::Unsat {
95                        conflicting.push((i, j));
96                    }
97                }
98            }
99            ConsistencyResult::Inconsistent {
100                conflicting,
101                witness: Trace { cycles: vec![] },
102            }
103        }
104        SatResult::Unknown => ConsistencyResult::Unknown,
105    }
106}
107
108// ═══════════════════════════════════════════════════════════════════════════
109// NEW API: Spec Consistency Analysis
110// ═══════════════════════════════════════════════════════════════════════════
111
112/// A formula labeled with its source text for error reporting.
113#[derive(Debug, Clone)]
114pub struct LabeledFormula {
115    pub index: usize,
116    pub label: String,
117    pub expr: VerifyExpr,
118}
119
120/// Configuration for spec consistency analysis.
121#[derive(Debug, Clone)]
122pub struct ConsistencyConfig {
123    /// Z3 timeout per query in milliseconds.
124    pub timeout_ms: u64,
125    /// BMC bound for temporal unrolling (used by orchestrator, not by Z3 checks).
126    pub temporal_bound: u32,
127    /// Whether to check for vacuous implications.
128    pub check_vacuity: bool,
129    /// Whether to check for redundant formulas.
130    pub check_redundancy: bool,
131    /// Whether to identify pairwise conflicts (only runs when UNSAT).
132    pub check_pairwise: bool,
133}
134
135impl Default for ConsistencyConfig {
136    fn default() -> Self {
137        Self {
138            timeout_ms: 5000,
139            temporal_bound: 8,
140            check_vacuity: true,
141            check_redundancy: true,
142            check_pairwise: true,
143        }
144    }
145}
146
147/// Full consistency analysis report.
148#[derive(Debug)]
149pub struct ConsistencyReport {
150    pub satisfiability: SatisfiabilityResult,
151    pub vacuity: Vec<VacuityFinding>,
152    pub redundancies: Vec<RedundancyFinding>,
153    pub pairwise_conflicts: Vec<PairwiseConflict>,
154}
155
156/// Whether the conjunction of all formulas is satisfiable.
157#[derive(Debug, PartialEq)]
158pub enum SatisfiabilityResult {
159    /// All formulas can hold simultaneously.
160    Satisfiable,
161    /// The formulas are contradictory. `mus` contains the indices of
162    /// the Minimal Unsatisfiable Subset.
163    Unsatisfiable { mus: Vec<usize> },
164    /// Z3 returned unknown (timeout or undecidable).
165    Unknown,
166}
167
168/// A formula whose implication antecedent can never be satisfied.
169#[derive(Debug)]
170pub struct VacuityFinding {
171    pub formula_index: usize,
172    pub label: String,
173}
174
175/// A formula that is logically entailed by the remaining formulas.
176#[derive(Debug)]
177pub struct RedundancyFinding {
178    pub redundant_index: usize,
179    pub label: String,
180    pub entailed_by: Vec<usize>,
181}
182
183/// A pair of formulas that cannot hold simultaneously.
184#[derive(Debug)]
185pub struct PairwiseConflict {
186    pub i: usize,
187    pub j: usize,
188}
189
190// ═══════════════════════════════════════════════════════════════════════════
191// CORE ANALYSIS ENGINE
192// ═══════════════════════════════════════════════════════════════════════════
193
194/// Run full consistency analysis on a set of labeled formulas.
195///
196/// Orchestration order:
197/// 1. Check full conjunction satisfiability
198/// 2. If UNSAT → extract MUS, optionally run pairwise
199/// 3. If SAT → optionally run vacuity and redundancy checks
200pub fn check_spec_consistency(
201    formulas: &[LabeledFormula],
202    config: &ConsistencyConfig,
203) -> ConsistencyReport {
204    if formulas.is_empty() {
205        return ConsistencyReport {
206            satisfiability: SatisfiabilityResult::Satisfiable,
207            vacuity: vec![],
208            redundancies: vec![],
209            pairwise_conflicts: vec![],
210        };
211    }
212
213    // Collect all variable names from all formulas
214    let mut all_vars: HashSet<String> = HashSet::new();
215    for lf in formulas {
216        crate::equivalence::collect_vars_pub(&lf.expr, &mut all_vars);
217    }
218
219    // Declare all variables as Z3 Bools, and collect integer variables
220    let mut bool_vars: HashMap<String, Bool> = HashMap::new();
221    let mut int_vars: HashMap<String, Int> = HashMap::new();
222    for var_name in &all_vars {
223        bool_vars.insert(var_name.clone(), Bool::new_const(var_name.as_str()));
224    }
225    // Also detect integer variables from arithmetic contexts
226    let exprs: Vec<&VerifyExpr> = formulas.iter().map(|lf| &lf.expr).collect();
227    for expr in &exprs {
228        crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
229    }
230
231    let empty_bv_vars = HashMap::new();
232    let empty_array_vars = HashMap::new();
233    let encoder = crate::equivalence::EquivEncoder::new(
234        &bool_vars,
235        &int_vars,
236        &empty_bv_vars,
237        &empty_array_vars,
238    );
239
240    // Step 1: Check full conjunction satisfiability
241    let solver = crate::solver::new_solver();
242    for lf in formulas {
243        let encoded = encoder.encode_as_bool(&lf.expr);
244        solver.assert(&encoded);
245    }
246
247    match solver.check() {
248        SatResult::Sat => {
249            // Satisfiable — run vacuity and redundancy checks
250            let vacuity = if config.check_vacuity {
251                detect_vacuity(&encoder, formulas, config.timeout_ms)
252            } else {
253                vec![]
254            };
255
256            let redundancies = if config.check_redundancy {
257                detect_redundancy(&encoder, formulas, config.timeout_ms)
258            } else {
259                vec![]
260            };
261
262            // Skip pairwise when SAT — no pair can conflict if the full conjunction is SAT
263            ConsistencyReport {
264                satisfiability: SatisfiabilityResult::Satisfiable,
265                vacuity,
266                redundancies,
267                pairwise_conflicts: vec![],
268            }
269        }
270        SatResult::Unsat => {
271            // UNSAT — extract MUS
272            let mus = extract_mus(&encoder, formulas, config.timeout_ms);
273
274            // Optionally find all pairwise conflicts
275            let pairwise_conflicts = if config.check_pairwise {
276                detect_pairwise_conflicts(&encoder, formulas, config.timeout_ms)
277            } else {
278                vec![]
279            };
280
281            ConsistencyReport {
282                satisfiability: SatisfiabilityResult::Unsatisfiable { mus },
283                vacuity: vec![],
284                redundancies: vec![],
285                pairwise_conflicts,
286            }
287        }
288        SatResult::Unknown => ConsistencyReport {
289            satisfiability: SatisfiabilityResult::Unknown,
290            vacuity: vec![],
291            redundancies: vec![],
292            pairwise_conflicts: vec![],
293        },
294    }
295}
296
297// ═══════════════════════════════════════════════════════════════════════════
298// MUS EXTRACTION
299// ═══════════════════════════════════════════════════════════════════════════
300
301/// Deletion-based Minimal Unsatisfiable Subset extraction.
302///
303/// Precondition: the conjunction of all formulas is UNSAT.
304/// For each formula, checks whether removing it makes the remaining set SAT.
305/// If so, the formula is necessary for the contradiction (kept in MUS).
306/// If not, the formula is not necessary (removed from MUS).
307///
308/// O(n) Z3 calls.
309fn extract_mus(
310    encoder: &crate::equivalence::EquivEncoder,
311    formulas: &[LabeledFormula],
312    timeout_ms: u64,
313) -> Vec<usize> {
314    let n = formulas.len();
315    let mut in_mus: Vec<bool> = vec![true; n];
316
317    for i in 0..n {
318        // Try removing formula i — check if the rest is still UNSAT
319        let solver = Solver::new();
320        solver.set_params(&{
321            let mut params = z3::Params::new();
322            params.set_u32("timeout", timeout_ms as u32);
323            params
324        });
325
326        for j in 0..n {
327            if j == i || !in_mus[j] {
328                continue;
329            }
330            let encoded = encoder.encode_as_bool(&formulas[j].expr);
331            solver.assert(&encoded);
332        }
333
334        match solver.check() {
335            SatResult::Sat => {
336                // Removing i made it SAT → i is necessary for UNSAT → keep in MUS
337            }
338            SatResult::Unsat => {
339                // Still UNSAT without i → i is not necessary → remove from MUS
340                in_mus[i] = false;
341            }
342            SatResult::Unknown => {
343                // Conservative: keep it in MUS
344            }
345        }
346    }
347
348    in_mus
349        .iter()
350        .enumerate()
351        .filter(|(_, &b)| b)
352        .map(|(i, _)| i)
353        .collect()
354}
355
356// ═══════════════════════════════════════════════════════════════════════════
357// VACUITY DETECTION
358// ═══════════════════════════════════════════════════════════════════════════
359
360/// Extract the antecedent from an implication-shaped formula.
361///
362/// Looks through ForAll wrappers to find the implication core.
363fn extract_antecedent(expr: &VerifyExpr) -> Option<&VerifyExpr> {
364    match expr {
365        VerifyExpr::Binary {
366            op: VerifyOp::Implies,
367            left,
368            ..
369        } => Some(left),
370        VerifyExpr::ForAll { body, .. } => extract_antecedent(body),
371        _ => None,
372    }
373}
374
375/// Detect vacuously true implications.
376///
377/// For each formula with implication shape (P → Q), checks whether P
378/// can be satisfied under the context of all other formulas.
379/// If not, the implication is vacuously true.
380fn detect_vacuity(
381    encoder: &crate::equivalence::EquivEncoder,
382    formulas: &[LabeledFormula],
383    timeout_ms: u64,
384) -> Vec<VacuityFinding> {
385    let mut findings = Vec::new();
386
387    for i in 0..formulas.len() {
388        let antecedent = match extract_antecedent(&formulas[i].expr) {
389            Some(a) => a,
390            None => continue,
391        };
392
393        // Build context: conjunction of all other formulas
394        let solver = Solver::new();
395        solver.set_params(&{
396            let mut params = z3::Params::new();
397            params.set_u32("timeout", timeout_ms as u32);
398            params
399        });
400
401        for j in 0..formulas.len() {
402            if j == i {
403                continue;
404            }
405            let encoded = encoder.encode_as_bool(&formulas[j].expr);
406            solver.assert(&encoded);
407        }
408
409        // Assert the antecedent — can it be true?
410        let ante_encoded = encoder.encode_as_bool(antecedent);
411        solver.assert(&ante_encoded);
412
413        if solver.check() == SatResult::Unsat {
414            findings.push(VacuityFinding {
415                formula_index: i,
416                label: formulas[i].label.clone(),
417            });
418        }
419    }
420
421    findings
422}
423
424// ═══════════════════════════════════════════════════════════════════════════
425// REDUNDANCY DETECTION
426// ═══════════════════════════════════════════════════════════════════════════
427
428/// Detect formulas that are logically entailed by the remaining formulas.
429///
430/// For each formula F_i, checks whether context ∧ ¬F_i is satisfiable.
431/// If UNSAT, F_i is entailed by the others (redundant).
432fn detect_redundancy(
433    encoder: &crate::equivalence::EquivEncoder,
434    formulas: &[LabeledFormula],
435    timeout_ms: u64,
436) -> Vec<RedundancyFinding> {
437    let mut findings = Vec::new();
438
439    for i in 0..formulas.len() {
440        let solver = Solver::new();
441        solver.set_params(&{
442            let mut params = z3::Params::new();
443            params.set_u32("timeout", timeout_ms as u32);
444            params
445        });
446
447        // Assert all other formulas as context
448        for j in 0..formulas.len() {
449            if j == i {
450                continue;
451            }
452            let encoded = encoder.encode_as_bool(&formulas[j].expr);
453            solver.assert(&encoded);
454        }
455
456        // Assert the negation of F_i
457        let fi_encoded = encoder.encode_as_bool(&formulas[i].expr);
458        solver.assert(&fi_encoded.not());
459
460        if solver.check() == SatResult::Unsat {
461            // context ∧ ¬F_i is UNSAT → F_i is entailed by others
462            let entailed_by: Vec<usize> = (0..formulas.len()).filter(|&j| j != i).collect();
463            findings.push(RedundancyFinding {
464                redundant_index: i,
465                label: formulas[i].label.clone(),
466                entailed_by,
467            });
468        }
469    }
470
471    findings
472}
473
474// ═══════════════════════════════════════════════════════════════════════════
475// PAIRWISE CONFLICT DETECTION
476// ═══════════════════════════════════════════════════════════════════════════
477
478/// Identify all pairs of formulas that cannot hold simultaneously.
479///
480/// Only meaningful when the full conjunction is UNSAT.
481fn detect_pairwise_conflicts(
482    encoder: &crate::equivalence::EquivEncoder,
483    formulas: &[LabeledFormula],
484    timeout_ms: u64,
485) -> Vec<PairwiseConflict> {
486    let mut conflicts = Vec::new();
487
488    for i in 0..formulas.len() {
489        for j in (i + 1)..formulas.len() {
490            let solver = Solver::new();
491            solver.set_params(&{
492                let mut params = z3::Params::new();
493                params.set_u32("timeout", timeout_ms as u32);
494                params
495            });
496
497            let ei = encoder.encode_as_bool(&formulas[i].expr);
498            let ej = encoder.encode_as_bool(&formulas[j].expr);
499            solver.assert(&ei);
500            solver.assert(&ej);
501
502            if solver.check() == SatResult::Unsat {
503                conflicts.push(PairwiseConflict { i, j });
504            }
505        }
506    }
507
508    conflicts
509}