elinvar-engine 0.1.2

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! LOGIC.md section 13: the solver on traces against brute force. With
//! symmetry breaking off, the traces the solver enumerates, over every
//! shape up to the limit on steps, are those brute force finds; with it on,
//! both agree on whether there is any. Formulas come from a seeded
//! generator, so a failure is reproduced from its seed.

#![allow(clippy::unwrap_used)] // test helpers, as clippy.toml allows in tests

use elinvar_engine::logic::{
    BinaryOp, Bounds, Decl, Expr, Formula, Quantifier, Relation, TemporalBinaryOp, TemporalOp,
    Trace, TupleSet, Universe, Variable, count_traces, evaluate_trace, traces,
};
use elinvar_engine::{Finder, Next, Options};
use std::collections::BTreeSet;

struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }

    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }
}

fn set(rng: &mut Rng, sets: &[Expr], depth: u32) -> Expr {
    if depth == 0 || rng.below(3) == 0 {
        let i = rng.below(sets.len() as u64 + 2) as usize;
        return match i.checked_sub(sets.len()) {
            None => sets[i].clone(),
            Some(0) => Expr::univ(),
            Some(_) => Expr::none(),
        };
    }
    match rng.below(4) {
        0 => set(rng, sets, depth - 1).prime(),
        _ => {
            let op = [
                BinaryOp::Union,
                BinaryOp::Intersection,
                BinaryOp::Difference,
            ][rng.below(3) as usize];
            set(rng, sets, depth - 1).apply_binary(op, &set(rng, sets, depth - 1))
        }
    }
}

fn formula(rng: &mut Rng, sets: &[Expr], depth: u32) -> Formula {
    if depth == 0 {
        return match rng.below(3) {
            0 => set(rng, sets, 1).some(),
            1 => set(rng, sets, 1).no(),
            _ => set(rng, sets, 1).is_in(&set(rng, sets, 1)),
        };
    }
    match rng.below(10) {
        // Quantifiers around temporal bodies: skolemization must replace
        // the variable inside them.
        8 | 9 => {
            let q = [Quantifier::All, Quantifier::Some, Quantifier::No][rng.below(3) as usize];
            let v = Variable::new(format!("v{depth}"));
            let range = set(rng, sets, 1);
            let mut inner = sets.to_vec();
            inner.push(Expr::variable(&v));
            Formula::quantified(
                q,
                vec![Decl::new(&v, &range)],
                &formula(rng, &inner, depth - 1),
            )
        }
        0 => formula(rng, sets, depth - 1).not(),
        1 => formula(rng, sets, depth - 1).and(&formula(rng, sets, depth - 1)),
        2 => formula(rng, sets, depth - 1).or(&formula(rng, sets, depth - 1)),
        3 | 4 => {
            let op = [
                TemporalOp::After,
                TemporalOp::Always,
                TemporalOp::Eventually,
                TemporalOp::Before,
                TemporalOp::Historically,
                TemporalOp::Once,
            ][rng.below(6) as usize];
            formula(rng, sets, depth - 1).temporal(op)
        }
        5 => {
            let op = [
                TemporalBinaryOp::Until,
                TemporalBinaryOp::Releases,
                TemporalBinaryOp::Since,
                TemporalBinaryOp::Triggered,
            ][rng.below(4) as usize];
            formula(rng, sets, depth - 1).temporal_binary(op, &formula(rng, sets, depth - 1))
        }
        _ => set(rng, sets, depth - 1).equals(&set(rng, sets, depth - 1)),
    }
}

fn key(t: &Trace) -> String {
    serde_json::to_string(t).unwrap()
}

/// The trace without the skolem relations that name witnesses, so it can
/// be compared with brute force's.
fn user_part(t: &Trace, b: &Bounds) -> Trace {
    let mut fixed = elinvar_engine::logic::Instance::new(b.universe());
    for (r, s) in t.fixed().entries() {
        if b.contains(r) {
            fixed.set(r, s.clone()).unwrap();
        }
    }
    Trace::new(fixed, t.states().to_vec(), t.loop_to()).unwrap()
}

#[test]
fn random_temporal_formulas_agree_with_brute_force() {
    const STEPS: usize = 3;
    let (mut sat, mut unsat) = (0, 0);
    for seed in 0..300u64 {
        let mut rng = Rng(seed);
        let u = Universe::new(["A", "B"]).unwrap();
        let fixed = Relation::unary("s");
        let changing = Relation::changing("c", 1);
        let mut b = Bounds::new(&u);
        let mut lower = TupleSet::empty(&u, 1).unwrap();
        if rng.below(3) == 0 {
            lower.insert_index(0).unwrap();
        }
        b.bound(&fixed, lower, u.all(1).unwrap()).unwrap();
        b.bound_upper(&changing, u.all(1).unwrap()).unwrap();
        let sets = [Expr::relation(&fixed), Expr::relation(&changing)];
        let f = formula(&mut rng, &sets, 3);

        let mut brute = BTreeSet::new();
        for l in 1..=STEPS {
            for j in 0..l {
                for t in traces(&b, l, j, 20).unwrap() {
                    if evaluate_trace(&t, &f).unwrap() {
                        brute.insert(key(&t));
                    }
                }
            }
        }
        let off = Options::default().symmetry_breaking(false).steps(STEPS);
        let mut finder = Finder::new(&b, &f, &off).unwrap();
        let mut solved = BTreeSet::new();
        loop {
            match finder.next_instance() {
                Next::Trace(t) => {
                    solved.insert(key(&user_part(&t, &b)));
                }
                Next::Done => break,
                other => panic!("seed {seed}: {other:?}"),
            }
        }
        assert_eq!(solved, brute, "seed {seed}: {f}");

        let on = Options::default().steps(STEPS);
        let any = matches!(
            Finder::new(&b, &f, &on).unwrap().next_instance(),
            Next::Trace(_)
        );
        assert_eq!(
            any,
            !brute.is_empty(),
            "seed {seed} with symmetry breaking: {f}"
        );
        if brute.is_empty() {
            unsat += 1;
        } else {
            sat += 1;
        }
    }
    assert!(sat >= 80 && unsat >= 30, "{sat} satisfiable, {unsat} not");
}

#[test]
fn count_traces_matches_a_hand_count() {
    // One atom, a changing set, two states looping to 0: 4 traces, of which
    // `always some c` holds on 1 and `eventually some c` on 3.
    let u = Universe::new(["A"]).unwrap();
    let c = Relation::changing("c", 1);
    let mut b = Bounds::new(&u);
    b.bound_upper(&c, u.all(1).unwrap()).unwrap();
    let ce = Expr::relation(&c);
    assert_eq!(count_traces(&b, &ce.some().always(), 2, 0, 8).unwrap(), 1);
    assert_eq!(
        count_traces(&b, &ce.some().eventually(), 2, 0, 8).unwrap(),
        3
    );
}