Skip to main content

elinvar_engine/
tests_gen.rs

1//! Model-based test generation (N11): step reachability and per-guard refusal
2//! tests derived from a model's [`StepSpec`]s.
3
4use std::collections::BTreeMap;
5
6use serde::Serialize;
7
8use crate::model::{Model, StepSpec};
9use crate::render::{render_allowed_sql_with_values, render_refused_sql_with_values};
10use crate::report::{Report, TraceReport};
11use crate::sat::Budget;
12use crate::solve::Verdict;
13use elinvar_logic::{
14    Error, Formula, FormulaKind, TemporalOp, Trace, Variable, evaluate_trace_at,
15    evaluate_trace_expr_at,
16};
17
18/// Outcome kind of one generated test case (N11, B22).
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "snake_case")]
21#[non_exhaustive]
22pub enum TestKind {
23    /// Shortest trace in which the step fires.
24    Allowed,
25    /// Shortest trace reaching a state/attempt where only the named guard refuses the step.
26    Refused,
27    /// Proved impossible within the scope even from any valid state (not just bounded non-reach).
28    DeadStep,
29    /// Proved unable to decide on its own within the scope even from any valid state.
30    UnreachableGuard,
31    /// Not reached from the initial state within `--steps`, though reachable from a valid state (B22).
32    NotReached,
33    /// The solver budget ran out before deciding.
34    Unknown,
35}
36
37/// One generated test case from [`Model::generate_tests`] (N11).
38#[derive(Clone, Debug, Serialize)]
39#[non_exhaustive]
40pub struct TestCase {
41    /// Allowed flow, refused guard test, dead step, unreachable guard, or unknown.
42    pub kind: TestKind,
43    /// The step predicate tested.
44    pub step: String,
45    /// For `Refused` and `UnreachableGuard`, the guard condition or trigger name.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub rule: Option<String>,
48    /// Concrete witness argument atoms bound to the step under test (B40).
49    #[serde(default, skip_serializing_if = "Vec::is_empty")]
50    pub args: Vec<String>,
51    /// The witness trace, for `Allowed` and `Refused`.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub trace: Option<TraceReport>,
54    /// Executable SQL replay script (when requested with `with_sql = true`).
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub sql: Option<String>,
57    /// Additional note (for `DeadStep`, `UnreachableGuard`, or `Unknown`).
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub note: Option<String>,
60}
61
62impl Model {
63    /// Generates step reachability tests and per-guard refusal tests from the
64    /// model's registered [`StepSpec`]s (N11).
65    ///
66    /// - For each step: finds the shortest trace in which it fires, or flags it
67    ///   as [`TestKind::DeadStep`].
68    /// - For each guard condition of each step: finds the shortest trace to a
69    ///   state/attempt where that guard alone refuses the step, or flags it as
70    ///   [`TestKind::UnreachableGuard`].
71    pub fn generate_tests(
72        &self,
73        scope: usize,
74        steps: usize,
75        budget: Budget,
76        with_sql: bool,
77    ) -> Result<Vec<TestCase>, Vec<Error>> {
78        self.generate_tests_with(scope, steps, budget, with_sql, &BTreeMap::new(), |_| {})
79    }
80
81    /// Streaming, sample-aware variant of [`Self::generate_tests`] (B16, N21):
82    /// invokes `on_case` immediately as each test finishes, uses `sample_values`
83    /// (`"table.col"` -> valid sample strings) when rendering SQL, and executes
84    /// the refused step in a relaxed-guard trace so every SQL refusal script
85    /// includes the concrete statement under test.
86    pub fn generate_tests_with(
87        &self,
88        scope: usize,
89        steps: usize,
90        budget: Budget,
91        with_sql: bool,
92        sample_values: &BTreeMap<String, Vec<String>>,
93        on_case: impl FnMut(&TestCase),
94    ) -> Result<Vec<TestCase>, Vec<Error>> {
95        self.generate_tests_for_tables(
96            scope,
97            steps,
98            budget,
99            with_sql,
100            sample_values,
101            &[],
102            &BTreeMap::new(),
103            on_case,
104        )
105    }
106
107    /// Table-filtered, trigger-aware variant of [`Self::generate_tests_with`]
108    /// (B24, B25, B40):
109    /// - When `only_tables` is non-empty, only generates cases for steps
110    ///   (`insert_<t>`, `update_<t>`, `delete_<t>`) belonging to those tables,
111    ///   while keeping all other imported tables and rules active in the model.
112    /// - Uses `trigger_targets` (`source_table -> [target_table]`) when
113    ///   rendering SQL so rows written automatically by `AFTER` triggers are
114    ///   not emitted as duplicate `INSERT` statements.
115    #[allow(clippy::too_many_arguments)]
116    pub fn generate_tests_for_tables(
117        &self,
118        scope: usize,
119        steps: usize,
120        budget: Budget,
121        with_sql: bool,
122        sample_values: &BTreeMap<String, Vec<String>>,
123        only_tables: &[String],
124        trigger_targets: &BTreeMap<String, Vec<String>>,
125        mut on_case: impl FnMut(&TestCase),
126    ) -> Result<Vec<TestCase>, Vec<Error>> {
127        let specs = self.step_specs();
128        let mut cases = Vec::new();
129        let mut emit = |case: TestCase| {
130            on_case(&case);
131            cases.push(case);
132        };
133        // B69: share one wall-clock deadline across every solver call in `tests`
134        // so `--timeout` bounds the entire command instead of resetting per case.
135        let deadline = budget.time.map(|d| std::time::Instant::now() + d);
136        let rem_budget = || -> Option<Budget> {
137            match deadline {
138                Some(d) => {
139                    let rem = d.checked_duration_since(std::time::Instant::now())?;
140                    if rem.is_zero() {
141                        return None;
142                    }
143                    Some(Budget {
144                        conflicts: budget.conflicts,
145                        time: Some(rem),
146                    })
147                }
148                None => Some(budget),
149            }
150        };
151
152        'specs: for (si, spec) in specs.iter().enumerate() {
153            if !only_tables.is_empty() {
154                let s_low = spec.name.to_ascii_lowercase();
155                let target_table = s_low
156                    .strip_prefix("insert_")
157                    .or_else(|| s_low.strip_prefix("update_"))
158                    .or_else(|| s_low.strip_prefix("delete_"));
159                let keep = target_table.is_some_and(|t| {
160                    let t_clean = t.strip_suffix("_sql").unwrap_or(t);
161                    only_tables
162                        .iter()
163                        .any(|req| req.eq_ignore_ascii_case(t) || req.eq_ignore_ascii_case(t_clean))
164                });
165                if !keep {
166                    continue;
167                }
168            }
169            // 1. Shortest trace where this step happens.
170            let Some(cur_budget) = rem_budget() else {
171                emit(TestCase {
172                    kind: TestKind::Unknown,
173                    step: spec.name.clone(),
174                    rule: None,
175                    args: Vec::new(),
176                    trace: None,
177                    sql: None,
178                    note: Some("time limit reached".to_string()),
179                });
180                break 'specs;
181            };
182            let allow_body = {
183                let mut parts: Vec<Formula> =
184                    spec.guards.iter().map(|g| g.formula.clone()).collect();
185                parts.push(spec.effect.clone());
186                Formula::and_all(parts)
187            };
188            let reach_goal = spec.full_arm().eventually();
189            let rep = self
190                .run(&reach_goal)
191                .named(&format!("allow_{}", spec.name))
192                .scope(scope)
193                .steps(steps)
194                .budget(cur_budget)
195                .report();
196            if !rep.errors.is_empty() {
197                return Err(rep.errors);
198            }
199            match rep.verdict {
200                Some(Verdict::Found) => {
201                    let witness = find_step_witness(&rep, spec, &allow_body);
202                    let target_step = witness.as_ref().map(|(k, _)| *k);
203                    let args = witness.map(|(_, a)| a).unwrap_or_default();
204                    let sql = if with_sql {
205                        render_allowed_sql_with_values(
206                            &rep,
207                            &spec.name,
208                            target_step,
209                            sample_values,
210                            trigger_targets,
211                        )
212                        .ok()
213                    } else {
214                        None
215                    };
216                    emit(TestCase {
217                        kind: TestKind::Allowed,
218                        step: spec.name.clone(),
219                        rule: None,
220                        args,
221                        trace: rep.trace,
222                        sql,
223                        note: None,
224                    });
225                }
226                Some(Verdict::None) => {
227                    // B22: probe from any valid state (without initial-state
228                    // constraints such as StartEmpty) in 2 steps. Only report
229                    // `DeadStep` if it cannot fire even from any valid state;
230                    // otherwise report `NotReached` within `steps`.
231                    let Some(probe_budget) = rem_budget() else {
232                        emit(TestCase {
233                            kind: TestKind::Unknown,
234                            step: spec.name.clone(),
235                            rule: None,
236                            args: Vec::new(),
237                            trace: None,
238                            sql: None,
239                            note: Some("time limit reached".to_string()),
240                        });
241                        break;
242                    };
243                    let probe = self
244                        .without_initial_constraints()
245                        .run(&reach_goal)
246                        .named(&format!("probe_allow_{}", spec.name))
247                        .scope(scope)
248                        .steps(2)
249                        .budget(probe_budget)
250                        .report();
251                    match probe.verdict {
252                        Some(Verdict::None) => {
253                            emit(TestCase {
254                                kind: TestKind::DeadStep,
255                                step: spec.name.clone(),
256                                rule: None,
257                                args: Vec::new(),
258                                trace: None,
259                                sql: None,
260                                note: Some(format!(
261                                    "step `{}` cannot fire from any valid state within scope {scope}",
262                                    spec.name
263                                )),
264                            });
265                        }
266                        Some(Verdict::Found) => {
267                            emit(TestCase {
268                                kind: TestKind::NotReached,
269                                step: spec.name.clone(),
270                                rule: None,
271                                args: Vec::new(),
272                                trace: None,
273                                sql: None,
274                                note: Some(format!(
275                                    "step `{}` was not reached within {steps} steps (raise --steps)",
276                                    spec.name
277                                )),
278                            });
279                        }
280                        _ => {
281                            emit(TestCase {
282                                kind: TestKind::Unknown,
283                                step: spec.name.clone(),
284                                rule: None,
285                                args: Vec::new(),
286                                trace: None,
287                                sql: None,
288                                note: probe
289                                    .note
290                                    .or_else(|| Some("budget or time limit reached".to_string())),
291                            });
292                            if rem_budget().is_none() {
293                                break 'specs;
294                            }
295                        }
296                    }
297                }
298                _ => {
299                    emit(TestCase {
300                        kind: TestKind::Unknown,
301                        step: spec.name.clone(),
302                        rule: None,
303                        args: Vec::new(),
304                        trace: None,
305                        sql: None,
306                        note: rep.note,
307                    });
308                }
309            }
310
311            // 2. For each guard condition: shortest trace where that guard alone refuses the step.
312            for (gi, guard) in spec.guards.iter().enumerate() {
313                let Some(guard_budget) = rem_budget() else {
314                    emit(TestCase {
315                        kind: TestKind::Unknown,
316                        step: spec.name.clone(),
317                        rule: Some(guard.label.clone()),
318                        args: Vec::new(),
319                        trace: None,
320                        sql: None,
321                        note: Some("time limit reached".to_string()),
322                    });
323                    break 'specs;
324                };
325                // B16: when rendering SQL (or when the guard is temporal),
326                // relax ONLY this guard in the transition fact and run the
327                // step's effect so the witness trace actually executes the
328                // refused INSERT/UPDATE/DELETE statement!
329                let use_relaxed = with_sql || guard.formula.is_temporal();
330                let pre_state_body = {
331                    let mut parts: Vec<Formula> = spec
332                        .guards
333                        .iter()
334                        .enumerate()
335                        .filter(|&(j, g)| j != gi && !g.formula.is_temporal())
336                        .map(|(_, g)| g.formula.clone())
337                        .collect();
338                    parts.push(guard.formula.not());
339                    Formula::and_all(parts)
340                };
341                let relaxed_body = {
342                    let mut parts: Vec<Formula> = spec
343                        .guards
344                        .iter()
345                        .enumerate()
346                        .filter(|&(j, _)| j != gi)
347                        .map(|(_, g)| g.formula.clone())
348                        .collect();
349                    parts.push(guard.formula.not());
350                    parts.push(spec.effect.clone());
351                    Formula::and_all(parts)
352                };
353                let relaxed_model = if use_relaxed {
354                    Some(self.with_relaxed_guard(si, gi, specs))
355                } else {
356                    None
357                };
358                let mut pre_state_only = !use_relaxed;
359                let mut rep = if !use_relaxed {
360                    let goal = spec.quantify(pre_state_body.clone()).eventually();
361                    self.run(&goal)
362                        .named(&format!("refuse_{}_{gi}", spec.name))
363                        .scope(scope)
364                        .steps(steps)
365                        .budget(guard_budget)
366                        .report()
367                } else {
368                    let goal = spec.quantify(relaxed_body.clone()).eventually();
369                    relaxed_model
370                        .as_ref()
371                        .expect("relaxed model built when use_relaxed")
372                        .run(&goal)
373                        .named(&format!("refuse_{}_{gi}", spec.name))
374                        .scope(scope)
375                        .steps(steps)
376                        .budget(guard_budget)
377                        .report()
378                };
379                // B16: if a non-temporal guard (such as a RESTRICT foreign-key
380                // check on `delete_T`) could not execute `spec.effect` because
381                // doing so would violate a table invariant in the next state,
382                // fall back to reaching the pre-state where the guard refuses
383                // and synthesize the refused SQL statement from that state.
384                if use_relaxed
385                    && !guard.formula.is_temporal()
386                    && rep.verdict == Some(Verdict::None)
387                    && let Some(fb_budget) = rem_budget()
388                {
389                    let goal = spec.quantify(pre_state_body.clone()).eventually();
390                    let fallback = self
391                        .run(&goal)
392                        .named(&format!("refuse_{}_{gi}", spec.name))
393                        .scope(scope)
394                        .steps(steps)
395                        .budget(fb_budget)
396                        .report();
397                    if fallback.verdict == Some(Verdict::Found) {
398                        pre_state_only = true;
399                        rep = fallback;
400                    }
401                }
402                if !rep.errors.is_empty() {
403                    return Err(rep.errors);
404                }
405                match rep.verdict {
406                    Some(Verdict::Found) => {
407                        let active_body = if pre_state_only {
408                            &pre_state_body
409                        } else {
410                            &relaxed_body
411                        };
412                        let witness = find_step_witness(&rep, spec, active_body);
413                        let target_step = witness.as_ref().map(|(k, _)| *k);
414                        let args = witness.as_ref().map(|(_, a)| a.clone()).unwrap_or_default();
415                        let witness_row = args.first().map(String::as_str);
416                        let sql = if with_sql {
417                            render_refused_sql_with_values(
418                                &rep,
419                                &spec.name,
420                                &guard.label,
421                                target_step,
422                                pre_state_only,
423                                witness_row,
424                                sample_values,
425                                trigger_targets,
426                            )
427                            .ok()
428                        } else {
429                            None
430                        };
431                        emit(TestCase {
432                            kind: TestKind::Refused,
433                            step: spec.name.clone(),
434                            rule: Some(guard.label.clone()),
435                            args,
436                            trace: rep.trace,
437                            sql,
438                            note: None,
439                        });
440                    }
441                    Some(Verdict::None) => {
442                        // B22/Law 14: probe from any valid state in 2 steps before
443                        // claiming `UnreachableGuard`; never misclassify `Unknown`
444                        // or timeout as `UnreachableGuard` or `NotReached`.
445                        let Some(pb1) = rem_budget() else {
446                            emit(TestCase {
447                                kind: TestKind::Unknown,
448                                step: spec.name.clone(),
449                                rule: Some(guard.label.clone()),
450                                args: Vec::new(),
451                                trace: None,
452                                sql: None,
453                                note: Some("time limit reached".to_string()),
454                            });
455                            break 'specs;
456                        };
457                        let probe_verdict: Option<Verdict> = if let Some(rel) = &relaxed_model {
458                            let goal = spec.quantify(relaxed_body.clone()).eventually();
459                            let p1 = rel
460                                .without_initial_constraints()
461                                .run(&goal)
462                                .named(&format!("probe_refuse_{}_{gi}", spec.name))
463                                .scope(scope)
464                                .steps(2)
465                                .budget(pb1)
466                                .report();
467                            if p1.verdict == Some(Verdict::None) && !guard.formula.is_temporal() {
468                                if let Some(pb2) = rem_budget() {
469                                    let p2_goal =
470                                        spec.quantify(pre_state_body.clone()).eventually();
471                                    let p2 = self
472                                        .without_initial_constraints()
473                                        .run(&p2_goal)
474                                        .named(&format!("probe_pre_{}_{gi}", spec.name))
475                                        .scope(scope)
476                                        .steps(2)
477                                        .budget(pb2)
478                                        .report();
479                                    p2.verdict
480                                } else {
481                                    Some(Verdict::Unknown)
482                                }
483                            } else {
484                                p1.verdict
485                            }
486                        } else {
487                            let goal = spec.quantify(pre_state_body.clone()).eventually();
488                            let p = self
489                                .without_initial_constraints()
490                                .run(&goal)
491                                .named(&format!("probe_refuse_{}_{gi}", spec.name))
492                                .scope(scope)
493                                .steps(2)
494                                .budget(pb1)
495                                .report();
496                            p.verdict
497                        };
498                        match probe_verdict {
499                            Some(Verdict::None) => {
500                                emit(TestCase {
501                                    kind: TestKind::UnreachableGuard,
502                                    step: spec.name.clone(),
503                                    rule: Some(guard.label.clone()),
504                                    args: Vec::new(),
505                                    trace: None,
506                                    sql: None,
507                                    note: Some(format!(
508                                        "guard `{}` of `{}` cannot decide from any valid state within scope {scope}",
509                                        guard.label, spec.name
510                                    )),
511                                });
512                            }
513                            Some(Verdict::Found) => {
514                                emit(TestCase {
515                                    kind: TestKind::NotReached,
516                                    step: spec.name.clone(),
517                                    rule: Some(guard.label.clone()),
518                                    args: Vec::new(),
519                                    trace: None,
520                                    sql: None,
521                                    note: Some(format!(
522                                        "guard `{}` of `{}` was not reached within {steps} steps (raise --steps)",
523                                        guard.label, spec.name
524                                    )),
525                                });
526                            }
527                            _ => {
528                                emit(TestCase {
529                                    kind: TestKind::Unknown,
530                                    step: spec.name.clone(),
531                                    rule: Some(guard.label.clone()),
532                                    args: Vec::new(),
533                                    trace: None,
534                                    sql: None,
535                                    note: Some("budget or time limit reached".to_string()),
536                                });
537                                if rem_budget().is_none() {
538                                    break 'specs;
539                                }
540                            }
541                        }
542                    }
543                    _ => {
544                        emit(TestCase {
545                            kind: TestKind::Unknown,
546                            step: spec.name.clone(),
547                            rule: Some(guard.label.clone()),
548                            args: Vec::new(),
549                            trace: None,
550                            sql: None,
551                            note: rep.note,
552                        });
553                    }
554                }
555            }
556        }
557        Ok(cases)
558    }
559
560    /// Clones this model with guard `(step_idx, guard_idx)` relaxed in its
561    /// transition fact so a guard violation can be witnessed as a step,
562    /// preserving any initial-state conjuncts in the same fact.
563    fn with_relaxed_guard(&self, step_idx: usize, guard_idx: usize, specs: &[StepSpec]) -> Model {
564        fn extract_init(f: &Formula, out: &mut Vec<Formula>) {
565            match f.kind() {
566                FormulaKind::And(fs) => {
567                    for g in fs {
568                        extract_init(g, out);
569                    }
570                }
571                FormulaKind::Temporal(TemporalOp::Always, _) => {}
572                _ => out.push(f.clone()),
573            }
574        }
575        let mut cloned = self.clone();
576        let target_fact = &specs[step_idx].fact_name;
577        let mut init_parts = Vec::new();
578        for (name, f) in self.all_facts_named() {
579            if name == *target_fact {
580                extract_init(&f, &mut init_parts);
581            }
582        }
583        let mut arms = cloned.transition_extras_for(target_fact).to_vec();
584        for (i, sp) in specs.iter().enumerate() {
585            if &sp.fact_name != target_fact {
586                continue;
587            }
588            let mut active = vec![true; sp.guards.len()];
589            if i == step_idx && guard_idx < active.len() {
590                active[guard_idx] = false;
591            }
592            arms.push(sp.with_active_guards(&active));
593        }
594        if !arms.is_empty() {
595            let trans = Formula::or_all(arms).always();
596            let replacement = if init_parts.is_empty() {
597                trans
598            } else {
599                init_parts.push(trans);
600                Formula::and_all(init_parts)
601            };
602            cloned.replace_fact(target_fact, replacement);
603        }
604        cloned
605    }
606}
607
608/// Finds the earliest state/step `k` and concrete atom bindings for `spec.vars`
609/// where `body` evaluates to `true` on `rep.trace` (B20, B21).
610fn find_step_witness(
611    rep: &Report,
612    spec: &StepSpec,
613    body: &Formula,
614) -> Option<(usize, Vec<String>)> {
615    let tr = rep.trace.as_ref()?;
616    let trace = Trace::new(tr.fixed.clone(), tr.states.clone(), tr.loop_to).ok()?;
617    let u = trace.fixed().universe();
618    for k in 0..trace.states().len() {
619        if spec.vars.is_empty() {
620            if evaluate_trace_at(&trace, body, k, &[]) == Ok(true) {
621                return Some((k, Vec::new()));
622            }
623            continue;
624        }
625        let mut domains: Vec<Vec<usize>> = Vec::with_capacity(spec.vars.len());
626        let mut empty = false;
627        for r in &spec.ranges {
628            let atoms: Vec<usize> = match evaluate_trace_expr_at(&trace, r, k) {
629                Ok(ts) => ts.indices().map(|i| i as usize).collect(),
630                Err(_) => Vec::new(),
631            };
632            if atoms.is_empty() {
633                empty = true;
634                break;
635            }
636            domains.push(atoms);
637        }
638        if empty {
639            continue;
640        }
641        let total: usize = domains
642            .iter()
643            .try_fold(1usize, |acc, d| acc.checked_mul(d.len()))
644            .unwrap_or(0);
645        if total == 0 || total > 1024 {
646            continue;
647        }
648        for code in 0..total {
649            let mut atoms = vec![0usize; domains.len()];
650            let mut c = code;
651            for (slot, dom) in atoms.iter_mut().zip(&domains).rev() {
652                *slot = dom[c % dom.len()];
653                c /= dom.len();
654            }
655            let bindings: Vec<(Variable, usize)> = spec
656                .vars
657                .iter()
658                .cloned()
659                .zip(atoms.iter().copied())
660                .collect();
661            if evaluate_trace_at(&trace, body, k, &bindings) == Ok(true) {
662                let names: Vec<String> = atoms
663                    .iter()
664                    .filter_map(|&idx| u.atom(idx).map(str::to_string))
665                    .collect();
666                return Some((k, names));
667            }
668        }
669    }
670    None
671}