Skip to main content

constraint_search/
parallel.rs

1//! Parallel search over one shared [`Model`], behind the `parallel` feature (needs `std`).
2//!
3//! [`ParallelSolver`] splits the search tree into subproblems: it fixes the first few
4//! branching variables in every consistent way, and a pool of threads works through those
5//! partial assignments, each with its own [`Solver`]. A shared flag stops every thread at the
6//! first solution, or when a count reaches its limit (2 for a uniqueness check).
7//! [`ParallelSolver::portfolio`] instead races different branching heuristics on the whole
8//! problem.
9//!
10//! ```mermaid
11//! flowchart LR
12//!     model[Model] --> split[split into partial assignments]
13//!     split --> queue[(shared queue)]
14//!     queue --> w1[worker: Solver] & w2[worker: Solver] & w3[worker: Solver]
15//!     w1 & w2 & w3 -->|solution / limit / budget| stop[shared stop flag]
16//! ```
17
18extern crate std;
19
20use alloc::collections::VecDeque;
21use alloc::vec;
22use alloc::vec::Vec;
23use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
24use std::sync::Mutex;
25use std::thread;
26
27use search_core::Budget;
28
29use crate::{
30    Count, Domain, Inconsistent, Model, Outcome, Progress, Report, Solver, Stats, ValueOrder, Var,
31    VarOrder,
32};
33
34/// A partial assignment: the subproblem one worker searches.
35type Cube = Vec<(Var, u32)>;
36
37/// Backtracking search over a shared model on several threads.
38///
39/// Each worker thread owns a [`Solver`] and searches subproblems below partial assignments
40/// of the first branching variables. Which solution [`ParallelSolver::solve`] returns depends
41/// on thread timing; counts are exact whenever the search completes.
42///
43/// The budget is cloned into every worker and judges that worker's own counters. When any
44/// worker's budget runs out, all workers stop and the result is incomplete.
45///
46/// # Examples
47///
48/// ```
49/// use constraint_search::{AllDifferent, Count, Domain, Model, ParallelSolver, Stats};
50///
51/// let mut model = Model::<u16>::new();
52/// let vars = model.add_vars(6, u16::range(6));
53/// model.add(AllDifferent::new(vars));
54///
55/// let report = ParallelSolver::new(&model, 4).count(u64::MAX, |_: &Stats| false);
56/// assert_eq!(report.outcome, Count::Exact(720));
57/// ```
58pub struct ParallelSolver<'m, D> {
59    /// The problem being solved.
60    model: &'m Model<D>,
61    /// The number of worker threads. At least 1.
62    threads: usize,
63    /// How workers pick the variable to branch on; also used to split the tree.
64    var_order: VarOrder,
65    /// How workers order the values of that variable.
66    value_order: ValueOrder,
67    /// How many subproblems to aim for per thread, so that fast threads take over the work
68    /// of slow ones.
69    pieces_per_thread: usize,
70}
71
72impl<'m, D: Domain> ParallelSolver<'m, D> {
73    /// A parallel solver over `model` with `threads` worker threads, branching with
74    /// [`VarOrder::Mrv`] and [`ValueOrder::Ascending`].
75    ///
76    /// # Panics
77    ///
78    /// Panics if `threads` is 0.
79    #[must_use]
80    pub fn new(model: &'m Model<D>, threads: usize) -> Self {
81        assert!(threads > 0, "a parallel search needs at least one thread");
82
83        Self {
84            model,
85            threads,
86            var_order: VarOrder::default(),
87            value_order: ValueOrder::default(),
88            pieces_per_thread: 8,
89        }
90    }
91
92    /// Sets how workers pick the variable to branch on.
93    #[must_use]
94    pub fn with_var_order(mut self, order: VarOrder) -> Self {
95        self.var_order = order;
96        self
97    }
98
99    /// Sets how workers order the values of the branching variable.
100    #[must_use]
101    pub fn with_value_order(mut self, order: ValueOrder) -> Self {
102        self.value_order = order;
103        self
104    }
105
106    /// Finds one solution, stopping every thread at the first one found.
107    pub fn solve<B: Budget<Stats> + Clone + Send>(&self, budget: B) -> Report<Outcome> {
108        let cubes = split(
109            self.model,
110            self.var_order,
111            self.threads * self.pieces_per_thread,
112        );
113        let shared = Shared::new(Goal::First);
114        let orders = vec![(self.var_order, self.value_order); self.threads];
115        let stats = run_workers(self.model, &orders, &cubes, &shared, budget, false);
116
117        Report {
118            outcome: shared.outcome(),
119            stats,
120        }
121    }
122
123    /// Counts solutions on all threads, stopping every thread once `limit` are found.
124    ///
125    /// A limit of 2 decides uniqueness. Threads may find a few solutions past the limit
126    /// before they see the stop; [`Count::AtLeast`] then reports all of them.
127    pub fn count<B: Budget<Stats> + Clone + Send>(&self, limit: u64, budget: B) -> Report<Count> {
128        if limit == 0 {
129            return Report {
130                outcome: Count::AtLeast(0),
131                stats: Stats::default(),
132            };
133        }
134
135        let cubes = split(
136            self.model,
137            self.var_order,
138            self.threads * self.pieces_per_thread,
139        );
140        let shared = Shared::new(Goal::Count(limit));
141        let orders = vec![(self.var_order, self.value_order); self.threads];
142        let stats = run_workers(self.model, &orders, &cubes, &shared, budget, false);
143
144        Report {
145            outcome: shared.count(),
146            stats,
147        }
148    }
149
150    /// Races one thread per `(VarOrder, ValueOrder)` pair on the whole problem and returns
151    /// the first solution any of them finds.
152    ///
153    /// # Panics
154    ///
155    /// Panics if `orders` is empty.
156    pub fn portfolio<B: Budget<Stats> + Clone + Send>(
157        model: &Model<D>,
158        orders: &[(VarOrder, ValueOrder)],
159        budget: B,
160    ) -> Report<Outcome> {
161        assert!(
162            !orders.is_empty(),
163            "a portfolio needs at least one strategy"
164        );
165
166        let cubes = vec![Cube::new()];
167        let shared = Shared::new(Goal::First);
168        let stats = run_workers(model, orders, &cubes, &shared, budget, true);
169
170        Report {
171            outcome: shared.outcome(),
172            stats,
173        }
174    }
175}
176
177/// What the workers search for.
178#[derive(Debug, Clone, Copy)]
179enum Goal {
180    /// The first solution.
181    First,
182    /// Solutions, until this many are found.
183    Count(u64),
184}
185
186/// The state all workers share.
187struct Shared {
188    /// What the workers search for.
189    goal: Goal,
190    /// The index of the next subproblem to take.
191    next: AtomicUsize,
192    /// Set when every worker must stop.
193    stop: AtomicBool,
194    /// Set when a worker's budget ran out, so the search is incomplete.
195    exhausted: AtomicBool,
196    /// Solutions found so far, by all workers.
197    found: AtomicU64,
198    /// The first solution found, for [`Goal::First`].
199    solution: Mutex<Option<Vec<u32>>>,
200}
201
202impl Shared {
203    /// Fresh shared state for `goal`.
204    fn new(goal: Goal) -> Self {
205        Self {
206            goal,
207            next: AtomicUsize::new(0),
208            stop: AtomicBool::new(false),
209            exhausted: AtomicBool::new(false),
210            found: AtomicU64::new(0),
211            solution: Mutex::new(None),
212        }
213    }
214
215    /// Records the solution in `domains`; returns `true` if the workers should stop.
216    fn record<D: Domain>(&self, solver: &Solver<'_, D>) -> bool {
217        let found = self.found.fetch_add(1, Ordering::SeqCst) + 1;
218        match self.goal {
219            Goal::First => {
220                let mut solution = self.solution.lock().expect("no worker panics holding it");
221                if solution.is_none() {
222                    *solution = solver.domains().solution();
223                }
224
225                true
226            }
227            Goal::Count(limit) => found >= limit,
228        }
229    }
230
231    /// The outcome of a [`Goal::First`] search.
232    fn outcome(&self) -> Outcome {
233        let solution = self.solution.lock().expect("no worker panics holding it");
234        match solution.clone() {
235            Some(values) => Outcome::Solved(values),
236            None if self.exhausted.load(Ordering::SeqCst) => Outcome::Exhausted,
237            None => Outcome::Unsatisfiable,
238        }
239    }
240
241    /// The outcome of a [`Goal::Count`] search.
242    fn count(&self) -> Count {
243        let found = self.found.load(Ordering::SeqCst);
244        if self.stop.load(Ordering::SeqCst) {
245            Count::AtLeast(found)
246        } else {
247            Count::Exact(found)
248        }
249    }
250}
251
252/// Runs one worker per entry of `orders` over `cubes` and returns their summed counters.
253///
254/// With `each_takes_all`, every worker searches every cube (a portfolio); otherwise the
255/// workers share the cubes out.
256fn run_workers<D: Domain, B: Budget<Stats> + Clone + Send>(
257    model: &Model<D>,
258    orders: &[(VarOrder, ValueOrder)],
259    cubes: &[Cube],
260    shared: &Shared,
261    budget: B,
262    each_takes_all: bool,
263) -> Stats {
264    thread::scope(|scope| {
265        // One budget per worker: clones for all but the last, which takes the original.
266        let budgets = core::iter::repeat_n(budget, orders.len());
267        let workers: Vec<_> = orders
268            .iter()
269            .zip(budgets)
270            .map(|(&(var_order, value_order), budget)| {
271                scope.spawn(move || {
272                    let solver = Solver::new(model)
273                        .with_var_order(var_order)
274                        .with_value_order(value_order);
275                    let next = AtomicUsize::new(0);
276                    let queue = if each_takes_all { &next } else { &shared.next };
277                    work(solver, cubes, queue, shared, budget)
278                })
279            })
280            .collect();
281
282        workers
283            .into_iter()
284            .map(|worker| worker.join().expect("a worker panicked"))
285            .fold(Stats::default(), Stats::plus)
286    })
287}
288
289/// Takes cubes from `queue` and searches below each until the queue runs dry or the shared
290/// flag says stop; returns the worker's counters.
291fn work<D: Domain>(
292    mut solver: Solver<'_, D>,
293    cubes: &[Cube],
294    queue: &AtomicUsize,
295    shared: &Shared,
296    mut budget: impl Budget<Stats>,
297) -> Stats {
298    let mut total = Stats::default();
299    while !shared.stop.load(Ordering::SeqCst) {
300        let Some(cube) = cubes.get(queue.fetch_add(1, Ordering::SeqCst)) else {
301            break;
302        };
303
304        if load(&mut solver, cube).is_ok() {
305            total = search_cube(&mut solver, shared, &mut budget, total);
306        }
307    }
308
309    total
310}
311
312/// Searches below the loaded cube until it is exhausted or the workers must stop; returns
313/// `total` plus the work done.
314fn search_cube<D: Domain>(
315    solver: &mut Solver<'_, D>,
316    shared: &Shared,
317    budget: &mut impl Budget<Stats>,
318    mut total: Stats,
319) -> Stats {
320    solver.begin();
321    loop {
322        let base = total;
323        let report = solver.resume(|stats: &Stats| {
324            shared.stop.load(Ordering::SeqCst) || budget.exhausted(&base.plus(*stats))
325        });
326        total = base.plus(report.stats);
327
328        match report.outcome {
329            Progress::Solution => {
330                if shared.record(solver) {
331                    shared.stop.store(true, Ordering::SeqCst);
332                    break;
333                }
334            }
335            Progress::Paused => {
336                if !shared.stop.swap(true, Ordering::SeqCst) {
337                    shared.exhausted.store(true, Ordering::SeqCst);
338                }
339
340                break;
341            }
342            Progress::Complete => break,
343        }
344    }
345
346    solver.abandon();
347    total
348}
349
350/// Resets the solver and fixes the assignments of `cube`.
351///
352/// # Errors
353///
354/// Returns [`Inconsistent`] if an assignment contradicts the initial domains.
355fn load<D: Domain>(solver: &mut Solver<'_, D>, cube: &Cube) -> Result<(), Inconsistent> {
356    solver.reset();
357    for &(var, value) in cube {
358        solver.domains_mut().assign(var, value)?;
359    }
360
361    Ok(())
362}
363
364/// Splits the search tree into at least `target` partial assignments, where it can, by
365/// fixing branching variables breadth first. Inconsistent branches are dropped; an
366/// inconsistent model yields none.
367fn split<D: Domain>(model: &Model<D>, var_order: VarOrder, target: usize) -> Vec<Cube> {
368    let mut solver = Solver::new(model);
369    let mut open: VecDeque<Cube> = VecDeque::from([Cube::new()]);
370    let mut leaves = Vec::new();
371
372    while open.len() + leaves.len() < target {
373        let Some(cube) = open.pop_front() else {
374            break;
375        };
376
377        if load(&mut solver, &cube)
378            .and_then(|()| solver.propagate())
379            .is_err()
380        {
381            continue;
382        }
383
384        let Some(var) = var_order.pick(solver.domains()) else {
385            leaves.push(cube);
386            continue;
387        };
388
389        for value in solver.domains()[var].values() {
390            let mut child = cube.clone();
391            child.push((var, value));
392            open.push_back(child);
393        }
394    }
395
396    open.into_iter().chain(leaves).collect()
397}
398
399/// Unit tests for [`ParallelSolver`].
400#[cfg(test)]
401mod tests {
402    use super::{ParallelSolver, split};
403    use crate::{AllDifferent, Count, Domain, Model, Outcome, Stats, ValueOrder, VarOrder};
404
405    /// Six variables over six values, all different: 720 solutions.
406    fn permutations(n: usize) -> Model<u16> {
407        let mut model = Model::new();
408        let vars = model.add_vars(n, u16::range(u32::try_from(n).unwrap()));
409        model.add(AllDifferent::new(vars));
410
411        model
412    }
413
414    /// Counting on several threads matches the exact count, and a limit stops early.
415    #[test]
416    fn counts_agree_with_sequential() {
417        let model = permutations(6);
418        for threads in [1, 3, 8] {
419            let solver = ParallelSolver::new(&model, threads);
420            let report = solver.count(u64::MAX, |_: &Stats| false);
421            assert_eq!(report.outcome, Count::Exact(720), "{threads} threads");
422            assert_eq!(report.stats.solutions, 720);
423
424            match solver.count(2, |_: &Stats| false).outcome {
425                Count::AtLeast(found) => assert!(found >= 2),
426                Count::Exact(_) => panic!("720 solutions exceed the limit"),
427            }
428        }
429
430        let solver = ParallelSolver::new(&model, 2);
431        assert_eq!(
432            solver.count(0, |_: &Stats| false).outcome,
433            Count::AtLeast(0)
434        );
435    }
436
437    /// Solving returns a valid solution, an unsatisfiable model none.
438    #[test]
439    fn solve_finds_a_solution_or_none() {
440        let model = permutations(5);
441        let Outcome::Solved(values) = ParallelSolver::new(&model, 4)
442            .solve(|_: &Stats| false)
443            .outcome
444        else {
445            panic!("solvable");
446        };
447
448        let mut seen = values.clone();
449        seen.sort_unstable();
450        assert_eq!(seen, [0, 1, 2, 3, 4]);
451
452        let mut model = Model::<u16>::new();
453        let vars = model.add_vars(3, u16::range(2));
454        model.add(AllDifferent::new(vars));
455        let report = ParallelSolver::new(&model, 3).solve(|_: &Stats| false);
456        assert_eq!(report.outcome, Outcome::Unsatisfiable);
457        assert_eq!(split(&model, VarOrder::Mrv, 8).len(), 0);
458    }
459
460    /// A budget stops all workers, and the portfolio races heuristics to a solution.
461    #[test]
462    fn budget_and_portfolio() {
463        let model = permutations(7);
464        let solver = ParallelSolver::new(&model, 2)
465            .with_var_order(VarOrder::Input)
466            .with_value_order(ValueOrder::Descending);
467        let report = solver.count(u64::MAX, |stats: &Stats| stats.nodes >= 50);
468        assert!(matches!(report.outcome, Count::AtLeast(_)));
469        assert_eq!(solver.solve(|_: &Stats| true).outcome, Outcome::Exhausted);
470
471        let orders = [
472            (VarOrder::Mrv, ValueOrder::Ascending),
473            (VarOrder::Input, ValueOrder::Lcv),
474        ];
475        let report = ParallelSolver::portfolio(&model, &orders, |_: &Stats| false);
476        assert!(matches!(report.outcome, Outcome::Solved(_)));
477    }
478}