From fa42ab43e957b0f540c62680737131b52d2e9e4f Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 01:50:20 +0900 Subject: [PATCH 1/3] perf(sv): avoid redundant scope discovery and constant evaluation Repeated literal arithmetic in aggregate port defaults rediscovered declaration scopes and copied growing scope snapshots. Runtime select lowering also repeatedly attempted constant evaluation of large inlined expressions. Skip declaration discovery for expression trees composed entirely of literals, reject required unbound runtime operands before constant substitution, reuse binary operands already evaluated for type context, and return width one for identical runtime bit-select bounds. Keep names in unselected query arms on the discovery path and preserve short-circuit evaluation. Local compile measurements against master ee675d820f, using frozen CLI binaries and identical options: - 128 aggregate-default ports: 20.62 s to 0.69 s. - 256 aggregate-default ports: 90 s timeout to 0.50 s. - Original Taxi 32-channel Ethernet configuration: 123.971 s to 99.821 s, about 20% faster. - VCU108 still exceeds the 300 s compile limit with both binaries. This remains unresolved. Taxi sources were unchanged at cc70b270b910d369ab1ad7b3855e76399fd461f1. Taxi measurements cover compilation only, with O1 and two-state operation; cocotb runtime tests were not rerun. These are local measurements rather than timing assertions in CI. Validation: - Analyzer/frontend unit tests: 846 passed; 2 doctests passed. - Full SystemVerilog backend suite: 5,664 passed; 20 existing skips. - Clippy for celox-sv-analyzer, celox-frontend-sv and celox tests with systemverilog, cranelift and wasm-runtime: passed with -D warnings. - cargo fmt --all -- --check and git diff --check: passed. Regression tests assert discovery/evaluation counts and width semantics without wall-clock thresholds. Shared executable cases and external adapters are unchanged. Change-Id: Ia023a992051109e82c9ae3ae147c313b49f70e54 --- crates/celox-frontend-sv/src/lowering.rs | 37 ++++ .../src/ast/dimensions/query_binding.rs | 45 +++-- .../src/ast/dimensions/tests.rs | 68 ++++++++ crates/celox-sv-analyzer/src/typecheck.rs | 164 +++++++++++++++++- 4 files changed, 303 insertions(+), 11 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d7029c83308..9c85e3b5931 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -8827,6 +8827,12 @@ fn runtime_select_width( if constant(msb).is_some() && constant(lsb).is_some() { return None; } + // A bit select has width one regardless of its runtime position. Sampling + // both bounds evaluates the same (potentially inlined) expression twice, + // and the zero sample need not even be a valid index computation. + if msb == lsb { + return Some(1); + } // The width is the same for every value of the runtime operands. let mut sample = constants.clone(); for name in name_to_id.keys() { @@ -10510,6 +10516,37 @@ fn inferred_clock( mod tests { use super::*; + #[test] + fn bit_select_width_does_not_evaluate_a_runtime_zero_sample() { + let index = sv::ir::ConstExpr::Ident("index".into()); + let bound = sv::ir::ConstExpr::Binary { + left: Box::new(sv::ir::ConstExpr::Literal("255".into())), + op: sv::ir::BinaryOp::Div, + right: Box::new(index.clone()), + }; + let names = HashMap::from_iter([("index".into(), SourceVarId(0))]); + let constants = HashMap::default(); + let types = HashMap::default(); + assert_eq!( + runtime_select_width(&bound, &bound, &names, &constants, &types), + Some(1) + ); + let high = sv::ir::ConstExpr::Binary { + left: Box::new(index.clone()), + op: sv::ir::BinaryOp::Add, + right: Box::new(sv::ir::ConstExpr::Literal("7".into())), + }; + assert_eq!( + runtime_select_width(&high, &index, &names, &constants, &types), + Some(8) + ); + let constant = sv::ir::ConstExpr::Literal("3".into()); + assert_eq!( + runtime_select_width(&constant, &constant, &names, &constants, &types), + None + ); + } + /// The per-name driver scan [`ModuleDrivers`] replaced, which walks every /// process for each name. mod per_name_scan { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 353055ff483..83c870dbb80 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -21,21 +21,46 @@ fn query_context(context: &PackedDimensions) -> PackedDimensions { query } +/// These operands carry all type information in their literal leaves. Walking +/// declaration scopes cannot change their shape or signedness. Keep calls, +/// casts and names on the discovery path, including names in unevaluated arms. +fn literal_operand(root: ExprId, native: &celox_sv_syntax::Declarations) -> bool { + let root = expression_binding::ungroup(root, native); + if matches!(native.expression(root).kind, ExprKind::Literal(_)) { + return true; + } + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + match &native.expression(id).kind { + ExprKind::Literal(_) => {} + ExprKind::Group(inner) + | ExprKind::Unary { + expression: inner, .. + } => { + pending.push(*inner); + } + ExprKind::Binary { left, right, .. } => pending.extend([*left, *right]), + ExprKind::Conditional { + condition, + then_expression, + else_expression, + } => { + pending.extend([*condition, *then_expression, *else_expression]); + } + _ => return false, + } + } + true +} + pub(in crate::ast) fn query_context_for_operand( root: ExprId, tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - // Literals carry their type in their spelling and cannot reference lexical - // declarations. Pattern elements otherwise rediscover the whole scope for - // each literal while the surrounding declaration is still being bound. - let operand = expression_binding::ungroup(root, tree.declarations()); - if context.scope_types_complete - || matches!( - tree.declarations().expression(operand).kind, - ExprKind::Literal(_) - ) - { + // Aggregate port defaults commonly repeat literal arithmetic. Rediscovering + // all declarations for each item repeatedly snapshots the growing prefix. + if context.scope_types_complete || literal_operand(root, tree.declarations()) { return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index f29dadcf3e5..eeeac9bcae6 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -45,6 +45,74 @@ fn query_number( .and_then(|value| usize::try_from(value).ok()) } +#[test] +fn repeated_literal_port_defaults_do_not_rediscover_declarations() { + for count in [8, 32, 128] { + let ports = (0..count) + .map(|i| format!("input logic [7:0] p{i}[2] = '{{2{{8'd60-1}}}}")) + .collect::>() + .join(","); + let code = format!("module Top({ports}, output wire [7:0] y); assign y=p0[0]; endmodule"); + let tree = + crate::source_tree::parse_scope_fixture(&code, Path::new("literal-port-defaults.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let source = Source::from_syntax(&tree).unwrap(); + assert_eq!(source.modules()[0].ports().len(), count + 1); + assert_eq!( + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), + 0, + "{count} ports" + ); + } +} + +#[test] +fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { + let code = "module Top; assign y=$bits(8'd60-1)+$bits(-8'sd1+16'sd2)+$bits(1'b0 ? 8'hff : 16'hffff)+$bits(~8'hff)+$bits(32'd1<<64'd40); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("literal-query-types.sv")).unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let input = PackedDimensions::default(); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let values = native_calls(&tree) + .into_iter() + .map(|root| { + query_number( + root, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&input), + ) + }) + .collect::>(); + assert_eq!(values, [Some(32), Some(16), Some(16), Some(8), Some(32)]); + assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), 0); +} + +#[test] +fn queries_still_discover_names_in_unselected_conditional_arms() { + let code = "module Top; logic [15:0] data; assign y=$bits(1'b0 ? data : 8'hff); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("conditional-query-types.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + assert_eq!( + query_number( + native_calls(&tree)[0], + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&PackedDimensions::default()) + ), + Some(16) + ); + assert!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()) > 0); +} + #[test] fn function_result_queries_preserve_expression_bodies() { let tree = crate::source_tree::parse_scope_fixture( diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 460881888e5..f795cfb1994 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -345,6 +345,11 @@ pub fn eval_const_expr_with_types( constants: &HashMap, types: &HashMap, ) -> Option { + // Runtime select bounds often contain large inlined expressions. Reject a + // required runtime value before attempting literal folding at every node. + if requires_unbound_value(expr, constants) { + return None; + } // Substitution only replaces the identifiers of typed constants. if !has_typed_constant(expr, constants, types) { return eval_const_expr(expr, constants); @@ -353,6 +358,38 @@ pub fn eval_const_expr_with_types( eval_const_expr(&expr, constants) } +fn requires_unbound_value(expr: &ConstExpr, constants: &HashMap) -> bool { + match expr { + ConstExpr::Literal(_) | ConstExpr::Function { .. } => return false, + ConstExpr::Ident(name) => return !constants.contains_key(name), + _ => {} + } + let mut pending = vec![expr]; + while let Some(expr) = pending.pop() { + match expr { + ConstExpr::Ident(name) if !constants.contains_key(name) => return true, + ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => pending.push(expr), + ConstExpr::Select { expr, bit } => pending.extend([bit.as_ref(), expr.as_ref()]), + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + pending.extend([lsb.as_ref(), msb.as_ref(), expr.as_ref()]); + } + ConstExpr::Binary { left, op, right } => { + // A right logical operand can be skipped. The left operand is + // required; preserve the evaluator's short-circuiting policy. + if !matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) { + pending.push(right); + } + pending.push(left); + } + ConstExpr::Mux { condition, .. } => pending.push(condition), + // Argument evaluation belongs to the callee (including checked + // accesses). Do not infer whether a call needs its actuals here. + ConstExpr::Function { .. } | ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} + } + } + false +} + /// Whether `expr` names a constant that has a type, which /// [`substitute_typed_constants`] replaces with a sized literal. fn has_typed_constant( @@ -714,6 +751,15 @@ fn context_binary_operands( right: &ConstExpr, ) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let (left_type, right_type) = integral_binary_operands(left, right)?; + context_binary_values(left, right, left_type, right_type) +} + +fn context_binary_values( + left: &ConstExpr, + right: &ConstExpr, + left_type: IntegralLiteral, + right_type: IntegralLiteral, +) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let width = left_type.width.max(right_type.width); let signed = left_type.signed && right_type.signed; // These values were already evaluated in their own expression contexts. @@ -783,7 +829,7 @@ fn eval_literal_binary( ); return eval_four_state_binary(&left, op, &right, signed); } - let (left, right, signed) = context_binary_operands(left_expr, right_expr)?; + let (left, right, signed) = context_binary_values(left_expr, right_expr, left, right)?; eval_four_state_binary(&left, op, &right, signed) } @@ -1089,7 +1135,14 @@ fn self_determined_integral_literal(expr: &ConstExpr) -> Option } } +#[cfg(test)] +thread_local! { + static LITERAL_EVALUATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option { + #[cfg(test)] + LITERAL_EVALUATIONS.with(|count| count.set(count.get() + 1)); match expr { ConstExpr::Literal(literal) => parse_integral_literal(literal), ConstExpr::Resize { @@ -2015,6 +2068,115 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) { mod literal_tests { use super::*; + #[test] + fn numeric_binary_operands_are_evaluated_once_before_type_context() { + let expr = ConstExpr::Binary { + left: Box::new(ConstExpr::Literal("2".into())), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Literal("3".into())), + }; + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + Some(5) + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 2); + } + + #[test] + fn runtime_bounds_skip_literal_evaluation_before_substitution() { + let mut bound = ConstExpr::Ident("runtime_index".into()); + for _ in 0..64 { + bound = ConstExpr::Resize { + expr: Box::new(ConstExpr::Binary { + left: Box::new(bound), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Ident("P".into())), + }), + width: 32, + signed: false, + }; + } + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types( + &bound, + &HashMap::from_iter([("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + None + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 0); + } + + #[test] + fn runtime_bound_probe_preserves_short_circuiting_and_sampled_values() { + let literal = |text: &str| ConstExpr::Literal(text.into()); + let missing = || ConstExpr::Ident("runtime_index".into()); + let expressions = [ + ( + ConstExpr::Binary { + left: Box::new(literal("0")), + op: BinaryOp::LogicAnd, + right: Box::new(missing()), + }, + Some(0), + ), + ( + ConstExpr::Binary { + left: Box::new(literal("1")), + op: BinaryOp::LogicOr, + right: Box::new(missing()), + }, + Some(1), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1")), + then_expr: Box::new(literal("13")), + else_expr: Box::new(missing()), + }, + Some(13), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("0")), + then_expr: Box::new(missing()), + else_expr: Box::new(literal("19")), + }, + Some(19), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1'bx")), + then_expr: Box::new(literal("17")), + else_expr: Box::new(literal("17")), + }, + Some(17), + ), + ]; + for (expr, expected) in expressions { + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + expected, + "{expr:?}" + ); + } + let sample = ConstExpr::Binary { + left: Box::new(missing()), + op: BinaryOp::Mul, + right: Box::new(ConstExpr::Ident("P".into())), + }; + assert_eq!( + eval_const_expr_with_types( + &sample, + &HashMap::from_iter([("runtime_index".into(), 3), ("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + Some(21) + ); + } + /// Expressions without typed constants evaluate as their substituted /// copies do, and typed constants still take their declared type. #[test] From e8aec711eeb131c130b068520c3d0f3e1c9ee9cf Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 02:00:27 +0900 Subject: [PATCH 2/3] 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)] From 681261a189a13675ee531defd1d907777ca14145 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:27:13 +0000 Subject: [PATCH 3/3] chore(deps): update actions/setup-node action to v7 --- .github/workflows/publish-aplite.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish-aplite.yml b/.github/workflows/publish-aplite.yml index bd20e7ea3ee..7a63ac31eef 100644 --- a/.github/workflows/publish-aplite.yml +++ b/.github/workflows/publish-aplite.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/checkout@v7 with: ref: ${{ github.sha }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '24' - name: Check release identity @@ -46,7 +46,7 @@ jobs: - uses: actions/checkout@v7 with: ref: ${{ github.sha }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '24' - uses: ./.github/actions/setup-rust