diff --git a/crates/aplite/README.md b/crates/aplite/README.md index f57e41496bb..9e08d3aa567 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -24,7 +24,15 @@ original query and requested context. UNSAT trusts the Rust implementation; there is no independently checked UNSAT certificate. The expression constructors are a low-level IR, not a SystemVerilog parser or a complete typed input validator. The scalar backend uses words up to 64 bits; callers may encode wider values in -chunks. The solver does not sample models randomly or promise uniform sampling. +chunks. `solve_seeded` selects initial SAT phases using a caller-owned seed for scalar +Boolean/bit-vector queries. The same input and seed reproduce the search within +a solver version, provided budgets permit completion. It returns only replayed +models and preserves `Unknown` on unsupported input or exhausted budgets. Arrays +remain available through `solve`/`solve_with_hint`, not `solve_seeded`. + +Seeded search is not uniform model sampling: it must not be used to claim the +legal-combination distribution required by SystemVerilog randomization. Weighted +sampling, `solve before`, and cyclic randomization require a separate policy. The crate has no dependency on Celox, lydite, Z3, or an external executable. Lydite retains its proof-obligation generation, proof orchestration, structural @@ -41,3 +49,11 @@ cache and lint configuration. Its explicit package version, changelog and Run `cargo test --locked -p aplite` and the lydite consumer tests after changes. The Lydite CI lane also tests Aplite directly. See [RELEASING.md](RELEASING.md) for its independent release process. + +```rust +use aplite::{Env, Limits, Sort, Verdict, boolv, solve_seeded, var}; +let context = Env::from([("data".into(), var("data".into(), Sort::Bv(32)))]); +let result = solve_seeded(&boolv(true), &context, Limits::default(), 42); +assert_eq!(result.verdict, Verdict::Sat); +assert!(result.original_formula_validated); +``` diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index 64cbdb72dfd..dd9dab46e8e 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -1759,7 +1759,28 @@ fn solve_scalar(formula: &Term, context: &Env, limits: Limits, search_hint: Sear solve_plain(formula, context, limits, search_hint) } } +/// Find a scalar satisfying assignment using seed-selected initial SAT phases. +/// +/// The seed changes search preferences, never the formula. This is a reproducible +/// search heuristic, not uniform model sampling. Reproducibility requires the +/// same solver version, input and sufficient budgets; wall-clock timeouts can +/// interrupt different prefixes. Arrays are unsupported by this entry point and +/// return `Unknown`. Existing proof-oriented entry points are unchanged. +pub fn solve_seeded(formula: &Term, context: &Env, limits: Limits, seed: u64) -> Outcome { + solve_plain_with_seed(formula, context, limits, SearchHint::Sat, Some(seed)) +} + fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: SearchHint) -> Outcome { + solve_plain_with_seed(formula, context, limits, search_hint, None) +} + +fn solve_plain_with_seed( + formula: &Term, + context: &Env, + limits: Limits, + search_hint: SearchHint, + seed: Option, +) -> Outcome { let mut outcome = Outcome { search_hint, search_strategy: SearchStrategy::NotStarted, @@ -1781,6 +1802,11 @@ fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: Searc 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()); } @@ -1838,7 +1864,13 @@ fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: Searc outcome.stats.work = budget.work; return outcome; } - let choices = match split_choices(formula, &blast, &mut budget) { + // A seeded query uses one CDCL search so decomposition cannot reset its + // preferences or bias the result toward the first syntactic alternative. + let choices = match if seed.is_some() { + Ok(Vec::new()) + } else { + split_choices(formula, &blast, &mut budget) + } { Ok(choices) => choices, Err(reason) => { outcome.reason = Some(reason); @@ -1859,6 +1891,19 @@ fn solve_plain(formula: &Term, context: &Env, limits: Limits, search_hint: Searc 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; + } + } let mut probe_verdict = None; if !choices.is_empty() && search_hint == SearchHint::Sat { // Probe the original query for a quick witness, scaled to its CNF diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 96c058485f9..79a6868d102 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -9,4 +9,9 @@ pub mod term; pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; -pub use finite::{Limits, Outcome, Scalar, SearchHint, Verdict, solve, solve_with_hint}; +pub use finite::{ + Limits, Outcome, Scalar, SearchHint, Verdict, solve, solve_seeded, solve_with_hint, +}; + +#[cfg(test)] +mod seeded_tests; diff --git a/crates/aplite/src/seeded_tests.rs b/crates/aplite/src/seeded_tests.rs new file mode 100644 index 00000000000..487c3b8a546 --- /dev/null +++ b/crates/aplite/src/seeded_tests.rs @@ -0,0 +1,159 @@ +use crate::{ + Env, Limits, Scalar, Sort, Verdict, and, boolv, bv, eq, node, not, solve, solve_seeded, var, +}; +use std::collections::BTreeSet; + +#[test] +fn seeds_reproduce_and_vary_unconstrained_inputs() { + let x = var("x".into(), Sort::Bv(64)); + let flag = var("flag".into(), Sort::Bool); + let context = Env::from([("x".into(), x), ("flag".into(), flag)]); + let mut words = BTreeSet::new(); + let mut flags = BTreeSet::new(); + for seed in 0..64 { + let a = solve_seeded(&boolv(true), &context, Limits::default(), seed); + let b = solve_seeded(&boolv(true), &context, Limits::default(), seed); + assert_eq!(a.verdict, Verdict::Sat); + assert!(a.original_formula_validated); + assert_eq!(a.assignments, b.assignments); + assert_eq!(a.context_values, b.context_values); + let Scalar::Bv { value, .. } = a.assignments["x"] else { + panic!() + }; + let Scalar::Bool(flag) = a.assignments["flag"] else { + panic!() + }; + words.insert(value); + flags.insert(flag); + } + assert_eq!(words.len(), 64); + assert_eq!(flags.len(), 2); +} + +#[test] +fn constrained_models_preserve_relations_and_context_expressions() { + let x = var("x".into(), Sort::Bv(4)); + let y = var("y".into(), Sort::Bv(4)); + let sum = node(Sort::Bv(4), "bvadd", vec![x.clone(), y.clone()]); + let formula = and( + eq(sum.clone(), bv(4, 9)), + node(Sort::Bool, "bvult", vec![x.clone(), bv(4, 4)]), + ); + let context = Env::from([("sum".into(), sum)]); + let mut seen = BTreeSet::new(); + for seed in 0..128 { + let result = solve_seeded(&formula, &context, Limits::default(), seed); + assert_eq!(result.verdict, Verdict::Sat); + assert!(result.original_formula_validated); + let Scalar::Bv { value: x, .. } = result.assignments["x"] else { + panic!() + }; + let Scalar::Bv { value: y, .. } = result.assignments["y"] else { + panic!() + }; + assert!(x < 4); + assert_eq!((x + y) & 15, 9); + assert_eq!( + result.context_values["sum"], + Scalar::Bv { width: 4, value: 9 } + ); + seen.insert(x); + } + assert_eq!(seen.len(), 4); +} + +#[test] +fn seeds_cannot_change_unsatisfiability_or_unique_models() { + let x = var("x".into(), Sort::Bv(8)); + let fixed = eq(x.clone(), bv(8, 37)); + let impossible = and(fixed.clone(), not(fixed.clone())); + for seed in [0, 1, 42, u64::MAX] { + assert_eq!( + solve_seeded(&impossible, &Env::new(), Limits::default(), seed).verdict, + Verdict::Unsat + ); + let result = solve_seeded(&fixed, &Env::new(), Limits::default(), seed); + assert_eq!(result.verdict, Verdict::Sat); + assert_eq!( + result.assignments["x"], + Scalar::Bv { + width: 8, + value: 37 + } + ); + } + assert_eq!( + solve(&impossible, &Env::new(), Limits::default()).verdict, + Verdict::Unsat + ); +} + +#[test] +fn unsupported_input_and_exhausted_budgets_are_unknown_without_models() { + let x = var("x".into(), Sort::Bv(8)); + let context = Env::from([("x".into(), x)]); + for limits in [ + Limits { + max_work: 0, + ..Limits::default() + }, + Limits { + max_variables: 1, + ..Limits::default() + }, + Limits { + max_clauses: 0, + ..Limits::default() + }, + ] { + let result = solve_seeded(&boolv(true), &context, limits, 0); + assert_eq!(result.verdict, Verdict::Unknown); + assert!(!result.original_formula_validated); + assert!(result.assignments.is_empty()); + } + let memory = Env::from([("m".into(), var("m".into(), Sort::Mem(4, 8)))]); + let result = solve_seeded(&boolv(true), &memory, Limits::default(), 0); + assert_eq!(result.verdict, Verdict::Unknown); + assert!(result.reason.unwrap().contains("scalar")); + let invalid = node(Sort::Bool, "unsupported", vec![]); + assert_eq!( + solve_seeded(&invalid, &Env::new(), Limits::default(), 0).verdict, + Verdict::Unknown + ); +} + +#[test] +fn seeded_search_matches_every_two_boolean_truth_table() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let context = Env::from([("x".into(), x.clone()), ("y".into(), y.clone())]); + for mask in 0..16u8 { + let mut formula = boolv(false); + for row in 0..4u8 { + if mask & (1 << row) != 0 { + let case = and( + eq(x.clone(), boolv(row & 1 != 0)), + eq(y.clone(), boolv(row & 2 != 0)), + ); + formula = node(Sort::Bool, "or", vec![formula, case]); + } + } + for seed in 0..16 { + let result = solve_seeded(&formula, &context, Limits::default(), seed); + if mask == 0 { + assert_eq!(result.verdict, Verdict::Unsat); + } else { + assert_eq!(result.verdict, Verdict::Sat); + assert!(result.original_formula_validated); + let Scalar::Bool(x) = result.assignments["x"] else { + panic!() + }; + let Scalar::Bool(y) = result.assignments["y"] else { + panic!() + }; + let row = u8::from(x) | (u8::from(y) << 1); + assert_ne!(mask & (1 << row), 0); + } + } + } +}