From e8aec711eeb131c130b068520c3d0f3e1c9ee9cf Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:00:27 +0900 Subject: [PATCH] feat(aplite): reuse compiled queries with temporary assumptions Repeated constraint queries currently validate and bit-blast the same expressions on every solve. Add PreparedQuery to compile a fixed scalar formula, context and Boolean predicate definitions once, then assert chosen predicate polarities per call. Encode assumptions as decision levels rather than permanent unit clauses, reapply them after backjumps, and retain learned clauses after successful searches. Discard mutable search state after UNSAT or interruption while keeping the original encoding reusable. Share source compilation, phase initialization and model replay with the existing solver. Replay every SAT witness against the original formula, requested context and asserted predicates. Preparation and solve budgets are explicit and separate; invalid predicate indexes or resource exhaustion return Unknown, never UNSAT. The API is a reusable solving primitive, not a uniform sampler or an implementation of SystemVerilog randomize. Validation: 84 existing Aplite tests plus six prepared-query regressions and three README doctests. Exhaustively checked 4,096 changing assumption queries against all three-Boolean truth tables; tested retained learned clauses, opposite/duplicate/constant assumptions, sort conflicts, invalid input, and recovery after interrupted searches. Lydite IR (38), solver (29), kernel (5), and pipeline/search consumers (7) passed, including finite-only proofs and deliberate fault detection. Affected all-target clippy, formatting, package include/version checks, diff checks and standalone cargo package verification passed. No full RV32I campaign or release build was run. Change-Id: I80ec43950e64c7fc7a7dfc0c0975848fe51adea2 --- crates/aplite/README.md | 29 ++ crates/aplite/src/finite.rs | 227 ++++++++----- crates/aplite/src/finite/prepared.rs | 489 +++++++++++++++++++++++++++ crates/aplite/src/lib.rs | 3 +- 4 files changed, 656 insertions(+), 92 deletions(-) create mode 100644 crates/aplite/src/finite/prepared.rs diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 9e08d3aa567..0a9b136e90e 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -57,3 +57,32 @@ let result = solve_seeded(&boolv(true), &context, Limits::default(), 42); assert_eq!(result.verdict, Verdict::Sat); assert!(result.original_formula_validated); ``` + +## Reusable constraints and temporary assumptions + +`PreparedQuery` validates and bit-blasts a fixed scalar formula, context and list +of Boolean predicates once. Each solve can assert either polarity of any of those +predicates. Their definitions are compiled, but unused predicates do not constrain +the answer. Successful searches reuse their SAT database and learned clauses. +UNSAT or interrupted searches discard mutable search state and retain the compiled +encoding, so failed assumptions cannot contaminate the next call. + +```rust +use aplite::{Assumption, Env, Limits, PreparedQuery, Sort, Verdict, boolv, bv, eq, var}; +let x = var("x".into(), Sort::Bv(32)); +let context = Env::from([("x".into(), x.clone())]); +let predicates = [eq(x, bv(32, 7))]; +let mut query = PreparedQuery::new(&boolv(true), &context, &predicates, Limits::default()).unwrap(); +for value in [true, false] { + let result = query.solve(&[Assumption { predicate: 0, value }], Limits::default(), 42); + assert_eq!(result.verdict, Verdict::Sat); + assert!(result.original_formula_validated); +} +``` + +Preparation and each solve have separate budgets; `preparation_work()` reports +the setup work and each outcome reports its solve work. Reproducibility includes +the query history because learning and search activity are retained. Unknown +includes invalid predicate indexes and exhausted budgets, and is not Unsat. +This API supplies reusable solving for future distribution policies; it does not +implement uniform sampling, variable ordering, or SystemVerilog `randomize()`. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index dd9dab46e8e..a3136f146ee 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -14,7 +14,9 @@ use std::{ mod control; mod lookup; +mod prepared; mod readonly; +pub use prepared::{Assumption, PreparedQuery}; pub use readonly::ArrayModel; type Lit = i32; @@ -1394,6 +1396,18 @@ impl Sat { conflicts: 0, } } + fn seed_phases(&mut self, mut state: u64, budget: &mut Budget) -> Res<()> { + // SplitMix64 is local and deterministic, including seed zero. + for phase in self.phase.iter_mut().skip(1) { + budget.tick(1)?; + state = state.wrapping_add(0x9e3779b97f4a7c15); + let mut value = state; + value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); + *phase = (value ^ (value >> 31)) >> 63 != 0; + } + Ok(()) + } fn enqueue(&mut self, p: Lit, reason: Option) -> bool { let v = p.unsigned_abs() as usize; if self.values[v] != 0 { @@ -1552,6 +1566,14 @@ impl Sat { Ok((learned, backtrack)) } fn run_slice(&mut self, b: &mut Budget, quantum: u64) -> Res { + self.run_slice_assuming(b, quantum, &[]) + } + fn run_slice_assuming( + &mut self, + b: &mut Budget, + quantum: u64, + assumptions: &[Lit], + ) -> Res { let stop_work = b.work.saturating_add(quantum.max(1)); if !self.initialized { for id in 0..self.clauses.len() { @@ -1598,6 +1620,22 @@ impl Sat { return Err("finite SAT asserting clause invariant violated".into()); } } else { + // Reapply assumptions after every backjump. Each has its own + // level, including already-implied ones, so the level indexes + // remain stable. An assumption falsified by propagation proves + // only this query UNSAT, not the permanent clause database. + if self.starts.len() < assumptions.len() { + b.tick(1)?; + let p = assumptions[self.starts.len()]; + if truth(&self.values, p) < 0 { + return Ok(Search::Complete(Verdict::Unsat)); + } + self.starts.push(self.trail.len()); + if truth(&self.values, p) == 0 { + self.enqueue(p, None); + } + continue; + } let v = loop { let Some(v) = self.order.pop(&self.activity, b)? else { #[cfg(test)] @@ -1774,6 +1812,100 @@ fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: Searc solve_plain_with_seed(formula, context, limits, search_hint, None) } +fn replay_model( + formula: &Term, + context: &Env, + blast: &Blast, + sat: &Sat, + budget: &mut Budget, +) -> Res<(BTreeMap, BTreeMap)> { + // Validate every original CNF clause as well as the source-level witness. + for clause in &sat.clauses { + budget.tick(clause.len() as u64)?; + if !clause.iter().any(|&p| truth(&sat.values, p) > 0) { + return Err("finite SAT assignment failed CNF validation".into()); + } + } + let mut assignments = BTreeMap::new(); + for (n, bits) in &blast.inputs { + let value = match bits.sort { + Sort::Bool => Scalar::Bool(truth(&sat.values, bits.bits[0]) > 0), + Sort::Bv(width) => Scalar::Bv { + width, + value: bits.bits.iter().enumerate().fold(0u64, |v, (i, &p)| { + v | ((truth(&sat.values, p) > 0) as u64) << i + }), + }, + _ => unreachable!(), + }; + assignments.insert(n.clone(), value); + } + let mut memo = HashMap::new(); + if evaluate(formula, &assignments, &mut memo, budget, 0)? != Scalar::Bool(true) { + return Err("finite SAT assignment failed original-formula validation".into()); + } + let mut values = BTreeMap::new(); + for (label, term) in context { + values.insert( + label.clone(), + evaluate(term, &assignments, &mut memo, budget, 0)?, + ); + } + budget.check_time()?; + Ok((assignments, values)) +} + +fn compile_scalar( + blast: &mut Blast, + formula: &Term, + context: &Env, + budget: &mut Budget, + scalar_only: bool, +) -> Res<()> { + budget.tick(1)?; + if scalar_only && (formula.contains_memory() || context.values().any(Term::contains_memory)) { + return Err("scalar search supports scalar formulas and contexts only".into()); + } + if budget.limits.max_variables < 1 || budget.limits.max_clauses < 1 { + return Err("finite solver initial CNF budget exhausted".into()); + } + if formula.0.sort != Sort::Bool { + return Err("finite formula must have Bool sort".into()); + } + // Rewriting can bypass source nodes. Validate every original formula + // and context signature first, including dead branches and Sat hints. + blast.lookup.source_nodes = lookup::validate_source(formula, context, budget)?; + blast.aliases.collect(formula, budget)?; + let root = blast.term(formula, budget, 0)?; + for term in context.values() { + blast.term(term, budget, 0)?; + } + // Exact normalization may erase the last occurrence of a variable. + // Materialize missing ORIGINAL inputs after normal blasting, preserving + // the existing search order while keeping original SAT replay complete. + let mut source = vec![formula]; + source.extend(context.values()); + let mut seen = HashSet::new(); + let mut variables = BTreeMap::new(); + while let Some(term) = source.pop() { + budget.tick(1)?; + if !seen.insert(term.clone()) { + continue; + } + if let Some(name) = term.0.op.strip_prefix('@') { + if !blast.inputs.contains_key(name) { + variables.insert(name.to_string(), term.clone()); + } + } + source.extend(&term.0.args); + } + for term in variables.values() { + blast.term(term, budget, 0)?; + } + blast.clause(vec![root.bits[0]], budget)?; + Ok(()) +} + fn solve_plain_with_seed( formula: &Term, context: &Env, @@ -1800,52 +1932,7 @@ fn solve_plain_with_seed( time_check_in: 0, }; let mut blast = Blast::new(); - let compile = (|| -> Res<()> { - budget.tick(1)?; - if seed.is_some() - && (formula.contains_memory() || context.values().any(Term::contains_memory)) - { - return Err("seeded search supports scalar formulas and contexts only".into()); - } - if budget.limits.max_variables < 1 || budget.limits.max_clauses < 1 { - return Err("finite solver initial CNF budget exhausted".into()); - } - if formula.0.sort != Sort::Bool { - return Err("finite formula must have Bool sort".into()); - } - // Rewriting can bypass source nodes. Validate every original formula - // and context signature first, including dead branches and Sat hints. - blast.lookup.source_nodes = lookup::validate_source(formula, context, &mut budget)?; - blast.aliases.collect(formula, &mut budget)?; - let root = blast.term(formula, &mut budget, 0)?; - for term in context.values() { - blast.term(term, &mut budget, 0)?; - } - // Exact normalization may erase the last occurrence of a variable. - // Materialize missing ORIGINAL inputs after normal blasting, preserving - // the existing search order while keeping original SAT replay complete. - let mut source = vec![formula]; - source.extend(context.values()); - let mut seen = HashSet::new(); - let mut variables = BTreeMap::new(); - while let Some(term) = source.pop() { - budget.tick(1)?; - if !seen.insert(term.clone()) { - continue; - } - if let Some(name) = term.0.op.strip_prefix('@') { - if !blast.inputs.contains_key(name) { - variables.insert(name.to_string(), term.clone()); - } - } - source.extend(&term.0.args); - } - for term in variables.values() { - blast.term(term, &mut budget, 0)?; - } - blast.clause(vec![root.bits[0]], &mut budget)?; - Ok(()) - })(); + let compile = compile_scalar(&mut blast, formula, context, &mut budget, seed.is_some()); outcome.stats.asserted_definitions = blast.aliases.definitions.len(); outcome.stats.guarded_equalities = blast.aliases.guarded.len(); outcome.stats.guarded_rewrites = blast.guarded_rewrites; @@ -1891,18 +1978,8 @@ fn solve_plain_with_seed( SearchStrategy::CounterexampleProbeFair }; let result = (|| -> Res { - if let Some(mut state) = seed { - // SplitMix64 gives a local, fully specified stream (including seed - // zero). No process RNG, global state or platform-dependent hashing. - for phase in sat.phase.iter_mut().skip(1) { - budget.tick(1)?; - state = state.wrapping_add(0x9e3779b97f4a7c15); - let mut value = state; - value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb); - value ^= value >> 31; - *phase = value >> 63 != 0; - } + if let Some(seed) = seed { + sat.seed_phases(seed, &mut budget)?; } let mut probe_verdict = None; if !choices.is_empty() && search_hint == SearchHint::Sat { @@ -2100,39 +2177,7 @@ fn solve_plain_with_seed( if verdict != Verdict::Sat { return Ok(verdict); } - // Validate every original CNF clause as well as the source-level witness. - for clause in &sat.clauses { - budget.tick(clause.len() as u64)?; - if !clause.iter().any(|&p| truth(&sat.values, p) > 0) { - return Err("finite SAT assignment failed CNF validation".into()); - } - } - let mut assignments = BTreeMap::new(); - for (n, bits) in &blast.inputs { - let value = match bits.sort { - Sort::Bool => Scalar::Bool(truth(&sat.values, bits.bits[0]) > 0), - Sort::Bv(width) => Scalar::Bv { - width, - value: bits.bits.iter().enumerate().fold(0u64, |v, (i, &p)| { - v | ((truth(&sat.values, p) > 0) as u64) << i - }), - }, - _ => unreachable!(), - }; - assignments.insert(n.clone(), value); - } - let mut memo = HashMap::new(); - if evaluate(formula, &assignments, &mut memo, &mut budget, 0)? != Scalar::Bool(true) { - return Err("finite SAT assignment failed original-formula validation".into()); - } - let mut values = BTreeMap::new(); - for (label, term) in context { - values.insert( - label.clone(), - evaluate(term, &assignments, &mut memo, &mut budget, 0)?, - ); - } - budget.check_time()?; + let (assignments, values) = replay_model(formula, context, &blast, &sat, &mut budget)?; outcome.assignments = assignments; outcome.context_values = values; outcome.original_formula_validated = true; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs new file mode 100644 index 00000000000..3016ce5691c --- /dev/null +++ b/crates/aplite/src/finite/prepared.rs @@ -0,0 +1,489 @@ +//! Reusable scalar encoding with temporary Boolean assumptions. +use super::*; + +/// Select the polarity of a predicate supplied when preparing the query. +#[derive(Clone, Copy, Debug)] +pub struct Assumption { + pub predicate: usize, + pub value: bool, +} + +/// A compiled scalar query. Predicate definitions are permanent, but asserting +/// their truth values is local to each call. A successful search retains its +/// learned clauses and heuristic state; UNSAT and interrupted searches discard +/// search state while preserving the compiled encoding. +/// +/// This provides reusable solving, not uniform sampling. Seed reproducibility +/// requires the same query history and solver version. Preparation and each +/// solve have separate explicit budgets; callers must account for an aggregate +/// operation budget themselves. +pub struct PreparedQuery { + formula: Term, + context: Env, + predicates: Vec, + literals: Vec, + blast: Blast, + sat: Option, + preparation_work: u64, +} + +impl PreparedQuery { + pub fn new(formula: &Term, context: &Env, predicates: &[Term], limits: Limits) -> Res { + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + budget.tick(1)?; + // Add predicates to the compile context so source validation sees dead + // branches, sort conflicts and variables erased by normalization too. + let mut compile_context = context.clone(); + for (index, term) in predicates.iter().enumerate() { + budget.tick(1)?; + if term.0.sort != Sort::Bool { + return Err("prepared predicates must have Bool sort".into()); + } + let mut key = format!("__aplite_predicate_{index}"); + while compile_context.contains_key(&key) { + budget.tick(1)?; + key.push('_'); + } + compile_context.insert(key, term.clone()); + } + let mut blast = Blast::new(); + compile_scalar(&mut blast, formula, &compile_context, &mut budget, true)?; + let mut literals = Vec::with_capacity(predicates.len()); + for term in predicates { + literals.push(blast.term(term, &mut budget, 0)?.bits[0]); + } + budget.check_time()?; + Ok(Self { + formula: formula.clone(), + context: context.clone(), + predicates: predicates.to_vec(), + literals, + blast, + sat: None, + preparation_work: budget.work, + }) + } + + /// Work charged for the one-time source validation and bit blasting. + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + /// Solve with temporary assumptions. Invalid indexes and exhausted budgets + /// yield Unknown. SAT models are replayed against the original formula, + /// context and each asserted predicate before becoming visible. + pub fn solve(&mut self, assumptions: &[Assumption], limits: Limits, seed: u64) -> Outcome { + let mut outcome = Outcome { + search_hint: SearchHint::Sat, + search_strategy: SearchStrategy::SingleSearch, + verdict: Verdict::Unknown, + reason: None, + assignments: BTreeMap::new(), + context_values: BTreeMap::new(), + array_assignments: BTreeMap::new(), + array_context_values: BTreeMap::new(), + original_formula_validated: false, + stats: Stats::default(), + }; + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + // Take ownership so any error drops possibly interrupted mutations. + let mut sat = self.sat.take(); + let result = (|| -> Res { + budget.tick(1)?; + if self.blast.vars > budget.limits.max_variables + || self.blast.memo.len() > budget.limits.max_terms + { + return Err("prepared query exceeds solve size limits".into()); + } + let mut literals = Vec::with_capacity(assumptions.len()); + for assumption in assumptions { + budget.tick(1)?; + let p = *self + .literals + .get(assumption.predicate) + .ok_or("invalid prepared predicate index")?; + literals.push(if assumption.value { p } else { -p }); + } + if self.blast.clauses.len() > budget.limits.max_clauses { + return Err("prepared query exceeds solve clause limit".into()); + } + if sat.is_none() { + let mut clauses = Vec::with_capacity(self.blast.clauses.len()); + for clause in &self.blast.clauses { + budget.tick(1 + clause.len() as u64)?; + clauses.push(clause.clone()); + } + sat = Some(Sat::new(self.blast.vars, clauses)); + } + let solver = sat.as_mut().unwrap(); + if solver.clauses.len() > budget.limits.max_clauses { + return Err("prepared query exceeds solve clause limit".into()); + } + solver.backtrack(0, &mut budget)?; + solver.seed_phases(seed, &mut budget)?; + let decisions = solver.decisions; + let conflicts = solver.conflicts; + let result = solver.run_slice_assuming(&mut budget, u64::MAX, &literals); + outcome.stats.decisions = solver.decisions - decisions; + outcome.stats.conflicts = solver.conflicts - conflicts; + outcome.stats.search_slices = 1; + let verdict = match result? { + Search::Complete(verdict) => verdict, + Search::Pending => return Err("prepared search did not complete".into()), + }; + if verdict != Verdict::Sat { + budget.check_time()?; + return Ok(verdict); + } + let (assignments, values) = replay_model( + &self.formula, + &self.context, + &self.blast, + solver, + &mut budget, + )?; + let mut memo = HashMap::new(); + for assumption in assumptions { + if evaluate( + &self.predicates[assumption.predicate], + &assignments, + &mut memo, + &mut budget, + 0, + )? != Scalar::Bool(assumption.value) + { + return Err("prepared model failed assumption replay".into()); + } + } + budget.check_time()?; + outcome.assignments = assignments; + outcome.context_values = values; + outcome.original_formula_validated = true; + Ok(Verdict::Sat) + })(); + outcome.stats.work = budget.work; + outcome.stats.base_cnf_reused = true; + outcome.stats.terms = self.blast.memo.len(); + outcome.stats.variables = self.blast.vars; + outcome.stats.base_clauses = self.blast.clauses.len(); + outcome.stats.clauses = sat + .as_ref() + .map_or(self.blast.clauses.len(), |sat| sat.clauses.len()); + outcome.stats.peak_live_clauses = outcome.stats.clauses; + match result { + Ok(verdict) => outcome.verdict = verdict, + Err(reason) => outcome.reason = Some(reason), + } + if outcome.verdict == Verdict::Sat { + self.sat = sat; + } + outcome + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{and, boolv, bv, eq, node, not, var}; + + fn assumption(predicate: usize, value: bool) -> Assumption { + Assumption { predicate, value } + } + + #[test] + fn assumptions_do_not_escape_calls_or_become_alias_definitions() { + let x = var("x".into(), Sort::Bv(8)); + let y = var("y".into(), Sort::Bv(8)); + let predicates = [eq(x.clone(), y.clone()), eq(x.clone(), bv(8, 37))]; + let context = Env::from([("x".into(), x), ("y".into(), y)]); + let mut prepared = + PreparedQuery::new(&boolv(true), &context, &predicates, Limits::default()).unwrap(); + assert!(prepared.preparation_work() > 0); + for value in [true, false, true, false] { + let outcome = prepared.solve( + &[assumption(0, value), assumption(1, true)], + Limits::default(), + 42, + ); + assert_eq!(outcome.verdict, Verdict::Sat); + assert!(outcome.original_formula_validated); + assert_eq!( + outcome.assignments["x"], + Scalar::Bv { + width: 8, + value: 37 + } + ); + assert_eq!(outcome.assignments["x"] == outcome.assignments["y"], value); + assert!(prepared.sat.is_some()); + } + let bad = prepared.solve( + &[assumption(0, true), assumption(0, false)], + Limits::default(), + 0, + ); + assert_eq!(bad.verdict, Verdict::Unsat); + assert!(bad.assignments.is_empty()); + assert_eq!( + prepared.solve(&[], Limits::default(), 0).verdict, + Verdict::Sat + ); + } + + #[test] + fn constant_aliased_and_duplicate_assumptions_are_sound() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = and(x.clone(), eq(x.clone(), y.clone())); + let predicates = [boolv(true), boolv(false), x, y]; + let mut query = + PreparedQuery::new(&formula, &Env::new(), &predicates, Limits::default()).unwrap(); + for (index, required) in [(0, true), (1, false), (2, true), (3, true)] { + let sat = query.solve( + &[assumption(index, required), assumption(index, required)], + Limits::default(), + 0, + ); + assert_eq!(sat.verdict, Verdict::Sat); + assert_eq!( + query + .solve(&[assumption(index, !required)], Limits::default(), 0) + .verdict, + Verdict::Unsat + ); + } + } + + #[test] + fn exhaustive_three_boolean_queries_match_truth_tables_across_reuse() { + let vars = [ + var("x".into(), Sort::Bool), + var("y".into(), Sort::Bool), + var("z".into(), Sort::Bool), + ]; + let context = Env::from([ + ("x".into(), vars[0].clone()), + ("y".into(), vars[1].clone()), + ("z".into(), vars[2].clone()), + ]); + for mask in 0..256u16 { + let mut formula = boolv(false); + for row in 0..8 { + if mask & (1 << row) != 0 { + let mut cube = boolv(true); + for (index, variable) in vars.iter().enumerate() { + cube = and( + cube, + if row & (1 << index) != 0 { + variable.clone() + } else { + not(variable.clone()) + }, + ); + } + formula = node(Sort::Bool, "or", vec![formula, cube]); + } + } + let predicates = [ + vars[0].clone(), + vars[1].clone(), + vars[2].clone(), + node(Sort::Bool, "xor", vec![vars[0].clone(), vars[1].clone()]), + ]; + let mut query = + PreparedQuery::new(&formula, &context, &predicates, Limits::default()).unwrap(); + for choice in 0..16 { + // Alternate partial assumptions and XOR predicates to leave + // search decisions/conflicts beyond the assumption prefix. + let conditions = [ + assumption(choice % 3, choice & 1 != 0), + assumption(3, choice & 2 != 0), + ]; + let legal: Vec<_> = (0..8) + .filter(|row| { + mask & (1 << row) != 0 + && ((*row >> (choice % 3)) & 1 != 0) == (choice & 1 != 0) + && (((*row & 1) != 0) ^ ((*row & 2) != 0)) == (choice & 2 != 0) + }) + .collect(); + let outcome = query.solve(&conditions, Limits::default(), choice as u64); + assert_eq!( + outcome.verdict, + if legal.is_empty() { + Verdict::Unsat + } else { + Verdict::Sat + }, + "mask={mask}, choice={choice}" + ); + if outcome.verdict == Verdict::Sat { + let mut row = 0; + for (index, name) in ["x", "y", "z"].iter().enumerate() { + if outcome.assignments[*name] == Scalar::Bool(true) { + row |= 1 << index; + } + } + assert!(legal.contains(&row)); + assert!(outcome.original_formula_validated); + } + } + } + } + + #[test] + fn interruptions_and_invalid_indexes_leave_the_encoding_reusable() { + let x = var("x".into(), Sort::Bv(8)); + let context = Env::from([("x".into(), x.clone())]); + let predicate = eq(x, bv(8, 127)); + let mut query = + PreparedQuery::new(&boolv(true), &context, &[predicate], Limits::default()).unwrap(); + for work in 0..100 { + let result = query.solve( + &[assumption(0, true)], + Limits { + max_work: work, + ..Limits::default() + }, + 0, + ); + if result.verdict == Verdict::Unknown { + assert!(query.sat.is_none()); + assert!(result.assignments.is_empty()); + } + let next = query.solve(&[assumption(0, false)], Limits::default(), 0); + assert_eq!(next.verdict, Verdict::Sat); + assert_ne!( + next.assignments["x"], + Scalar::Bv { + width: 8, + value: 127 + } + ); + } + for conditions in [ + vec![assumption(usize::MAX, true)], + vec![assumption(1, false)], + ] { + assert_eq!( + query.solve(&conditions, Limits::default(), 0).verdict, + Verdict::Unknown + ); + assert_eq!(query.solve(&[], Limits::default(), 0).verdict, Verdict::Sat); + } + for limits in [ + Limits { + max_variables: 0, + ..Limits::default() + }, + Limits { + max_clauses: 0, + ..Limits::default() + }, + Limits { + timeout_ms: 0, + ..Limits::default() + }, + ] { + assert_eq!(query.solve(&[], limits, 0).verdict, Verdict::Unknown); + assert_eq!(query.solve(&[], Limits::default(), 0).verdict, Verdict::Sat); + } + } + + #[test] + fn learned_clauses_survive_success_but_do_not_turn_assumptions_into_facts() { + // Resolution proves x, but there is no x unit in the source. Exercise + // a conflict and retained learning before changing the assumptions. + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = and( + node(Sort::Bool, "or", vec![x.clone(), y.clone()]), + node(Sort::Bool, "or", vec![x.clone(), not(y.clone())]), + ); + let mut exercised_learning = false; + for seed in 0..64 { + let mut query = PreparedQuery::new( + &formula, + &Env::new(), + &[x.clone(), y.clone()], + Limits::default(), + ) + .unwrap(); + let first = query.solve(&[], Limits::default(), seed); + assert_eq!(first.verdict, Verdict::Sat); + if first.stats.conflicts == 0 { + continue; + } + exercised_learning = true; + assert!(query.sat.as_ref().unwrap().clauses.len() > query.blast.clauses.len()); + for value in [false, true, false] { + let result = query.solve(&[assumption(1, value)], Limits::default(), seed); + assert_eq!(result.verdict, Verdict::Sat); + assert_eq!(result.assignments["x"], Scalar::Bool(true)); + assert_eq!(result.assignments["y"], Scalar::Bool(value)); + } + assert_eq!( + query + .solve(&[assumption(0, false)], Limits::default(), seed) + .verdict, + Verdict::Unsat + ); + assert_eq!( + query + .solve(&[assumption(0, true)], Limits::default(), seed) + .verdict, + Verdict::Sat + ); + break; + } + assert!(exercised_learning); + } + + #[test] + fn preparation_checks_predicates_even_when_unasserted() { + for predicate in [ + bv(8, 1), + node(Sort::Bool, "unknown", vec![]), + eq( + var("m".into(), Sort::Mem(4, 8)), + var("m".into(), Sort::Mem(4, 8)), + ), + ] { + assert!( + PreparedQuery::new(&boolv(true), &Env::new(), &[predicate], Limits::default()) + .is_err() + ); + } + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); + assert!( + PreparedQuery::new( + &boolv(true), + &context, + &[var("x".into(), Sort::Bool)], + Limits::default() + ) + .is_err() + ); + assert!( + PreparedQuery::new( + &boolv(true), + &Env::new(), + &[], + Limits { + max_work: 0, + ..Limits::default() + } + ) + .is_err() + ); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 5b48cd6b275..7a721daf55f 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -10,7 +10,8 @@ pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Limits, Outcome, Scalar, SearchHint, Verdict, solve, solve_seeded, solve_with_hint, + Assumption, Limits, Outcome, PreparedQuery, Scalar, SearchHint, Verdict, solve, solve_seeded, + solve_with_hint, }; #[cfg(test)]