elinvar-engine 0.1.1

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! Coverage and behavioral tests for `diff_models`, `render_*`, and
//! `elinvar_engine::prelude` (DESIGN.md sections 9.2 and 9.5; REQUIREMENTS.md section 8).

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

use elinvar_engine::logic::{Expr, Instance, IntExpr, Relation, Universe};
use elinvar_engine::prelude::*;
use elinvar_engine::{
    DiagramFormat, DiffVerdict, diff_models, render_instance, render_report, render_trace,
};

#[test]
fn diff_models_handles_integers_temporal_and_mismatch_errors() {
    // 1. Models using integer expressions (exercises `rebind_int` and `rebind_expr`).
    let make_int_model = |min_sum: i64| {
        let mut m = Model::new();
        let item = m.set("Item");
        let ints = m.ints();
        let w = m.field_with("w", &item, Multiplicity::One, &ints);
        let v = Variable::new("i");
        let ve = Expr::variable(&v);
        let sum_all = IntExpr::sum_over(
            vec![Decl::new(&v, &item)],
            &IntExpr::if_then_else(
                &ve.join(&w).some(),
                &ve.join(&w).sum().plus(&IntExpr::constant(0)),
                &IntExpr::constant(1).negate(),
            ),
        );
        let positive = all([&item], |[i]| {
            i.join(&w)
                .sum()
                .gte(&IntExpr::constant(1))
                .and(&IntExpr::constant(1).to_set().is_in(&ints))
        });
        m.fact(positive);
        m.fact(item.count().gte(&IntExpr::constant(1)));
        m.fact(sum_all.gte(&IntExpr::constant(min_sum)));
        m
    };

    let old_int = make_int_model(1);
    let new_int = make_int_model(2);
    let rep = diff_models(&old_int, &new_int, 2, &Options::default());
    assert_eq!(rep.verdict, Some(DiffVerdict::Tightened));
    assert!(format!("{rep}").contains("diff: tightened"));
    assert_eq!(format!("{}", DiffVerdict::Tightened), "tightened");
    assert_eq!(format!("{}", DiffVerdict::Loosened), "loosened");
    assert_eq!(format!("{}", DiffVerdict::Diverged), "diverged");
    assert_eq!(format!("{}", DiffVerdict::Equivalent), "equivalent");
    assert_eq!(format!("{}", DiffVerdict::Unknown), "unknown");

    // 2. Models with temporal operators, prime, comprehension, and if-then-else.
    let make_temp = |strict: bool| {
        let mut m = Model::new();
        let s = m.changing_set("S");
        let v = Variable::new("x");
        let comp = Expr::comprehension(vec![Decl::new(&v, &s)], &Expr::variable(&v).is_in(&s));
        let ite = Expr::if_then_else(&s.some(), &comp, &Expr::none());
        m.fact(ite.is_in(&s));
        if strict {
            m.fact(always(s.prime().equals(&s)));
        } else {
            m.fact(eventually(s.some().until(&s.no())));
        }
        m
    };
    let rep_t = diff_models(
        &make_temp(false),
        &make_temp(true),
        2,
        &Options::default().steps(3),
    );
    assert_eq!(rep_t.verdict, Some(DiffVerdict::Diverged));
    assert!(format!("{rep_t}").contains("allowed by old, forbidden by new:"));
    assert!(format!("{rep_t}").contains("allowed by new, forbidden by old:"));

    // 3. Incompatible models: missing relation, arity mismatch, changing mismatch.
    let mut a = Model::new();
    let p = a.set("P");
    let _r = a.field("r", &p, &p);
    let _c = a.changing_set("C");
    let _only_old = a.set("OnlyOld");

    let mut b = Model::new();
    let pb = b.set("P");
    let _rb = b.subset("r", &pb); // arity 1 vs 2
    let _cb = b.set("C"); // fixed vs changing
    let _only_new = b.set("OnlyNew");

    let err_rep = diff_models(&a, &b, 2, &Options::default());
    assert_eq!(err_rep.verdict, None);
    assert_eq!(err_rep.errors.len(), 4);
    assert!(format!("{err_rep}").contains("model.diff_mismatch"));
}

#[test]
fn render_trace_report_and_ternary_relations() {
    // Ternary relation rendering in both DOT and Mermaid.
    let u = Universe::new(["A", "B", "C"]).unwrap();
    let tri = Relation::new("link", 3);
    let mut inst = Instance::new(&u);
    inst.set(&tri, u.tuple_set(3, &[&["A", "B", "C"]]).unwrap())
        .unwrap();
    let dot = render_instance(&inst, DiagramFormat::Dot);
    assert!(dot.contains("link[B]"), "{dot}");
    let mmd = render_instance(&inst, DiagramFormat::Mermaid);
    assert!(mmd.contains("link[B]"), "{mmd}");

    // Temporal model with action labels -> test render_trace and render_report.
    let mut m = Model::new();
    let item = m.set("Item");
    let held = m.changing_subset("Held", &item);
    m.fact(held.no());
    m.action("take", [&item], |s, [i]| {
        s.when(i.is_in(&held).not());
        s.add(&held, i);
    });
    let rep = m
        .check(&always(held.no()))
        .named("NeverHeld")
        .scope(2)
        .steps(3)
        .report();
    assert_eq!(rep.verdict, Some(Verdict::Counterexample));
    let trace = rep.trace.as_ref().unwrap();

    // Full trace and single-state trace in DOT and Mermaid.
    let full_dot = render_trace(trace, None, DiagramFormat::Dot);
    assert!(full_dot.contains("subgraph cluster_state_0"));
    assert!(full_dot.contains("next: take("));
    let single_dot = render_trace(trace, Some(0), DiagramFormat::Dot);
    assert!(single_dot.contains("label=\"state 0\""));
    let full_mmd = render_trace(trace, None, DiagramFormat::Mermaid);
    assert!(full_mmd.contains("subgraph state_0"));
    let single_mmd = render_trace(trace, Some(0), DiagramFormat::Mermaid);
    assert!(single_mmd.contains("subgraph state_0"));

    // render_report: valid trace, out-of-range state, and report with no instance/trace.
    assert!(render_report(&rep, None, DiagramFormat::Dot).is_ok());
    assert!(render_report(&rep, Some(0), DiagramFormat::Mermaid).is_ok());
    assert!(render_report(&rep, Some(99), DiagramFormat::Dot).is_err());

    let holds_rep = m
        .check(&always(held.is_in(&item)))
        .named("AlwaysInItem")
        .scope(2)
        .steps(3)
        .report();
    assert_eq!(holds_rep.verdict, Some(Verdict::Holds));
    assert!(render_report(&holds_rep, None, DiagramFormat::Dot).is_err());

    // Static instance report.
    let mut s = Model::new();
    let x = s.set("X");
    let found = s.run(&x.some()).scope(2).report();
    assert!(render_report(&found, None, DiagramFormat::Mermaid).is_ok());
}

#[test]
fn prelude_quantifiers_and_temporal_helpers() {
    let mut m = Model::new();
    let s = m.changing_set("S");
    let f = all([&s], |[x]| x.is_in(&s))
        .and(&some([&s], |[x]| x.is_in(&s)))
        .and(&no([&s], |[x]| x.is_in(&s).not()))
        .and(&one([&s], |[x]| x.is_in(&s)))
        .and(&lone([&s], |[x]| x.is_in(&s)))
        .and(&eventually(s.some()));
    // Exercise >6 bound variables (triggers `format!("x{i}")` name fallback).
    let seven = all([&s, &s, &s, &s, &s, &s, &s], |[a, b, c, d, e, f, g]| {
        a.union(&b)
            .union(&c)
            .union(&d)
            .union(&e)
            .union(&f)
            .union(&g)
            .is_in(&s)
    });
    let out = m.run(&f.and(&seven)).scope(1).steps(2).solve().unwrap();
    assert_eq!(out.verdict, Verdict::Found);
    assert_eq!(format!("{out}"), "found");
}

/// A `one` set is exact through its bounds alone; `diff` must still see
/// that `sig A` allows 0 or 2 atoms where `one sig A` allows exactly one.
#[test]
fn diff_sees_a_one_set_declared_by_bounds() {
    let plain = {
        let mut m = Model::new();
        m.set("A");
        m
    };
    let one = {
        let mut m = Model::new();
        m.one("A");
        m
    };
    let tightened = diff_models(&plain, &one, 3, &Options::default());
    assert_eq!(tightened.verdict, Some(DiffVerdict::Tightened));
    let loosened = diff_models(&one, &plain, 3, &Options::default());
    assert_eq!(loosened.verdict, Some(DiffVerdict::Loosened));
    let same = diff_models(&one, &one, 3, &Options::default());
    assert_eq!(same.verdict, Some(DiffVerdict::Equivalent));
}

/// DESIGN.md section 7.6: when the two models together allow no case,
/// `diff --of` says `vacuous`, not that the functions agree.
#[test]
fn diff_of_functions_over_no_case_is_vacuous() {
    let make = |some_a: bool| {
        let mut m = Model::new();
        let a = m.set("A");
        m.set("B");
        m.fact(if some_a { a.some() } else { a.no() });
        m
    };
    let (old, new) = (make(true), make(false));
    let a_old = Expr::relation(old.relations().first().unwrap());
    let rep = elinvar_engine::diff_functions(&old, &a_old, &new, &a_old, 3, 4, &Options::default());
    assert_eq!(rep.verdict, Some(DiffVerdict::Vacuous));
    assert_eq!(format!("{}", DiffVerdict::Vacuous), "vacuous");
    assert!(format!("{rep}").contains("allow no case"));
}