Skip to main content

logicaffeine_verify/
compositional.rs

1//! Assume-Guarantee Compositional Reasoning
2//!
3//! Decompose verification into per-component proofs with interface contracts.
4//! Each component has assumptions (what it requires from environment) and
5//! guarantees (what it provides). Verify each component independently.
6
7use crate::equivalence::Trace;
8use crate::ir::VerifyExpr;
9use crate::kinduction;
10use std::collections::HashMap;
11
12/// A component specification for compositional verification.
13#[derive(Debug, Clone)]
14pub struct ComponentSpec {
15    pub name: String,
16    pub assumes: Vec<VerifyExpr>,
17    pub guarantees: Vec<VerifyExpr>,
18    pub init: VerifyExpr,
19    pub transition: VerifyExpr,
20}
21
22/// Result of compositional verification.
23#[derive(Debug)]
24pub enum CompositionalResult {
25    /// All components verified.
26    AllVerified,
27    /// A component failed verification.
28    ComponentFailed { name: String, trace: Trace },
29    /// Circular dependency detected.
30    CircularDependency { components: Vec<String> },
31    /// Could not determine.
32    Unknown,
33}
34
35/// Verify a set of components compositionally.
36///
37/// For each component:
38/// 1. Assume all assumptions hold
39/// 2. Verify all guarantees under those assumptions
40/// 3. Check that each component's guarantees discharge other components' assumptions
41pub fn verify_compositional(components: &[ComponentSpec]) -> CompositionalResult {
42    if components.is_empty() {
43        return CompositionalResult::AllVerified;
44    }
45
46    // Phase 1: Verify each component in isolation (assumptions → guarantees)
47    for comp in components {
48        for guarantee in &comp.guarantees {
49            // Check: init AND assumptions AND transition → guarantee
50            let assumptions = if comp.assumes.is_empty() {
51                VerifyExpr::bool(true)
52            } else {
53                comp.assumes
54                    .iter()
55                    .cloned()
56                    .reduce(|a, b| VerifyExpr::and(a, b))
57                    .unwrap()
58            };
59
60            // Use k-induction to verify: under assumptions, guarantee holds
61            let strengthened_init = VerifyExpr::and(comp.init.clone(), assumptions.clone());
62            let strengthened_transition =
63                VerifyExpr::and(comp.transition.clone(), assumptions.clone());
64
65            let result = kinduction::k_induction(
66                &strengthened_init,
67                &strengthened_transition,
68                guarantee,
69                &[],
70                10,
71            );
72
73            match result {
74                kinduction::KInductionResult::Counterexample { trace, .. } => {
75                    return CompositionalResult::ComponentFailed {
76                        name: comp.name.clone(),
77                        trace,
78                    };
79                }
80                kinduction::KInductionResult::Proven { .. } => {
81                    // This guarantee verified
82                }
83                _ => {
84                    // Inconclusive — try IC3 as fallback
85                    let ic3_result = crate::ic3::ic3(
86                        &strengthened_init,
87                        &strengthened_transition,
88                        guarantee,
89                        10,
90                    );
91                    match ic3_result {
92                        crate::ic3::Ic3Result::Safe { .. } => {}
93                        crate::ic3::Ic3Result::Unsafe { trace } => {
94                            return CompositionalResult::ComponentFailed {
95                                name: comp.name.clone(),
96                                trace,
97                            };
98                        }
99                        _ => return CompositionalResult::Unknown,
100                    }
101                }
102            }
103        }
104    }
105
106    // Phase 2: Check that guarantees discharge assumptions
107    // For each component A's assumption, check that some component B's guarantee covers it
108    // (simplified: check that the conjunction of all guarantees implies each assumption)
109    let all_guarantees: Vec<VerifyExpr> = components
110        .iter()
111        .flat_map(|c| c.guarantees.clone())
112        .collect();
113
114    if !all_guarantees.is_empty() {
115        let guarantees_conj = all_guarantees
116            .iter()
117            .cloned()
118            .reduce(|a, b| VerifyExpr::and(a, b))
119            .unwrap();
120
121        for comp in components {
122            for assumption in &comp.assumes {
123                // Check: guarantees_conj → assumption
124                let check = VerifyExpr::implies(guarantees_conj.clone(), assumption.clone());
125                let solver = crate::solver::new_solver();
126                let not_check = VerifyExpr::not(check);
127                let encoded = encode_bool(&not_check);
128                solver.assert(&encoded);
129                match solver.check() {
130                    z3::SatResult::Sat => {
131                        // Guarantee doesn't cover assumption — could be circular
132                        // For now, report as circular dependency
133                        return CompositionalResult::CircularDependency {
134                            components: vec![comp.name.clone()],
135                        };
136                    }
137                    z3::SatResult::Unsat => {} // Good: guarantees discharge assumption
138                    z3::SatResult::Unknown => return CompositionalResult::Unknown,
139                }
140            }
141        }
142    }
143
144    CompositionalResult::AllVerified
145}
146
147fn encode_bool(expr: &VerifyExpr) -> z3::ast::Bool {
148    let mut bool_vars = HashMap::new();
149    let mut int_vars = HashMap::new();
150    let mut all_vars = std::collections::HashSet::new();
151    crate::equivalence::collect_vars_pub(expr, &mut all_vars);
152    for name in &all_vars {
153        bool_vars.insert(name.clone(), z3::ast::Bool::new_const(name.as_str()));
154    }
155    crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
156    kinduction::encode_expr_bool(expr, &bool_vars, &int_vars)
157}