From c2a33b9581709847768eb5ad13811d2959fe7e5b Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:13:23 +0900 Subject: [PATCH] feat(aplite): query bounded projected XOR cells Add PreparedQuery::enumerate_cell to enumerate at most a caller-bounded projected cell under temporary predicates. Use one scoped CDCL database, retaining local learning while blocking already-seen projected assignments. Hidden witness multiplicity does not duplicate a projected model. Blocking clauses and their learned consequences never escape into the prepared query or a later cell. Return Complete, TooLarge, or Unknown distinctly. One extra search distinguishes an exact-size cell from overflow; only Complete exposes models. Work and time budgets cover the entire cell operation, including model replay. Replay source formulas, contexts and predicate assumptions before accepting models or declaring overflow. Add HashCells to prepare seed-selected affine XOR rows once and query different prefixes/targets without recompilation. Preserve constant and dependent rows, validate projection variables, and bound construction as well as search. These are partitioning/counting primitives, not a uniform sampler: adaptive sizing and a justified cell-acceptance/model-selection policy remain follow-up work. The exhaustive reservoir sampler remains test-only; an empty predicate prefix can still inspect a small whole domain within the explicit cell bound. Validation: 98 Aplite unit tests and four README doctests. Checked every three-Boolean truth table across XOR cells; verified disjoint/complete partitions across seeds, projected multiplicity, alias/constant bits, exact thresholds, overflow, invalid inputs, budget recovery and no state leakage. A 32-bit domain narrowed by XOR predicates completes a 16-model cell; the unpartitioned query stops at overflow. Lydite IR/solver/kernel tests (38/29/5), affected all-target clippy, formatting, package/version checks and standalone package verification passed. No full RV32I campaign, release build, or production uniformity guarantee is claimed. Change-Id: I562d30b5a8a1d9c75859358602aa1b3cc9c76455 --- crates/aplite/README.md | 31 ++ crates/aplite/src/finite.rs | 2 +- crates/aplite/src/finite/prepared.rs | 5 + crates/aplite/src/finite/prepared/cell.rs | 442 +++++++++++++++++++ crates/aplite/src/finite/prepared/hashing.rs | 303 +++++++++++++ crates/aplite/src/lib.rs | 4 +- 6 files changed, 784 insertions(+), 3 deletions(-) create mode 100644 crates/aplite/src/finite/prepared/cell.rs create mode 100644 crates/aplite/src/finite/prepared/hashing.rs diff --git a/crates/aplite/README.md b/crates/aplite/README.md index 0a9b136e90e..077f0fec470 100644 --- a/crates/aplite/README.md +++ b/crates/aplite/README.md @@ -86,3 +86,34 @@ 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()`. + +## Bounded hash cells + +`HashCells` prepares seed-selected affine XOR predicates over chosen scalar +variables. A query chooses a prefix of those predicates and their target bits; +shorter prefixes leave larger cells. The original formula and all predicates are +compiled once. The cell query uses one temporary SAT database and retains local +learning while it blocks already-seen projected assignments. It does not recompile +the formula for each model or retain blockers between cells. + +```rust +use aplite::{CellStatus, Env, HashCells, Limits, Sort, boolv, var}; +let projection = Env::from([("value".into(), var("x".into(), Sort::Bv(3)))]); +let cells = HashCells::new(&boolv(true), &projection, 2, 42, Limits::default()).unwrap(); +let cell = cells.cell(&[true, false], 8, Limits::default()); +assert_eq!(cell.status, CellStatus::Complete); +assert!(cell.models.iter().all(|model| model.contains_key("x"))); +``` + +`Complete` certifies all models in that cell, including an empty cell. `TooLarge` +means the cell has more models than the caller's bound, and `Unknown` covers +invalid input or exhausted budgets. Neither exposes a truncated model list. +All searches and replay in one cell share one work/time budget. Hidden variables +are existential: multiple witnesses cannot duplicate a projected assignment. +Call `PreparedQuery::enumerate_cell` directly for custom partition predicates. + +These operations are building blocks, **not a uniform sampler**. Uniformly picking +a cell and then uniformly picking one of its models generally biases results +when cells have different sizes. A sampling policy must control cell sizing and +acceptance separately. The exhaustive reservoir sampler remains a test-only reference. +Rows may be dependent or constant; hash construction preserves those cases. diff --git a/crates/aplite/src/finite.rs b/crates/aplite/src/finite.rs index a3136f146ee..62443ec8663 100644 --- a/crates/aplite/src/finite.rs +++ b/crates/aplite/src/finite.rs @@ -16,7 +16,7 @@ mod control; mod lookup; mod prepared; mod readonly; -pub use prepared::{Assumption, PreparedQuery}; +pub use prepared::{Assumption, Cell, CellStatus, HashCells, PreparedQuery}; pub use readonly::ArrayModel; type Lit = i32; diff --git a/crates/aplite/src/finite/prepared.rs b/crates/aplite/src/finite/prepared.rs index 3016ce5691c..36f5d3916b9 100644 --- a/crates/aplite/src/finite/prepared.rs +++ b/crates/aplite/src/finite/prepared.rs @@ -1,6 +1,11 @@ //! Reusable scalar encoding with temporary Boolean assumptions. use super::*; +mod cell; +mod hashing; +pub use cell::{Cell, CellStatus}; +pub use hashing::HashCells; + /// Select the polarity of a predicate supplied when preparing the query. #[derive(Clone, Copy, Debug)] pub struct Assumption { diff --git a/crates/aplite/src/finite/prepared/cell.rs b/crates/aplite/src/finite/prepared/cell.rs new file mode 100644 index 00000000000..47da225784e --- /dev/null +++ b/crates/aplite/src/finite/prepared/cell.rs @@ -0,0 +1,442 @@ +//! Bounded projected model enumeration in a temporary SAT database. +use super::*; +use std::collections::BTreeSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CellStatus { + /// The entire selected cell was enumerated. It may be empty. + Complete, + /// At least max_models + 1 distinct projected models exist in the cell. + TooLarge, + /// Invalid input, unsupported query, or an exhausted resource budget. + Unknown, +} + +#[derive(Debug)] +pub struct Cell { + pub status: CellStatus, + /// Exposed only for Complete cells; never a biased truncated prefix. + /// Keys are original variable names, not context labels. + pub models: Vec>, + pub work: u64, + pub reason: Option, +} + +impl PreparedQuery { + /// Enumerate a bounded cell selected by temporary predicate assumptions. + /// + /// `projection` names distinct original scalar variables known at preparation. + /// Hidden witnesses do not multiply a projected assignment. One extra SAT + /// query distinguishes an exact-size cell from an oversized cell. The work + /// and time budgets cover all searches, blocking and replay in this call. + /// + /// This is a building block for hash-based sampling, not a sampling policy. + /// It never enumerates more than max_models + 1 witnesses. Blocking clauses + /// and learned clauses derived from them live only inside this call, so they + /// cannot change later cells or ordinary solves on the prepared query. + pub fn enumerate_cell( + &self, + assumptions: &[Assumption], + projection: &[String], + max_models: usize, + limits: Limits, + ) -> Cell { + let mut cell = Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: None, + }; + let mut budget = Budget { + limits, + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + let run = (|| -> Res { + budget.tick(1)?; + if self.blast.vars > budget.limits.max_variables + || self.blast.memo.len() > budget.limits.max_terms + || self.blast.clauses.len() > budget.limits.max_clauses + { + return Err("prepared cell exceeds solve size limits".into()); + } + let mut seen = BTreeSet::new(); + let mut bits = Vec::new(); + for name in projection { + budget.tick(1)?; + if !seen.insert(name) { + return Err("duplicate cell projection variable".into()); + } + let input = self + .blast + .inputs + .get(name) + .ok_or("unknown cell projection variable")?; + budget.tick(input.bits.len() as u64)?; + bits.extend_from_slice(&input.bits); + } + let mut literals = Vec::new(); + for assumption in assumptions { + budget.tick(1)?; + let lit = *self + .literals + .get(assumption.predicate) + .ok_or("invalid prepared predicate index")?; + literals.push(if assumption.value { lit } else { -lit }); + } + let mut clauses = Vec::new(); + for clause in &self.blast.clauses { + budget.tick(1 + clause.len() as u64)?; + clauses.push(clause.clone()); + } + // One scoped CDCL instance for the whole cell. Reuse encoding, + // propagation and local learning between models, without copying + // or recompiling the base formula on each enumeration step. + let mut solver = Sat::new(self.blast.vars, clauses); + loop { + match solver.run_slice_assuming(&mut budget, u64::MAX, &literals)? { + Search::Complete(Verdict::Unsat) => { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + Search::Complete(Verdict::Sat) => {} + _ => return Err("cell search did not complete".into()), + } + let (assignments, _) = 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("cell model failed assumption replay".into()); + } + } + if cell.models.len() == max_models { + budget.check_time()?; + return Ok(CellStatus::TooLarge); + } + let mut model = BTreeMap::new(); + for name in projection { + budget.tick(1)?; + model.insert(name.clone(), assignments[name].clone()); + } + let mut blocking = Vec::new(); + for &bit in &bits { + budget.tick(1)?; + blocking.push(if truth(&solver.values, bit) > 0 { + -bit + } else { + bit + }); + } + cell.models.push(model); + solver.backtrack(0, &mut budget)?; + if !add_blocking_clause(&mut solver, blocking, &mut budget)? { + budget.check_time()?; + return Ok(CellStatus::Complete); + } + } + })(); + cell.work = budget.work; + match run { + Ok(status) => cell.status = status, + Err(reason) => cell.reason = Some(reason), + } + if cell.status != CellStatus::Complete { + cell.models.clear(); + } + cell + } +} + +/// Insert a model blocker after backtracking to root. Root assignments are +/// permanent within this scoped database. Simplify by them before watching the +/// clause, so a newly inserted unit is propagated and an empty clause closes +/// the cell immediately. Assumption decisions have already been removed. +fn add_blocking_clause(solver: &mut Sat, clause: Vec, budget: &mut Budget) -> Res { + debug_assert!(solver.starts.is_empty()); + let mut remaining = BTreeSet::new(); + for lit in clause { + budget.tick(1)?; + match truth(&solver.values, lit) { + 1 => return Ok(true), + -1 => {} + _ => { + remaining.insert(lit); + } + } + } + if remaining.is_empty() { + return Ok(false); + } + if solver.clauses.len() >= budget.limits.max_clauses { + return Err("cell blocking-clause budget exhausted".into()); + } + let clause: Vec<_> = remaining.into_iter().collect(); + let unit = (clause.len() == 1).then_some(clause[0]); + let id = solver.clauses.len(); + solver.clauses.push(clause); + solver.attach(id); + if let Some(unit) = unit { + return Ok(solver.enqueue(unit, Some(id))); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{and, boolv, bv, eq, node, not, var}; + + fn selected(predicate: usize, value: bool) -> Assumption { + Assumption { predicate, value } + } + + #[test] + fn projected_enumeration_ignores_hidden_witnesses_and_is_scoped() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let formula = node(Sort::Bool, "or", vec![not(x.clone()), y.clone()]); + let mut query = + PreparedQuery::new(&formula, &Env::new(), &[x, y], Limits::default()).unwrap(); + for _ in 0..3 { + let cell = query.enumerate_cell(&[], &["x".into()], 2, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 2); + assert_ne!(cell.models[0], cell.models[1]); + let both = query.enumerate_cell(&[], &["x".into(), "y".into()], 3, Limits::default()); + assert_eq!(both.status, CellStatus::Complete); + assert_eq!(both.models.len(), 3); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + assert_eq!( + query + .solve(&[selected(0, false)], Limits::default(), 1) + .verdict, + Verdict::Sat + ); + } + } + + #[test] + fn exact_limit_overflow_empty_and_unsat_are_distinct() { + let x = var("x".into(), Sort::Bv(2)); + let query = PreparedQuery::new( + &boolv(true), + &Env::new(), + &[eq(x.clone(), bv(2, 0))], + Limits::default(), + ) + .unwrap(); + for bound in 0..=4 { + let cell = query.enumerate_cell(&[], &["x".into()], bound, Limits::default()); + assert_eq!( + cell.status, + if bound == 4 { + CellStatus::Complete + } else { + CellStatus::TooLarge + } + ); + assert_eq!(cell.models.len(), if bound == 4 { 4 } else { 0 }); + } + let empty = query.enumerate_cell( + &[selected(0, true), selected(0, false)], + &["x".into()], + 0, + Limits::default(), + ); + assert_eq!(empty.status, CellStatus::Complete); + assert!(empty.models.is_empty()); + let unit = query.enumerate_cell(&[], &[], 1, Limits::default()); + assert_eq!(unit.status, CellStatus::Complete); + assert_eq!(unit.models, vec![BTreeMap::new()]); + } + + #[test] + fn alias_and_constant_bits_do_not_duplicate_models() { + let x = var("x".into(), Sort::Bv(3)); + let y = var("y".into(), Sort::Bv(3)); + let z = var("z".into(), Sort::Bv(3)); + let formula = and(eq(x, y), eq(z, bv(3, 5))); + let query = PreparedQuery::new(&formula, &Env::new(), &[], Limits::default()).unwrap(); + let cell = query.enumerate_cell( + &[], + &["x".into(), "y".into(), "z".into()], + 8, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models.len(), 8); + for model in cell.models { + assert_eq!(model["x"], model["y"]); + assert_eq!(model["z"], Scalar::Bv { width: 3, value: 5 }); + } + } + + #[test] + fn xor_cells_cover_small_truth_tables_without_overlap() { + let x = var("x".into(), Sort::Bool); + let y = var("y".into(), Sort::Bool); + let z = var("z".into(), Sort::Bool); + let predicates = [ + node(Sort::Bool, "xor", vec![x.clone(), y.clone()]), + node(Sort::Bool, "xor", vec![y.clone(), z.clone()]), + ]; + for mask in 0..256u16 { + let mut formula = boolv(false); + for row in 0..8 { + if mask & (1 << row) != 0 { + let cube = and( + and( + eq(x.clone(), boolv(row & 1 != 0)), + eq(y.clone(), boolv(row & 2 != 0)), + ), + eq(z.clone(), boolv(row & 4 != 0)), + ); + formula = node(Sort::Bool, "or", vec![formula, cube]); + } + } + let query = + PreparedQuery::new(&formula, &Env::new(), &predicates, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + for target in 0..4 { + let cell = query.enumerate_cell( + &[selected(0, target & 1 != 0), selected(1, target & 2 != 0)], + &["x".into(), "y".into(), "z".into()], + 2, + Limits::default(), + ); + assert_eq!(cell.status, CellStatus::Complete); + for model in cell.models { + let row = usize::from(model["x"] == Scalar::Bool(true)) + | (usize::from(model["y"] == Scalar::Bool(true)) << 1) + | (usize::from(model["z"] == Scalar::Bool(true)) << 2); + assert_ne!(mask & (1 << row), 0); + assert!(found.insert(row)); + } + } + assert_eq!(found.len(), mask.count_ones() as usize); + } + } + + #[test] + fn wide_space_is_bounded_by_xor_cell_not_total_cardinality() { + let x = var("x".into(), Sort::Bv(32)); + let bit = |i| { + eq( + node(Sort::Bv(1), format!("(_ extract {i} {i})"), vec![x.clone()]), + bv(1, 1), + ) + }; + let predicates: Vec<_> = (4..32) + .map(|i| node(Sort::Bool, "xor", vec![bit(i), bit(i - 1)])) + .collect(); + let query = + PreparedQuery::new(&boolv(true), &Env::new(), &predicates, Limits::default()).unwrap(); + let assumptions: Vec<_> = (0..28).map(|i| selected(i, i % 3 == 0)).collect(); + let cell = query.enumerate_cell(&assumptions, &["x".into()], 16, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete, "{:?}", cell.reason); + assert_eq!(cell.models.len(), 16); + let mut lows = BTreeSet::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + lows.insert(value & 15); + for i in 4..32 { + assert_eq!( + ((value >> i) ^ (value >> (i - 1))) & 1 != 0, + (i - 4) % 3 == 0 + ); + } + } + assert_eq!(lows.len(), 16); + assert_eq!( + query + .enumerate_cell(&[], &["x".into()], 16, Limits::default()) + .status, + CellStatus::TooLarge + ); + } + + #[test] + fn failures_clear_partial_results_and_leave_prepared_state_untouched() { + let x = var("x".into(), Sort::Bv(3)); + let mut query = PreparedQuery::new( + &boolv(true), + &Env::from([("label".into(), x.clone())]), + &[eq(x, bv(3, 3))], + Limits::default(), + ) + .unwrap(); + query.solve(&[], Limits::default(), 0); + let original_clauses = query.sat.as_ref().unwrap().clauses.len(); + let full = query.enumerate_cell(&[], &["x".into()], 8, Limits::default()); + assert_eq!(full.status, CellStatus::Complete); + for work in [0, full.work / 2, full.work - 1] { + let cell = query.enumerate_cell( + &[], + &["x".into()], + 8, + Limits { + max_work: work, + ..Limits::default() + }, + ); + assert_eq!(cell.status, CellStatus::Unknown); + assert!(cell.models.is_empty()); + assert_eq!(query.sat.as_ref().unwrap().clauses.len(), original_clauses); + } + for projection in [vec!["label".into()], vec!["x".into(), "x".into()]] { + assert_eq!( + query + .enumerate_cell(&[], &projection, 8, Limits::default()) + .status, + CellStatus::Unknown + ); + } + assert_eq!( + query + .enumerate_cell(&[selected(1, true)], &[], 1, Limits::default()) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .enumerate_cell( + &[], + &[], + 1, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .status, + CellStatus::Unknown + ); + assert_eq!( + query + .solve(&[selected(0, true)], Limits::default(), 0) + .verdict, + Verdict::Sat + ); + } +} diff --git a/crates/aplite/src/finite/prepared/hashing.rs b/crates/aplite/src/finite/prepared/hashing.rs new file mode 100644 index 00000000000..264f1ce3338 --- /dev/null +++ b/crates/aplite/src/finite/prepared/hashing.rs @@ -0,0 +1,303 @@ +//! Seeded affine XOR partitions, with bounded projected cell queries. +use super::*; +use crate::{boolv, bv, eq, node}; +use std::collections::BTreeSet; + +/// A prepared family of affine XOR rows over projected scalar bits. +/// +/// Each row includes each bit and a constant with seed-selected coefficients. +/// With ideal independent random coefficients this is the standard affine XOR +/// hash family. The implementation uses a deterministic SplitMix64 PRNG, not a +/// source of cryptographic entropy. Rows may be zero or dependent: preserving +/// those cases is essential to the family; we do not silently repair them. +/// +/// `cell` selects a prefix of the rows and a target value for each selected row. +/// A caller can measure differently sized cells without recompiling the formula. +/// This is NOT a uniform sampler: choosing a cell and then a model arbitrarily +/// can bias results. A sampling policy must separately control cell acceptance, +/// target selection, and the distribution of models within accepted cells. +pub struct HashCells { + query: PreparedQuery, + projection: Vec, + rows: usize, + preparation_work: u64, +} + +impl HashCells { + /// Build at most `rows` XOR constraints. Projection values must be distinct + /// Bool or 1..=64-bit variable terms. Context labels do not affect model keys. + /// The single budget covers hash construction and query preparation. + pub fn new( + formula: &Term, + projection: &Env, + rows: usize, + seed: u64, + limits: Limits, + ) -> Res { + let mut budget = Budget { + limits: limits.clone(), + start: Instant::now(), + work: 0, + time_check_in: 0, + }; + budget.tick(1)?; + let mut created = 0usize; + let mut names = BTreeSet::new(); + let mut bits = Vec::new(); + for variable in projection.values() { + budget.tick(1)?; + let name = variable + .0 + .op + .strip_prefix('@') + .ok_or("hash projection requires variables")?; + if !variable.0.args.is_empty() + || !valid_sort(&variable.0.sort) + || !names.insert(name.to_owned()) + { + return Err("hash projection requires distinct supported scalar variables".into()); + } + let width = match variable.0.sort { + Sort::Bool => 1, + Sort::Bv(width) => width, + _ => unreachable!(), + }; + if bits.len().saturating_add(width as usize) > limits.max_variables { + return Err("hash projection bit budget exhausted".into()); + } + for bit in 0..width { + budget.tick(1)?; + let term = if variable.0.sort == Sort::Bool { + variable.clone() + } else { + reserve_terms(&mut created, 3, &budget)?; + eq( + node( + Sort::Bv(1), + format!("(_ extract {bit} {bit})"), + vec![variable.clone()], + ), + bv(1, 1), + ) + }; + bits.push(term); + } + } + if rows > bits.len() || rows > limits.max_terms { + return Err("hash row limit exceeds projected width or term budget".into()); + } + let mut rng = seed; + let mut predicates = Vec::new(); + for _ in 0..rows { + budget.tick(1)?; + reserve_terms(&mut created, 1, &budget)?; + let mut terms = vec![boolv(next(&mut rng) & 1 != 0)]; + for bit in &bits { + budget.tick(1)?; + if next(&mut rng) & 1 != 0 { + terms.push(bit.clone()); + } + } + predicates.push(parity(&terms, &mut budget, &mut created)?); + } + budget.check_time()?; + let mut remaining = limits; + remaining.max_work -= budget.work; + remaining.timeout_ms = remaining + .timeout_ms + .checked_sub(u64::try_from(budget.start.elapsed().as_millis()).unwrap_or(u64::MAX)) + .filter(|&ms| ms > 0) + .ok_or("hash preparation time budget exhausted")?; + let query = PreparedQuery::new(formula, projection, &predicates, remaining)?; + budget.tick(query.preparation_work())?; + budget.check_time()?; + Ok(Self { + query, + projection: names.into_iter().collect(), + rows, + preparation_work: budget.work, + }) + } + + pub fn preparation_work(&self) -> u64 { + self.preparation_work + } + + /// Targets select a prefix of the prepared XOR rows. Empty targets query + /// the unpartitioned space with the same bounded model limit. + pub fn cell(&self, targets: &[bool], max_models: usize, mut limits: Limits) -> Cell { + let start = Instant::now(); + if targets.len() > self.rows + || targets.len() as u64 >= limits.max_work + || limits.timeout_ms == 0 + { + return Cell { + status: CellStatus::Unknown, + models: Vec::new(), + work: 0, + reason: Some("hash targets exceed prepared rows or query budget".into()), + }; + } + let assumptions: Vec<_> = targets + .iter() + .enumerate() + .map(|(predicate, &value)| Assumption { predicate, value }) + .collect(); + let overhead = targets.len() as u64; + limits.max_work -= overhead; + let timeout = limits.timeout_ms; + let mut cell = + self.query + .enumerate_cell(&assumptions, &self.projection, max_models, limits); + cell.work = cell.work.saturating_add(overhead); + if start.elapsed().as_millis() >= u128::from(timeout) { + cell.status = CellStatus::Unknown; + cell.models.clear(); + cell.reason = Some("hash cell time budget exhausted".into()); + } + cell + } +} + +fn next(state: &mut u64) -> u64 { + *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) +} + +fn reserve_terms(created: &mut usize, amount: usize, budget: &Budget) -> Res<()> { + *created = created + .checked_add(amount) + .ok_or("hash construction term overflow")?; + if *created > budget.limits.max_terms { + return Err("hash construction term budget exhausted".into()); + } + Ok(()) +} + +fn parity(terms: &[Term], budget: &mut Budget, created: &mut usize) -> Res { + budget.tick(1)?; + if terms.len() == 1 { + return Ok(terms[0].clone()); + } + reserve_terms(created, 1, budget)?; + let mid = terms.len() / 2; + Ok(node( + Sort::Bool, + "xor", + vec![ + parity(&terms[..mid], budget, created)?, + parity(&terms[mid..], budget, created)?, + ], + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::var; + + #[test] + fn random_affine_cells_partition_and_reproduce_the_projected_domain() { + let x = var("x".into(), Sort::Bv(3)); + let context = Env::from([("label".into(), x)]); + let mut signatures = BTreeSet::new(); + for seed in 0..16 { + let cells = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let same = HashCells::new(&boolv(true), &context, 2, seed, Limits::default()).unwrap(); + let mut found = BTreeSet::new(); + let mut signature = Vec::new(); + for target in 0..4 { + let bits = [target & 1 != 0, target & 2 != 0]; + let cell = cells.cell(&bits, 8, Limits::default()); + assert_eq!(cell.status, CellStatus::Complete); + assert_eq!(cell.models, same.cell(&bits, 8, Limits::default()).models); + let mut values = Vec::new(); + for model in cell.models { + let Scalar::Bv { value, .. } = model["x"] else { + panic!() + }; + assert!(found.insert(value)); + values.push(value); + } + values.sort(); + signature.push(values); + } + assert_eq!(found.len(), 8); + signatures.insert(signature); + assert_eq!( + cells.cell(&[], 4, Limits::default()).status, + CellStatus::TooLarge + ); + assert_eq!( + cells.cell(&[false; 3], 8, Limits::default()).status, + CellStatus::Unknown + ); + } + assert!(signatures.len() > 1); + } + + #[test] + fn construction_and_cell_budgets_fail_closed() { + let context = Env::from([("x".into(), var("x".into(), Sort::Bv(8)))]); + assert!(HashCells::new(&boolv(true), &context, 9, 0, Limits::default()).is_err()); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_work: 1, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + timeout_ms: 0, + ..Limits::default() + } + ) + .is_err() + ); + assert!( + HashCells::new( + &boolv(true), + &context, + 3, + 0, + Limits { + max_terms: 2, + ..Limits::default() + } + ) + .is_err() + ); + let hash = HashCells::new(&boolv(true), &context, 3, 0, Limits::default()).unwrap(); + assert!(hash.preparation_work() > 0); + let failed = hash.cell( + &[true], + 8, + Limits { + max_work: 2, + ..Limits::default() + }, + ); + assert_eq!(failed.status, CellStatus::Unknown); + assert!(failed.models.is_empty()); + let duplicates = Env::from([ + ("x".into(), var("x".into(), Sort::Bool)), + ("alias".into(), var("x".into(), Sort::Bool)), + ]); + assert!(HashCells::new(&boolv(true), &duplicates, 1, 0, Limits::default()).is_err()); + } +} diff --git a/crates/aplite/src/lib.rs b/crates/aplite/src/lib.rs index 7a721daf55f..c9cad434b1a 100644 --- a/crates/aplite/src/lib.rs +++ b/crates/aplite/src/lib.rs @@ -10,8 +10,8 @@ pub use term::*; pub type Env = std::collections::BTreeMap; pub mod finite; pub use finite::{ - Assumption, Limits, Outcome, PreparedQuery, Scalar, SearchHint, Verdict, solve, solve_seeded, - solve_with_hint, + Assumption, Cell, CellStatus, HashCells, Limits, Outcome, PreparedQuery, Scalar, SearchHint, + Verdict, solve, solve_seeded, solve_with_hint, }; #[cfg(test)]