Skip to main content

bitwright/mba/
solve.rs

1//! The MBA service's extension points: solvers, provers, caches, and the native signature
2//! solver.
3
4use std::collections::{HashMap, VecDeque};
5use std::sync::Mutex;
6
7use super::expr::{MOp, MbaExpr};
8use crate::ops::{BinOp, UnOp};
9use crate::{BitVec, Width};
10
11/// What a solver may spend on one question. Solvers treat it as a hint; the engine enforces its
12/// own budget on calls.
13#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub struct MbaBudget {
16    /// A work bound in the solver's own units, for one question. In the engine a question
17    /// runs within the least of this and what is left of the run's
18    /// [`Budget::mba_steps`](crate::engine::Budget::mba_steps).
19    pub steps: u64,
20    /// Whether answers should carry the solver's own evidence (default true). A caller that
21    /// proves every answer itself asks without, and a solver may then skip checking an answer
22    /// it built exactly (answering [`Claim::Unverified`]); the engine does so when backend
23    /// certificates are not trusted.
24    pub evidence: bool,
25}
26
27impl Default for MbaBudget {
28    fn default() -> Self {
29        MbaBudget {
30            steps: 1 << 20,
31            evidence: true,
32        }
33    }
34}
35
36setters!(MbaBudget {
37    with_steps: steps: u64,
38    with_evidence: evidence: bool,
39});
40
41/// The evidence a solver attaches to an answer.
42#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
43#[non_exhaustive]
44pub enum Claim {
45    /// None.
46    Unverified,
47    /// Agreement at sampled points only.
48    Sampled,
49    /// Proved (for example by an SMT solver, or by a complete method).
50    Proved,
51    /// A checked certificate (for example a replayed proof).
52    Certified,
53}
54
55/// A solver's answer.
56#[derive(Clone, Debug, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum MbaAnswer {
59    /// An equivalent expression over the same variables, and the evidence for it.
60    Simplified {
61        /// The simpler expression.
62        expr: MbaExpr,
63        /// Its evidence.
64        claim: Claim,
65    },
66    /// The input is already as simple as this solver can make it (a complete answer).
67    NoSimpler,
68    /// The solver does not handle this input.
69    Unsupported(String),
70    /// The solver ran out of budget (never cached).
71    Exhausted,
72}
73
74/// A backend that simplifies MBA expressions.
75pub trait MbaSolver: Send + Sync {
76    /// A stable name, including anything that changes answers (it keys the caches).
77    fn id(&self) -> &str;
78    /// Simplifies `p`.
79    fn solve(&self, p: &MbaExpr, budget: &MbaBudget) -> MbaAnswer;
80    /// Simplifies `p`, and says how many of `budget`'s steps it spent: what the engine charges
81    /// the call against [`Budget::mba_steps`](crate::engine::Budget::mba_steps). A solver that
82    /// counts its work reports what it spent, and a remembered answer what finding it cost, so
83    /// that a charge does not depend on what the solver remembers. This default is
84    /// [`solve`](Self::solve) charged its whole limit (`budget.steps`), the most a solver that
85    /// keeps to its budget spends.
86    fn solve_counted(&self, p: &MbaExpr, budget: &MbaBudget) -> (MbaAnswer, u64) {
87        (self.solve(p, budget), budget.steps)
88    }
89    /// Whether `Phase::Mba` should also ask about polynomials: fragments without bitwise
90    /// operators in which two non-constants are multiplied, and fragments rooted at a constant
91    /// left shift. By default only mixed fragments (arithmetic and bitwise operators) rooted at
92    /// `+ − · neg & | ^ ~` are asked about.
93    fn polynomial_fragments(&self) -> bool {
94        false
95    }
96}
97
98/// The outcome of an equivalence proof attempt.
99#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
100#[non_exhaustive]
101pub enum Verdict {
102    /// Equal on every input.
103    Proved,
104    /// Different on some input.
105    Refuted,
106    /// Not decided.
107    Unknown,
108}
109
110/// A backend that proves two MBA expressions equal.
111pub trait EquivalenceProver: Send + Sync {
112    /// A stable name (it keys the caches).
113    fn id(&self) -> &str;
114    /// Decides whether `a` and `b` are equal on every input.
115    fn prove_equal(&self, a: &MbaExpr, b: &MbaExpr, budget: &MbaBudget) -> Verdict;
116}
117
118/// A cache key: the input's content hash, the solver and prover ids, and the lowering version.
119#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
120pub struct CacheKey(pub [u64; 2]);
121
122/// A durable cache entry: only verified results and complete "no simpler" answers.
123#[derive(Clone, Debug, PartialEq, Eq)]
124#[non_exhaustive]
125pub enum CacheEntry {
126    /// A verified simpler expression.
127    Simplified(MbaExpr),
128    /// The solver answered, completely, that nothing is simpler.
129    NoSimpler,
130}
131
132/// Where the MBA service keeps answers across calls. bitwright performs no IO: persistent
133/// stores belong to the host.
134pub trait MbaCacheStore: Send + Sync {
135    /// The entry for `k`.
136    fn get(&self, k: &CacheKey) -> Option<CacheEntry>;
137    /// Stores an entry.
138    fn put(&self, k: &CacheKey, e: &CacheEntry);
139}
140
141/// A cache that keeps nothing.
142#[derive(Copy, Clone, Debug, Default)]
143pub struct NoCache;
144
145impl MbaCacheStore for NoCache {
146    fn get(&self, _: &CacheKey) -> Option<CacheEntry> {
147        None
148    }
149    fn put(&self, _: &CacheKey, _: &CacheEntry) {}
150}
151
152/// A bounded in-memory cache (oldest entries evicted first).
153#[derive(Debug)]
154pub struct MemoryCache {
155    capacity: usize,
156    inner: Mutex<(HashMap<CacheKey, CacheEntry>, VecDeque<CacheKey>)>,
157}
158
159impl MemoryCache {
160    /// A cache of at most `capacity` entries.
161    pub fn new(capacity: usize) -> MemoryCache {
162        MemoryCache {
163            capacity,
164            inner: Mutex::new((HashMap::new(), VecDeque::new())),
165        }
166    }
167
168    /// The number of entries.
169    pub fn len(&self) -> usize {
170        self.inner.lock().map_or(0, |g| g.0.len())
171    }
172
173    /// Whether it is empty.
174    pub fn is_empty(&self) -> bool {
175        self.len() == 0
176    }
177}
178
179impl MbaCacheStore for MemoryCache {
180    fn get(&self, k: &CacheKey) -> Option<CacheEntry> {
181        self.inner.lock().ok()?.0.get(k).cloned()
182    }
183
184    fn put(&self, k: &CacheKey, e: &CacheEntry) {
185        let Ok(mut g) = self.inner.lock() else {
186            return;
187        };
188        if self.capacity == 0 {
189            return;
190        }
191        if g.0.insert(*k, e.clone()).is_none() {
192            g.1.push_back(*k);
193        }
194        while g.0.len() > self.capacity {
195            match g.1.pop_front() {
196                Some(old) => {
197                    g.0.remove(&old);
198                }
199                None => break,
200            }
201        }
202    }
203}
204
205/// The native solver: complete for linear MBA (arithmetic over bitwise functions of the
206/// variables), from the values at the all-zero/all-ones corners. It answers with the affine form
207/// when there is one, or the combination of the variables' conjunctions, and "no simpler" when
208/// that is not smaller; other inputs are unsupported.
209#[derive(Copy, Clone, Debug, Default)]
210pub struct SignatureSolver;
211
212/// The most variables the signature solver takes (2^t corners).
213const SIGNATURE_MAX_VARS: usize = 10;
214
215/// Node evaluations per step of the signature solver's work (as the normal-form solver counts
216/// its certificates').
217const SIGNATURE_EVALS_PER_STEP: u64 = 32;
218
219impl MbaSolver for SignatureSolver {
220    fn id(&self) -> &str {
221        "bitwright.signature.v1"
222    }
223
224    fn solve(&self, p: &MbaExpr, budget: &MbaBudget) -> MbaAnswer {
225        self.solve_counted(p, budget).0
226    }
227
228    /// Its work is evaluating the input at the 2^t corners, counted as the normal-form solver
229    /// counts certificate evaluations (a step per 32 node evaluations); a signature that does
230    /// not fit `budget.steps` is not computed (exhausted, nothing spent).
231    fn solve_counted(&self, p: &MbaExpr, budget: &MbaBudget) -> (MbaAnswer, u64) {
232        if !p.is_linear() {
233            return (MbaAnswer::Unsupported("not a linear MBA".into()), 0);
234        }
235        let t = p.vars().len();
236        if t > SIGNATURE_MAX_VARS || p.vars().iter().any(|&w| Some(w) != p.width()) {
237            let why = "too many variables, or mixed widths";
238            return (MbaAnswer::Unsupported(why.into()), 0);
239        }
240        let steps = ((p.nodes().len() as u64) << t).div_ceil(SIGNATURE_EVALS_PER_STEP);
241        if steps > budget.steps {
242            return (MbaAnswer::Exhausted, 0);
243        }
244        let Some(sig) = p.corners() else {
245            return (MbaAnswer::Unsupported("no signature".into()), steps);
246        };
247        let Some(w) = p.width() else {
248            return (MbaAnswer::Unsupported("empty".into()), steps);
249        };
250        let d = mobius(&sig);
251        let m = conjunction_form(p.vars(), w, &d);
252        let answer = match m {
253            Some(m) if m.nodes().len() < p.nodes().len() => MbaAnswer::Simplified {
254                expr: m,
255                claim: Claim::Proved,
256            },
257            _ => MbaAnswer::NoSimpler,
258        };
259        (answer, steps)
260    }
261}
262
263/// The conjunction coefficients `d_S` from corner values: `−E(p) = Σ_{S ⊆ p} d_S`.
264pub(crate) fn mobius(sig: &[BitVec]) -> Vec<BitVec> {
265    let mut d: Vec<BitVec> = sig
266        .iter()
267        .map(|v| BitVec::un_unchecked(UnOp::Neg, v))
268        .collect();
269    let n = d.len();
270    let mut bit = 1;
271    while bit < n {
272        for p in 0..n {
273            if p & bit != 0 {
274                d[p] = BitVec::bin_unchecked(BinOp::Sub, &d[p], &d[p ^ bit]);
275            }
276        }
277        bit <<= 1;
278    }
279    d
280}
281
282/// `Σ_S d_S · AND_S` (with `AND_∅ = −1`) as an expression: the constant first, then each
283/// conjunction with its coefficient.
284fn conjunction_form(vars: &[Width], w: Width, d: &[BitVec]) -> Option<MbaExpr> {
285    let mut m = MbaExpr::new(vars.to_vec());
286    let var_nodes: Vec<u32> = (0..vars.len() as u32)
287        .map(|i| m.push(MOp::Var(i), &[]))
288        .collect::<Result<_, _>>()
289        .ok()?;
290    let konst = BitVec::un_unchecked(UnOp::Neg, &d[0]);
291    let mut acc = m.push(MOp::Const(konst), &[]).ok()?;
292    let one = BitVec::one(w);
293    for (s, ds) in d.iter().enumerate().skip(1) {
294        if ds.is_zero() {
295            continue;
296        }
297        let mut conj: Option<u32> = None;
298        for (j, &v) in var_nodes.iter().enumerate() {
299            if s >> j & 1 == 1 {
300                conj = Some(match conj {
301                    None => v,
302                    Some(c) => m.push(MOp::And, &[c, v]).ok()?,
303                });
304            }
305        }
306        let conj = conj?;
307        let term = if *ds == one {
308            conj
309        } else {
310            let k = m.push(MOp::Const(*ds), &[]).ok()?;
311            m.push(MOp::Mul, &[conj, k]).ok()?
312        };
313        acc = m.push(MOp::Add, &[acc, term]).ok()?;
314    }
315    Some(m)
316}