From 5f14325537909e4cab6a40760974cfd6a995c999 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Thu, 5 Nov 2026 04:27:38 +0100 Subject: [PATCH 1/4] feat(scoring): fork a director over another solution `Director::fork_for_solution` builds an independent director of the same kind over a given solution: the constraint set is built for that solution with the recorded constructor, and the descriptor, weight mode, entity counter and score assertion are shared with the source. Unlike `fork_replica` it neither clones the working solution nor initializes the incremental state, so a sub-problem such as one partition of partitioned search initializes on the thread that solves it. Directors without a constraint-set constructor return `None`. --- crates/solverforge-scoring/WIREFRAME.md | 2 + crates/solverforge-scoring/public-api.txt | 3 +- .../src/director/score_director/adapters.rs | 4 ++ .../director/score_director/incremental.rs | 18 +++++-- .../src/director/tests/score_director.rs | 47 +++++++++++++++++++ .../src/director/traits.rs | 12 +++++ 6 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index 1b9e9821..b78e1b48 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -406,6 +406,7 @@ pub use stream::{ | `restore_score_state` | `fn restore_score_state(&mut self, state: DirectorScoreState)` | Restore a previously snapshotted committed score state | | `reset` | `fn reset(&mut self)` | Discard incremental state after an external working-solution rewrite; default: no-op | | `fork_replica` | `fn fork_replica(&self) -> Option where Self: Sized` | Independent evaluator replica with initialized incremental state, sharing the director's borrowed descriptor; default: `None` | +| `fork_for_solution` | `fn fork_for_solution(&self, solution: S) -> Option where Self: Sized` | Independent director of the same kind over another solution, incremental state uninitialized; default: `None` | ### `DirectorScoreState` @@ -611,6 +612,7 @@ Stock collectors include `count()`, `sum()`, `load_balance()`, - `simple_zero(solution)` — creates `ScoreDirector` with empty descriptor and zero entity counter - `with_descriptor(solution, constraints, descriptor: Desc, entity_counter)` — `Desc` is an owned `SolutionDescriptor` or a `ReplicaDescriptor`; `new()`, `simple()` and `simple_zero()` build owned-descriptor directors. - `Director::fork_replica` forks only directors holding a `ReplicaDescriptor`, in the same weight mode: the replica clones the working solution, builds its constraint set from that clone with the recorded constructor, initializes it, and shares the same borrowed descriptor. Owned-descriptor directors return `None`. +- `Director::fork_for_solution` forks the same way over a given solution instead of a clone of the working solution, and leaves the incremental state uninitialized so the first score calculation, on the thread that solves it, initializes it. Owned-descriptor directors return `None`. - `reset()` discards incremental state after an external rewrite of the working solution. Directors holding a `ReplicaDescriptor` rebuild their constraint set from the current working solution with the recorded constructor, so solution-derived constraint plans follow fact and entity changes; owned-descriptor directors reset their existing set. - Implements `Director` diff --git a/crates/solverforge-scoring/public-api.txt b/crates/solverforge-scoring/public-api.txt index 8015b08f..b6b10542 100644 --- a/crates/solverforge-scoring/public-api.txt +++ b/crates/solverforge-scoring/public-api.txt @@ -477,7 +477,7 @@ trait constraint::relational::AdaptWeight: pub trait AdaptWeight bool trait constraint::relational::RowWeight: pub trait RowWeight, Sc>: Send + Sync { // Required method fn score(&self, solution: &S, row: &O::View<'_>) -> Sc; } constraint::relational::RowWeight: fn score(&self, solution: &S, row: &O::View<'_>) -> Sc -trait director::Director: pub trait Director: Send { Show 18 methods // Required methods fn working_solution(&self) -> &S; fn working_solution_mut(&mut self) -> &mut S; fn calculate_score(&mut self) -> S::Score; fn solution_descriptor(&self) -> &SolutionDescriptor; fn clone_working_solution(&self) -> S; fn before_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn after_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn entity_count(&self, descriptor_index: usize) -> Option; fn total_entity_count(&self) -> Option; fn constraint_metadata(&self) -> Vec>; // Provided methods fn fresh_score(&self) -> Option { ... } fn set_score_assertion(&mut self, enabled: bool) { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState { ... } fn restore_score_state(&mut self, state: DirectorScoreState) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option where Self: Sized { ... } } +trait director::Director: pub trait Director: Send { Show 19 methods // Required methods fn working_solution(&self) -> &S; fn working_solution_mut(&mut self) -> &mut S; fn calculate_score(&mut self) -> S::Score; fn solution_descriptor(&self) -> &SolutionDescriptor; fn clone_working_solution(&self) -> S; fn before_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn after_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn entity_count(&self, descriptor_index: usize) -> Option; fn total_entity_count(&self) -> Option; fn constraint_metadata(&self) -> Vec>; // Provided methods fn fresh_score(&self) -> Option { ... } fn set_score_assertion(&mut self, enabled: bool) { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState { ... } fn restore_score_state(&mut self, state: DirectorScoreState) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option where Self: Sized { ... } fn fork_for_solution(&self, _solution: S) -> Option where Self: Sized { ... } } director::Director: fn working_solution(&self) -> &S director::Director: fn working_solution_mut(&mut self) -> &mut S director::Director: fn calculate_score(&mut self) -> S::Score @@ -496,6 +496,7 @@ trait director::Director: pub trait Director: Send { Show 1 director::Director: fn restore_score_state(&mut self, state: DirectorScoreState) director::Director: fn reset(&mut self) director::Director: fn fork_replica(&self) -> Option where Self: Sized, + director::Director: fn fork_for_solution(&self, _solution: S) -> Option where Self: Sized, trait director::score_director::DirectorDescriptor: pub trait DirectorDescriptor { // Required methods fn solution_descriptor(&self) -> &SolutionDescriptor; fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized; } director::score_director::DirectorDescriptor: fn solution_descriptor(&self) -> &SolutionDescriptor director::score_director::DirectorDescriptor: fn replica(&self) -> Option<(Self, fn(&S) -> C)> where Self: Sized, diff --git a/crates/solverforge-scoring/src/director/score_director/adapters.rs b/crates/solverforge-scoring/src/director/score_director/adapters.rs index 9f58bbf1..140898f4 100644 --- a/crates/solverforge-scoring/src/director/score_director/adapters.rs +++ b/crates/solverforge-scoring/src/director/score_director/adapters.rs @@ -114,4 +114,8 @@ where fn fork_replica(&self) -> Option { self.fork_replica_impl() } + + fn fork_for_solution(&self, solution: S) -> Option { + self.fork_for_solution_impl(solution) + } } diff --git a/crates/solverforge-scoring/src/director/score_director/incremental.rs b/crates/solverforge-scoring/src/director/score_director/incremental.rs index 10ac9edf..e7dc1b43 100644 --- a/crates/solverforge-scoring/src/director/score_director/incremental.rs +++ b/crates/solverforge-scoring/src/director/score_director/incremental.rs @@ -127,18 +127,26 @@ where /// The working-solution clone is the evaluator replica clone boundary: it /// happens when replicas are created, never per candidate or per step. pub(crate) fn fork_replica_impl(&self) -> Option { + let mut replica = self.fork_for_solution_impl(self.working_solution.clone())?; + replica.calculate_score_impl(); + Some(replica) + } + + /// Builds an independent director over `solution`: a constraint set built + /// for it, the same borrowed descriptor, weight mode, entity counter and + /// score assertion. Its incremental state is uninitialized; the first + /// score calculation initializes it, on whichever thread runs it. + pub(crate) fn fork_for_solution_impl(&self, solution: S) -> Option { let (descriptor, constraints) = self.solution_descriptor.replica()?; - let solution = self.working_solution.clone(); let replica_constraints = constraints(&solution); - let mut replica = Self::with_descriptor_in_mode( + let mut director = Self::with_descriptor_in_mode( solution, replica_constraints, descriptor, self.entity_counter, ); - replica.score_assertion = self.score_assertion; - replica.calculate_score_impl(); - Some(replica) + director.score_assertion = self.score_assertion; + Some(director) } /* ========================================================================= diff --git a/crates/solverforge-scoring/src/director/tests/score_director.rs b/crates/solverforge-scoring/src/director/tests/score_director.rs index f4ef7b2e..2987d058 100644 --- a/crates/solverforge-scoring/src/director/tests/score_director.rs +++ b/crates/solverforge-scoring/src/director/tests/score_director.rs @@ -409,6 +409,53 @@ fn fork_replica_matches_score_and_stays_independent() { assert_eq!(director.working_solution().values[1], None); } +#[test] +fn fork_for_solution_scores_its_own_solution_independently() { + let solution = TestSolution { + values: vec![Some(1), None, None], + score: None, + }; + let descriptor = test_descriptor(); + let mut director = ScoreDirector::with_descriptor( + solution.clone(), + unassigned_constraints(&solution), + ReplicaDescriptor::new(&descriptor, unassigned_constraints), + |_, _| 0, + ); + let main_score = director.calculate_score(); + + let partition = TestSolution { + values: vec![None, None, None, None, Some(2)], + score: None, + }; + let mut fork = director + .fork_for_solution(partition) + .expect("director with a constraint constructor must fork"); + assert!(!fork.is_initialized()); + assert!(std::ptr::eq( + Director::solution_descriptor(&fork), + Director::solution_descriptor(&director) + )); + assert_eq!(fork.calculate_score(), SoftScore::of(-4)); + + fork.before_variable_changed(0, 0); + fork.working_solution_mut().values[0] = Some(5); + fork.after_variable_changed(0, 0); + assert_eq!(fork.get_score(), SoftScore::of(-3)); + assert_eq!(director.get_score(), main_score); + assert_eq!(director.working_solution().values.len(), 3); +} + +#[test] +fn fork_for_solution_requires_a_replica_descriptor() { + let solution = TestSolution { + values: vec![Some(1)], + score: None, + }; + let director = ScoreDirector::new(solution.clone(), (make_unassigned_constraint(),)); + assert!(director.fork_for_solution(solution).is_none()); +} + #[test] fn fork_of_uninitialized_director_initializes_the_replica() { let solution = TestSolution { diff --git a/crates/solverforge-scoring/src/director/traits.rs b/crates/solverforge-scoring/src/director/traits.rs index bc82b6df..3d997648 100644 --- a/crates/solverforge-scoring/src/director/traits.rs +++ b/crates/solverforge-scoring/src/director/traits.rs @@ -115,4 +115,16 @@ pub trait Director: Send { { None } + + /// Builds an independent director of the same kind over `solution`, for + /// solving a sub-problem such as one partition of partitioned search. Its + /// incremental state is uninitialized until its first score calculation. + /// + /// Returns `None` when this director cannot construct one. + fn fork_for_solution(&self, _solution: S) -> Option + where + Self: Sized, + { + None + } } From 0c470c019c88776482409f88b73ee19ba0b97d45 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Thu, 5 Nov 2026 04:50:46 +0100 Subject: [PATCH 2/4] refactor(partitioned): run a partition pass through one shared function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `PartitionedSearchPhase` solved its partitions inline. The pass — split, solve each partition in its own child scope on the resolved thread count, merge — now lives in `solve_partitioned`, which takes the partitioner, the thread and logging settings, a director maker and the child-phase runner, so the configured runtime can run the same pass. Partition directors are now built on the solving thread, from the parent's director, before the partitions are dispatched; only `Send` directors cross to the worker threads, and each partition still initializes its score on the thread that solves it. `log_progress` now also logs the partition and thread counts at the start of a pass. --- crates/solverforge-solver/WIREFRAME.md | 3 +- .../src/phase/partitioned/execution.rs | 198 ++++++++++++++++++ .../src/phase/partitioned/mod.rs | 1 + .../src/phase/partitioned/phase.rs | 175 +--------------- .../phase/partitioned/phase_tests/limits.rs | 1 + 5 files changed, 213 insertions(+), 165 deletions(-) create mode 100644 crates/solverforge-solver/src/phase/partitioned/execution.rs diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 0a811a27..1d9664f2 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -303,6 +303,7 @@ src/ │ │ ├── mod.rs — Partitioned module declarations and re-exports │ │ ├── child_phases.rs — ChildPhases trait and tuple impls │ │ ├── config.rs — PartitionedSearchConfig +│ │ ├── execution.rs — One partition/solve/merge pass run by PartitionedSearchPhase │ │ ├── partitioner.rs — SolutionPartitioner trait, FunctionalPartitioner, ThreadCount │ │ ├── partitioner_tests.rs — Tests │ │ ├── phase.rs — PartitionedSearchPhase @@ -711,7 +712,7 @@ working solution without cloning. ### Partitioned Search -**`PartitionedSearchPhase`** — Generic over partitioner, score director factory, phase factory, child phases. Child scopes inherit runtime control, environment mode, remaining time limit, in-phase limits, and deterministic child seeds, but retained-job publication stays on the parent scope. The runtime phase-relative termination overlay is not propagated into a child scope. Pause checkpoints are emitted only from the parent full-solution boundary; child pause/cancel/config termination outcomes prevent partition merge. +**`PartitionedSearchPhase`** — Generic over partitioner, score director factory, phase factory, child phases. The score director factory runs on the solving thread for each partition before the partitions are dispatched; each partition initializes its score on the thread that solves it. Child scopes inherit runtime control, environment mode, remaining time limit, in-phase limits, and deterministic child seeds, but retained-job publication stays on the parent scope. The runtime phase-relative termination overlay is not propagated into a child scope. Pause checkpoints are emitted only from the parent full-solution boundary; child pause/cancel/config termination outcomes prevent partition merge. **`FunctionalPartitioner`** — Closure-based partitioner. diff --git a/crates/solverforge-solver/src/phase/partitioned/execution.rs b/crates/solverforge-solver/src/phase/partitioned/execution.rs new file mode 100644 index 00000000..8e3435fe --- /dev/null +++ b/crates/solverforge-solver/src/phase/partitioned/execution.rs @@ -0,0 +1,198 @@ +//! One partitioned-search pass: split the working solution, solve each +//! partition in its own child scope, merge. Run by +//! [`super::PartitionedSearchPhase`]. + +use rand::RngExt; +use rayon::prelude::*; +use rayon::ThreadPoolBuilder; +use solverforge_core::domain::PlanningSolution; +use solverforge_scoring::Director; + +use crate::manager::SolverTerminalReason; +use crate::scope::ProgressCallback; +use crate::scope::{PendingControl, SolverScope, SolverScopeChildConfig}; + +use super::config::PartitionedSearchConfig; +use super::partitioner::SolutionPartitioner; + +enum PartitionOutcome { + Complete(S), + Pause, + Cancelled, + Terminated, + /// A queued problem change stopped the child. The parent returns without + /// merging so the runner applies the change to the unmerged solution. + ProblemChange, +} + +/// Partitions the working solution with `partitioner`, solves every +/// partition with `solve_children` on up to `config.thread_count` threads, +/// and merges the solved partitions into the working solution. +/// +/// `make_director` builds each partition's director from the parent's on the +/// calling thread; +/// the partition's first score calculation, on the thread that solves it, +/// initializes it. A pause re-partitions from the parent's working solution +/// once resumed; cancellation, termination and a queued problem change stop +/// the pass without merging. +pub(crate) fn solve_partitioned( + solver_scope: &mut SolverScope<'_, S, D, BestCb>, + partitioner: &Part, + config: &PartitionedSearchConfig, + mut make_director: MakeDirector, + solve_children: &SolveChildren, +) where + S: PlanningSolution, + D: Director, + BestCb: ProgressCallback, + PD: Director, + Part: SolutionPartitioner, + MakeDirector: FnMut(&D, S) -> PD, + SolveChildren: Fn(&mut SolverScope<'_, S, PD>) + Sync, +{ + 'partitioning: loop { + if solver_scope.should_terminate() { + return; + } + + let solution = solver_scope.score_director().working_solution().clone(); + let partitions = partitioner.partition(&solution); + let partition_count = partitions.len(); + if partition_count == 0 { + return; + } + + let thread_count = config.thread_count.resolve(partition_count); + if config.log_progress { + tracing::info!( + event = "phase_start", + phase = "PartitionedSearch", + partition_count, + thread_count, + ); + } + + let directors: Vec = partitions + .into_iter() + .map(|partition| make_director(solver_scope.score_director(), partition)) + .collect(); + let children: Vec<(PD, u64)> = directors + .into_iter() + .map(|director| (director, solver_scope.rng().random())) + .collect(); + let phase_budget = solver_scope.child_phase_budget(); + let child_config = solver_scope.child_config(Some(&phase_budget)); + let outcomes = solve_partitions(children, thread_count, child_config, solve_children); + + let mut solved_partitions = Vec::with_capacity(outcomes.len()); + for outcome in outcomes { + match outcome { + PartitionOutcome::Complete(partition) => solved_partitions.push(partition), + PartitionOutcome::Pause => { + solver_scope.pause_if_requested(); + continue 'partitioning; + } + PartitionOutcome::Cancelled => { + solver_scope.mark_cancelled(); + return; + } + PartitionOutcome::Terminated => { + solver_scope.mark_terminated_by_config(); + return; + } + PartitionOutcome::ProblemChange => return, + } + } + + if solver_scope.should_terminate() { + return; + } + + let merged = partitioner.merge(&solution, solved_partitions); + solver_scope.replace_working_solution_and_reinitialize(merged); + solver_scope.update_best_solution(); + + if config.log_progress { + if let Some(score) = solver_scope.best_score() { + tracing::info!( + event = "phase_end", + phase = "PartitionedSearch", + score = %format!("{:?}", score), + ); + } + } + return; + } +} + +fn solve_partitions<'t, S, PD, SolveChildren>( + children: Vec<(PD, u64)>, + thread_count: usize, + child_config: SolverScopeChildConfig<'t, S>, + solve_children: &SolveChildren, +) -> Vec> +where + S: PlanningSolution, + PD: Director, + SolveChildren: Fn(&mut SolverScope<'_, S, PD>) + Sync, +{ + if thread_count <= 1 || children.len() <= 1 { + return children + .into_iter() + .map(|(director, seed)| { + solve_partition(director, child_config.clone(), seed, solve_children) + }) + .collect(); + } + + ThreadPoolBuilder::new() + .num_threads(thread_count) + .build() + .expect("failed to build partitioned search rayon pool") + .install(|| { + children + .into_par_iter() + .map(|(director, seed)| { + solve_partition(director, child_config.clone(), seed, solve_children) + }) + .collect() + }) +} + +fn solve_partition<'t, S, PD, SolveChildren>( + director: PD, + child_config: SolverScopeChildConfig<'t, S>, + seed: u64, + solve_children: &SolveChildren, +) -> PartitionOutcome +where + S: PlanningSolution, + PD: Director, + SolveChildren: Fn(&mut SolverScope<'_, S, PD>) + Sync, +{ + let mut solver_scope = child_config.build_scope(director, seed); + if solver_scope.should_terminate() { + return PartitionOutcome::Terminated; + } + solver_scope.initialize_working_solution_as_best(); + + solve_children(&mut solver_scope); + + match solver_scope.pending_control() { + PendingControl::PauseRequested => return PartitionOutcome::Pause, + PendingControl::CancelRequested => return PartitionOutcome::Cancelled, + PendingControl::ConfigTerminationRequested => return PartitionOutcome::Terminated, + PendingControl::ProblemChangeRequested => return PartitionOutcome::ProblemChange, + PendingControl::Continue => {} + } + if solver_scope.yielded_to_parent() { + return PartitionOutcome::Pause; + } + match solver_scope.terminal_reason() { + SolverTerminalReason::Cancelled => return PartitionOutcome::Cancelled, + SolverTerminalReason::TerminatedByConfig => return PartitionOutcome::Terminated, + SolverTerminalReason::Completed | SolverTerminalReason::Failed => {} + } + + PartitionOutcome::Complete(solver_scope.take_best_or_working_solution()) +} diff --git a/crates/solverforge-solver/src/phase/partitioned/mod.rs b/crates/solverforge-solver/src/phase/partitioned/mod.rs index 40f41ed1..9857e49e 100644 --- a/crates/solverforge-solver/src/phase/partitioned/mod.rs +++ b/crates/solverforge-solver/src/phase/partitioned/mod.rs @@ -23,6 +23,7 @@ log_progress: true, pub(crate) mod child_phases; pub(crate) mod config; +pub(crate) mod execution; pub(crate) mod partitioner; pub(crate) mod phase; diff --git a/crates/solverforge-solver/src/phase/partitioned/phase.rs b/crates/solverforge-solver/src/phase/partitioned/phase.rs index 695bef3f..db85f64e 100644 --- a/crates/solverforge-solver/src/phase/partitioned/phase.rs +++ b/crates/solverforge-solver/src/phase/partitioned/phase.rs @@ -3,31 +3,18 @@ use std::fmt::Debug; use std::marker::PhantomData; -use rand::RngExt; -use rayon::prelude::*; -use rayon::ThreadPoolBuilder; use solverforge_core::domain::PlanningSolution; use solverforge_scoring::Director; -use crate::manager::SolverTerminalReason; use crate::phase::Phase; use crate::scope::ProgressCallback; -use crate::scope::{PendingControl, SolverScope, SolverScopeChildConfig}; +use crate::scope::SolverScope; use super::child_phases::ChildPhases; use super::config::PartitionedSearchConfig; +use super::execution::solve_partitioned; use super::partitioner::SolutionPartitioner; -enum PartitionOutcome { - Complete(S), - Pause, - Cancelled, - Terminated, - /// A queued problem change stopped the child. The parent returns without - /// merging so the runner applies the change to the unmerged solution. - ProblemChange, -} - /// Partitioned search phase that solves partitions in parallel. /// /// This phase: @@ -137,73 +124,15 @@ where CP: ChildPhases + Send, { fn solve(&mut self, solver_scope: &mut SolverScope) { - 'partitioning: loop { - if solver_scope.should_terminate() { - return; - } - - let solution = solver_scope.score_director().working_solution().clone(); - let partitions = self.partitioner.partition(&solution); - let partition_count = partitions.len(); - - if partition_count == 0 { - return; - } - - let thread_count = self.config.thread_count.resolve(partition_count); - - if self.config.log_progress { - tracing::info!(event = "phase_start", phase = "PartitionedSearch",); - } - - let child_seeds: Vec = (0..partition_count) - .map(|_| solver_scope.rng().random()) - .collect(); - let phase_budget = solver_scope.child_phase_budget(); - let child_config = solver_scope.child_config(Some(&phase_budget)); - let outcomes = - self.solve_partitions(partitions, thread_count, child_config, child_seeds); - - let mut solved_partitions = Vec::with_capacity(outcomes.len()); - for outcome in outcomes { - match outcome { - PartitionOutcome::Complete(partition) => solved_partitions.push(partition), - PartitionOutcome::Pause => { - solver_scope.pause_if_requested(); - continue 'partitioning; - } - PartitionOutcome::Cancelled => { - solver_scope.mark_cancelled(); - return; - } - PartitionOutcome::Terminated => { - solver_scope.mark_terminated_by_config(); - return; - } - PartitionOutcome::ProblemChange => return, - } - } - - if solver_scope.should_terminate() { - return; - } - - let merged = self.partitioner.merge(&solution, solved_partitions); - solver_scope.replace_working_solution_and_reinitialize(merged); - solver_scope.update_best_solution(); - - if self.config.log_progress { - if let Some(score) = solver_scope.best_score() { - tracing::info!( - event = "phase_end", - phase = "PartitionedSearch", - score = %format!("{:?}", score), - ); - } - } - - return; - } + solve_partitioned( + solver_scope, + &self.partitioner, + &self.config, + |_: &D, partition| (self.score_director_factory)(partition), + &|child_scope: &mut SolverScope<'_, S, PD>| { + (self.phase_factory)().solve_all(child_scope); + }, + ); } fn phase_type_name(&self) -> &'static str { @@ -211,88 +140,6 @@ where } } -impl PartitionedSearchPhase -where - S: PlanningSolution, - PD: Director, - Part: SolutionPartitioner, - SDF: Fn(S) -> PD + Send + Sync, - PF: Fn() -> CP + Send + Sync, - CP: ChildPhases, -{ - /// Solves a single partition and returns the solved solution. - fn solve_partition<'t>( - &self, - partition: S, - child_config: SolverScopeChildConfig<'t, S>, - seed: u64, - ) -> PartitionOutcome { - // Create score director for this partition - let director = (self.score_director_factory)(partition); - - // Create solver scope - let mut solver_scope = child_config.build_scope(director, seed); - if solver_scope.should_terminate() { - return PartitionOutcome::Terminated; - } - solver_scope.initialize_working_solution_as_best(); - - // Create and run child phases - let mut phases = (self.phase_factory)(); - phases.solve_all(&mut solver_scope); - - match solver_scope.pending_control() { - PendingControl::PauseRequested => return PartitionOutcome::Pause, - PendingControl::CancelRequested => return PartitionOutcome::Cancelled, - PendingControl::ConfigTerminationRequested => return PartitionOutcome::Terminated, - PendingControl::ProblemChangeRequested => return PartitionOutcome::ProblemChange, - PendingControl::Continue => {} - } - if solver_scope.yielded_to_parent() { - return PartitionOutcome::Pause; - } - match solver_scope.terminal_reason() { - SolverTerminalReason::Cancelled => return PartitionOutcome::Cancelled, - SolverTerminalReason::TerminatedByConfig => return PartitionOutcome::Terminated, - SolverTerminalReason::Completed | SolverTerminalReason::Failed => {} - } - - PartitionOutcome::Complete(solver_scope.take_best_or_working_solution()) - } - - fn solve_partitions<'t>( - &self, - partitions: Vec, - thread_count: usize, - child_config: SolverScopeChildConfig<'t, S>, - child_seeds: Vec, - ) -> Vec> { - if thread_count <= 1 || partitions.len() <= 1 { - return partitions - .into_iter() - .zip(child_seeds) - .map(|(partition, seed)| { - self.solve_partition(partition, child_config.clone(), seed) - }) - .collect(); - } - - ThreadPoolBuilder::new() - .num_threads(thread_count) - .build() - .expect("failed to build partitioned search rayon pool") - .install(|| { - partitions - .into_par_iter() - .zip(child_seeds.into_par_iter()) - .map(|(partition, seed)| { - self.solve_partition(partition, child_config.clone(), seed) - }) - .collect() - }) - } -} - #[cfg(test)] #[path = "phase_tests.rs"] mod tests; diff --git a/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs b/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs index 676cf44b..68e74fc3 100644 --- a/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs +++ b/crates/solverforge-solver/src/phase/partitioned/phase_tests/limits.rs @@ -1,4 +1,5 @@ use super::*; +use crate::manager::SolverTerminalReason; #[test] fn sequential_partitioned_search_shares_step_limit_across_children() { From 11a406913ce633e890051c0611372e2cb9ca7881 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Thu, 5 Nov 2026 04:50:59 +0100 Subject: [PATCH 3/4] feat(solver)!: run partitioned_search in the framework A `partitioned_search` phase only looked up a user closure registered with `partitioned_phase` and ran whatever phase it built, so `child_phases` was validated and never run, and `thread_count` and `log_progress` took effect only if the closure forwarded them. The framework now runs the phase. A search declaration registers just the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`; `partitioner = "name"` selects it. Each partition is solved by a runner compiled from the parent configuration with `child_phases` as its phases, an empty list meaning the default phases, over a director forked from the solve's own with `Director::fork_for_solution`, on `thread_count` threads, with `log_progress` logging the pass. The graph compiler compiles every child configuration up front, so a child phase that cannot compile fails the solve with its `phases[i].partitioned_search.child_phases[j]` path. A child runner borrows its parent's declaration, so a partitioned phase nested in `child_phases` compiles to the same runner type, and extension registries are `Send + Sync` because partition runners compile on the threads that solve them. BREAKING CHANGE: `SearchBuilder::partitioned_phase` is removed. Register a `SolutionPartitioner` with `SearchBuilder::partitioner` instead; the framework builds and runs the phase from the `partitioned_search` configuration. --- Cargo.lock | 2 + crates/solverforge-config/WIREFRAME.md | 6 +- crates/solverforge-config/src/phase.rs | 6 +- crates/solverforge-solver/WIREFRAME.md | 9 +- crates/solverforge-solver/src/bench.rs | 11 +- .../solverforge-solver/src/builder/search.rs | 30 +-- .../src/builder/search/custom.rs | 113 +++--------- .../src/builder/search/partitioner.rs | 146 +++++++++++++++ .../src/builder/search/tests.rs | 28 ++- .../src/phase/partitioned/execution.rs | 5 +- crates/solverforge-solver/src/run.rs | 4 +- .../src/runtime/compiler/compile.rs | 55 +++++- .../src/runtime/compiler/executor/mod.rs | 1 + .../runtime/compiler/executor/partitioned.rs | 130 +++++++++++++ .../src/runtime/compiler/executor/prepared.rs | 41 +++-- .../compiler/executor/prepared/tests.rs | 8 +- .../src/runtime/compiler/executor/runner.rs | 125 ++++--------- .../runtime/compiler/executor/runner/bench.rs | 4 +- .../compiler/executor/runner/failure.rs | 2 +- .../compiler/executor/runner/phase_plan.rs | 76 ++++++++ .../executor/runner/problem_change.rs | 13 +- .../src/runtime/compiler/extension_tests.rs | 43 ++++- .../src/runtime/compiler/graph.rs | 34 ++-- .../src/runtime/compiler/input.rs | 47 ++++- .../src/runtime/compiler/mod.rs | 4 +- .../src/runtime/compiler/partitioned.rs | 33 ++++ .../src/runtime/compiler/tests.rs | 24 ++- crates/solverforge/Cargo.toml | 2 + .../solverforge/tests/partitioned_search.rs | 123 +++++++++++++ .../tests/partitioned_search/domain/mod.rs | 11 ++ .../tests/partitioned_search/domain/plan.rs | 153 ++++++++++++++++ .../partitioned_search/domain/resource.rs | 7 + .../tests/partitioned_search/domain/task.rs | 10 + .../tests/partitioned_search_log_progress.rs | 173 ++++++++++++++++++ docs/extend-solver.md | 31 ++++ 35 files changed, 1257 insertions(+), 253 deletions(-) create mode 100644 crates/solverforge-solver/src/builder/search/partitioner.rs create mode 100644 crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs create mode 100644 crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs create mode 100644 crates/solverforge-solver/src/runtime/compiler/partitioned.rs create mode 100644 crates/solverforge/tests/partitioned_search.rs create mode 100644 crates/solverforge/tests/partitioned_search/domain/mod.rs create mode 100644 crates/solverforge/tests/partitioned_search/domain/plan.rs create mode 100644 crates/solverforge/tests/partitioned_search/domain/resource.rs create mode 100644 crates/solverforge/tests/partitioned_search/domain/task.rs create mode 100644 crates/solverforge/tests/partitioned_search_log_progress.rs diff --git a/Cargo.lock b/Cargo.lock index 84ef0c98..ef596522 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -439,6 +439,7 @@ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" name = "solverforge" version = "0.24.0" dependencies = [ + "rayon", "serde", "solverforge-config", "solverforge-console", @@ -448,6 +449,7 @@ dependencies = [ "solverforge-scoring", "solverforge-solver", "toml", + "tracing", ] [[package]] diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index 55014750..d0d9e432 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -692,10 +692,10 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`. | Field | Type | Default | |-------|------|---------| -| `partitioner` | `Option` | `None` | +| `partitioner` | `Option` | `None`; required: the name registered with `SearchBuilder::partitioner` | | `thread_count` | `MoveThreadCount` | `Auto` | -| `log_progress` | `bool` | `false` | -| `child_phases` | `Vec` | `[]` | +| `log_progress` | `bool` | `false`; logs the phase's start and end | +| `child_phases` | `Vec` | `[]`; the phases each partition is solved with, compiled like `phases`; empty runs the default phases | | `termination` | `Option` | `None` | ### `CustomPhaseConfig` diff --git a/crates/solverforge-config/src/phase.rs b/crates/solverforge-config/src/phase.rs index 50704344..011f13b3 100644 --- a/crates/solverforge-config/src/phase.rs +++ b/crates/solverforge-config/src/phase.rs @@ -193,7 +193,8 @@ pub struct LocalSearchConfig { #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "snake_case", deny_unknown_fields)] pub struct PartitionedSearchConfig { - /// Compile-time registered partitioner name. + /// Name of the partitioner the search declaration registered with + /// `SearchBuilder::partitioner`. pub partitioner: Option, /// Threads solving the partitions: `auto` runs one per partition up to the @@ -205,7 +206,8 @@ pub struct PartitionedSearchConfig { #[serde(default)] pub log_progress: bool, - /// Optional child phase list to run inside each partition. + /// The phases each partition is solved with, compiled like the solver's + /// `phases`; empty runs the default phases. #[serde(default)] pub child_phases: Vec, diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 1d9664f2..221bf07e 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -32,8 +32,11 @@ src/ ├── runtime.rs — List-variable metadata plus the sole immutable compiled runtime-graph entrypoint ├── runtime/compiler/ — Immutable runtime-graph compiler, prepared runner, default policy, and executor kernels; every reached source-backed construction boundary validates stable element keys against the frozen declared stream before deciding whether work remains ├── runtime/compiler/executor/completion.rs — Structural mandatory-work gate and deferred best-solution publication +├── runtime/compiler/executor/partitioned.rs — The configured `partitioned_search` phase: registered partitioner, one child runner per partition +├── runtime/compiler/partitioned.rs — The solver configuration a partition is solved with ├── runtime/compiler/executor/runner/bench.rs — Moves a prepared runner's first lowered local search or scalar construction out for the `__bench` handles ├── runtime/compiler/executor/runner/failure.rs — Cold propagation of configured-runtime execution failures to the public run boundary +├── runtime/compiler/executor/runner/phase_plan.rs — A runner phase's index and its candidate-trace plan with the reached outcome ├── runtime/compiler/executor/runner/problem_change.rs — Problem-change pass loop and per-pass runner state reset ├── runtime/provider_cursor.rs — One lazy compound-provider cursor; static Rust providers retain typed candidates/function pointers, while host callbacks alone use raw named edits and object-safe dispatch ├── model_support.rs — Hidden `PlanningModelSupport` bridge implemented by `planning_model!` for model-owned scalar hook attachment, scalar group attachment, model/solution validation, and shadow updates @@ -72,7 +75,7 @@ src/ │ ├── context/scalar/*.rs — Scalar value-source, variable, and group binding definitions │ ├── context/scalar/group/*.rs — Assignment and member binding chunks │ ├── search.rs — Typed custom-search surface: SearchContext, Search, CustomSearchPhase, local_search(), and typed custom phase registration -│ ├── search/*.rs — Recursive typed custom-extension registry +│ ├── search/*.rs — Recursive typed extension registry: custom phases (`custom.rs`) and partitioners (`partitioner.rs`) │ ├── selector.rs — Internal grouped-scalar leaf and indexed compiled-selector composition root │ ├── selector/grouped_scalar.rs — GroupedScalarSelector used as one compiled runtime leaf │ ├── selector/types/composite.rs — Indexed Limited/union/cartesian declaration arena with stable node IDs @@ -303,7 +306,7 @@ src/ │ │ ├── mod.rs — Partitioned module declarations and re-exports │ │ ├── child_phases.rs — ChildPhases trait and tuple impls │ │ ├── config.rs — PartitionedSearchConfig -│ │ ├── execution.rs — One partition/solve/merge pass run by PartitionedSearchPhase +│ │ ├── execution.rs — One partition/solve/merge pass shared by PartitionedSearchPhase and the configured runtime │ │ ├── partitioner.rs — SolutionPartitioner trait, FunctionalPartitioner, ThreadCount │ │ ├── partitioner_tests.rs — Tests │ │ ├── phase.rs — PartitionedSearchPhase @@ -718,6 +721,8 @@ working solution without cloning. **`ThreadCount`** — `Auto` (one thread per partition, at most one per available core), `Unlimited` (one per available core), `Specific(NonZeroUsize)` (at most that many, at most one per partition). `PartitionedSearchPhase` solves child partitions sequentially when the resolved count is `1`, otherwise it installs a dedicated Rayon pool whose worker count matches the resolved value. +**Configured `partitioned_search`** — The framework runs it; a search declaration only registers the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`, in a namespace separate from custom phase names. `partitioner = "name"` selects it. Each partition gets a director from `Director::fork_for_solution` over the partition and a `CompiledRuntimePhaseRunner` compiled from `partition_child_config`: the parent configuration with `child_phases` as its phases (empty means the default phases) and, as termination, only the parent's time and step count limits, the bounds that reach a partition. The graph compiler compiles that child configuration once up front, so a child phase error fails the solve with a `phases[i].partitioned_search.child_phases[j]` path. `thread_count` and `log_progress` apply as for `PartitionedSearchPhase` (`log_progress` logs `phase_start` with `partition_count` and `thread_count`, and `phase_end`). A child runner borrows its parent's `RuntimeGraphInput`, so nested partitioned phases compile to the same runner type. The `RuntimeExtensionRegistry` is `Send + Sync` for that reason: partition runners compile on the threads that solve them. + ## Scope Hierarchy ### `ProgressCallback` — `scope/solver.rs` diff --git a/crates/solverforge-solver/src/bench.rs b/crates/solverforge-solver/src/bench.rs index eb8715bc..dc73381f 100644 --- a/crates/solverforge-solver/src/bench.rs +++ b/crates/solverforge-solver/src/bench.rs @@ -20,7 +20,7 @@ use solverforge_core::domain::PlanningSolution; use solverforge_core::score::{ParseableScore, Score}; use solverforge_scoring::Director; -use crate::builder::search::custom::{NoRuntimeExtensionPhase, NoTypedExtensions}; +use crate::builder::search::custom::NoTypedExtensions; use crate::builder::SearchContext; use crate::heuristic::r#move::Move; use crate::heuristic::selector::move_selector::MoveCandidateRef; @@ -28,6 +28,7 @@ use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; use crate::phase::Phase; use crate::run::compile_runtime_runner; use crate::runtime::compiler::executor::CompiledRuntimePhaseRunner; +use crate::runtime::compiler::RuntimeGraphInput; use crate::runtime_build_error::RuntimeBuildResult; use crate::scope::{ProgressCallback, SolverScope}; use crate::stats::CandidateTracePhasePlan; @@ -57,7 +58,13 @@ where DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, { - runner: CompiledRuntimePhaseRunner, + runner: CompiledRuntimePhaseRunner< + S, + V, + DM, + IDM, + RuntimeGraphInput, + >, } impl CompiledRuntimeRunner diff --git a/crates/solverforge-solver/src/builder/search.rs b/crates/solverforge-solver/src/builder/search.rs index efb09fab..eae4bd89 100644 --- a/crates/solverforge-solver/src/builder/search.rs +++ b/crates/solverforge-solver/src/builder/search.rs @@ -14,11 +14,13 @@ use crate::RuntimeBuildResult; use super::RuntimeModel; pub(crate) mod custom; +pub(crate) mod partitioner; pub(crate) use custom::{ - CustomPhaseNode, CustomSearchPhase, NoTypedExtensions, PartitionedPhaseNode, - RuntimeExtensionPolicy, RuntimeExtensionRegistry, + CustomPhaseNode, CustomSearchPhase, NoTypedExtensions, RuntimeExtensionPolicy, + RuntimeExtensionRegistry, }; +pub(crate) use partitioner::PartitionerNode; /// A model bound to its solution descriptor plus the solve's random seed: /// the input custom phases and the configured runtime build from. @@ -148,7 +150,7 @@ where P: CustomSearchPhase + 'static, { assert!( - !self.extensions.contains_custom(name) && !self.extensions.contains_partitioned(name), + !self.extensions.contains_custom(name), "custom phase `{name}` was registered more than once", ); SearchBuilder { @@ -157,25 +159,27 @@ where } } - pub fn partitioned_phase( + /// Registers the partitioner a `partitioned_search` phase selects with + /// `partitioner = "name"`. The framework runs the phase: it splits the + /// working solution with the partitioner, solves each partition with the + /// phase's `child_phases` on `thread_count` threads, and merges the + /// solved partitions back. + pub fn partitioner( self, name: &'static str, builder: F, - ) -> SearchBuilder> + ) -> SearchBuilder> where - F: Fn(&SearchContext, &solverforge_config::PartitionedSearchConfig) -> P - + Send - + Sync - + 'static, - P: CustomSearchPhase + 'static, + F: Fn(&SearchContext) -> P + Send + Sync + 'static, + P: crate::phase::partitioned::SolutionPartitioner + 'static, { assert!( - !self.extensions.contains_custom(name) && !self.extensions.contains_partitioned(name), - "partitioned_search partitioner `{name}` was registered more than once", + !self.extensions.contains_partitioner(name), + "partitioner `{name}` was registered more than once", ); SearchBuilder { context: self.context, - extensions: PartitionedPhaseNode::new(self.extensions, name, builder), + extensions: PartitionerNode::new(self.extensions, name, builder), } } } diff --git a/crates/solverforge-solver/src/builder/search/custom.rs b/crates/solverforge-solver/src/builder/search/custom.rs index 8d8c4cf0..b48158c0 100644 --- a/crates/solverforge-solver/src/builder/search/custom.rs +++ b/crates/solverforge-solver/src/builder/search/custom.rs @@ -1,7 +1,6 @@ use std::fmt::{self, Debug}; use std::marker::PhantomData; -use solverforge_config::PartitionedSearchConfig; use solverforge_core::domain::PlanningSolution; use solverforge_scoring::Director; @@ -12,6 +11,7 @@ use crate::phase::partitioned::{ChildPhases, PartitionedSearchPhase, SolutionPar use crate::phase::Phase; use crate::scope::{ProgressCallback, SolverScope}; +use super::partitioner::NoPartitioner; use super::SearchContext; /// A user-defined phase registered on a search declaration by name and run @@ -132,12 +132,17 @@ pub enum RuntimeExtensionPolicy { /// Compilation consults only the registration predicates. Instantiation is /// deferred to the graph executor, which creates fresh concrete phases from /// its frozen [`SearchContext`] once for each solve. -pub trait RuntimeExtensionRegistry +/// Registries are `Send + Sync`: a partitioned phase compiles each +/// partition's runner from the registry on the thread that solves it. +pub trait RuntimeExtensionRegistry: Send + Sync where S: PlanningSolution, { type Phase: CustomSearchPhase; + /// The registered partitioners, one concrete type for the whole registry. + type Partitioner: SolutionPartitioner; + fn policy(&self) -> RuntimeExtensionPolicy; fn contains_custom(&self, name: &str) -> bool; @@ -148,14 +153,13 @@ where context: &SearchContext, ) -> Option; - fn contains_partitioned(&self, name: &str) -> bool; + fn contains_partitioner(&self, name: &str) -> bool; - fn instantiate_partitioned( + fn instantiate_partitioner( &self, name: &str, - config: &PartitionedSearchConfig, context: &SearchContext, - ) -> Option; + ) -> Option; } pub struct NoTypedExtensions; @@ -165,6 +169,7 @@ where S: PlanningSolution, { type Phase = NoRuntimeExtensionPhase; + type Partitioner = NoPartitioner; fn policy(&self) -> RuntimeExtensionPolicy { RuntimeExtensionPolicy::Typed @@ -182,16 +187,15 @@ where None } - fn contains_partitioned(&self, _name: &str) -> bool { + fn contains_partitioner(&self, _name: &str) -> bool { false } - fn instantiate_partitioned( + fn instantiate_partitioner( &self, _name: &str, - _config: &PartitionedSearchConfig, _context: &SearchContext, - ) -> Option { + ) -> Option { None } } @@ -207,6 +211,7 @@ where S: PlanningSolution, { type Phase = NoRuntimeExtensionPhase; + type Partitioner = NoPartitioner; fn policy(&self) -> RuntimeExtensionPolicy { RuntimeExtensionPolicy::Dynamic @@ -224,16 +229,15 @@ where None } - fn contains_partitioned(&self, _name: &str) -> bool { + fn contains_partitioner(&self, _name: &str) -> bool { false } - fn instantiate_partitioned( + fn instantiate_partitioner( &self, _name: &str, - _config: &PartitionedSearchConfig, _context: &SearchContext, - ) -> Option { + ) -> Option { None } } @@ -286,24 +290,6 @@ pub struct CustomPhaseNode { _marker: PhantomData Phase>, } -pub struct PartitionedPhaseNode { - previous: Previous, - name: &'static str, - builder: Builder, - _marker: PhantomData Phase>, -} - -impl PartitionedPhaseNode { - pub fn new(previous: Previous, name: &'static str, builder: Builder) -> Self { - Self { - previous, - name, - builder, - _marker: PhantomData, - } - } -} - impl CustomPhaseNode { pub fn new(previous: Previous, name: &'static str, builder: Builder) -> Self { Self { @@ -401,10 +387,11 @@ impl RuntimeExtensionRegistry, - Builder: Fn(&SearchContext) -> CurrentPhase, + Builder: Fn(&SearchContext) -> CurrentPhase + Send + Sync, CurrentPhase: CustomSearchPhase, { type Phase = CustomPhaseUnion; + type Partitioner = Previous::Partitioner; fn policy(&self) -> RuntimeExtensionPolicy { self.previous.policy() @@ -427,65 +414,15 @@ where .map(CustomPhaseUnion::Previous) } - fn contains_partitioned(&self, name: &str) -> bool { - self.previous.contains_partitioned(name) + fn contains_partitioner(&self, name: &str) -> bool { + self.previous.contains_partitioner(name) } - fn instantiate_partitioned( + fn instantiate_partitioner( &self, name: &str, - config: &PartitionedSearchConfig, context: &SearchContext, - ) -> Option { - self.previous - .instantiate_partitioned(name, config, context) - .map(CustomPhaseUnion::Previous) - } -} - -impl RuntimeExtensionRegistry - for PartitionedPhaseNode -where - S: PlanningSolution, - Previous: RuntimeExtensionRegistry, - Builder: Fn(&SearchContext, &PartitionedSearchConfig) -> CurrentPhase, - CurrentPhase: CustomSearchPhase, -{ - type Phase = CustomPhaseUnion; - - fn policy(&self) -> RuntimeExtensionPolicy { - self.previous.policy() - } - - fn contains_custom(&self, name: &str) -> bool { - self.previous.contains_custom(name) - } - - fn instantiate_custom( - &self, - name: &str, - context: &SearchContext, - ) -> Option { - self.previous - .instantiate_custom(name, context) - .map(CustomPhaseUnion::Previous) - } - - fn contains_partitioned(&self, name: &str) -> bool { - self.name == name || self.previous.contains_partitioned(name) - } - - fn instantiate_partitioned( - &self, - name: &str, - config: &PartitionedSearchConfig, - context: &SearchContext, - ) -> Option { - if self.name == name { - return Some(CustomPhaseUnion::Current((self.builder)(context, config))); - } - self.previous - .instantiate_partitioned(name, config, context) - .map(CustomPhaseUnion::Previous) + ) -> Option { + self.previous.instantiate_partitioner(name, context) } } diff --git a/crates/solverforge-solver/src/builder/search/partitioner.rs b/crates/solverforge-solver/src/builder/search/partitioner.rs new file mode 100644 index 00000000..f4aa0c86 --- /dev/null +++ b/crates/solverforge-solver/src/builder/search/partitioner.rs @@ -0,0 +1,146 @@ +//! Partitioners registered on a search declaration by name, for the +//! framework's `partitioned_search` phase. + +use std::fmt::{self, Debug}; +use std::marker::PhantomData; + +use solverforge_core::domain::PlanningSolution; + +use crate::phase::partitioned::SolutionPartitioner; + +use super::custom::{RuntimeExtensionPolicy, RuntimeExtensionRegistry}; +use super::SearchContext; + +/// The partitioner of a registry with none registered. +#[derive(Clone, Copy)] +pub enum NoPartitioner {} + +impl Debug for NoPartitioner { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self {} + } +} + +impl SolutionPartitioner for NoPartitioner { + fn partition(&self, _solution: &S) -> Vec { + match *self {} + } + + fn merge(&self, _original: &S, _partitions: Vec) -> S { + match *self {} + } +} + +/// One registered partitioner: `builder` makes it from the solve's +/// [`SearchContext`] when a `partitioned_search` phase names it. +pub struct PartitionerNode { + previous: Previous, + name: &'static str, + builder: Builder, + _marker: PhantomData Partitioner>, +} + +impl PartitionerNode { + pub fn new(previous: Previous, name: &'static str, builder: Builder) -> Self { + Self { + previous, + name, + builder, + _marker: PhantomData, + } + } +} + +/// Either a previously registered partitioner or the current one. +pub enum PartitionerUnion { + Previous(Previous), + Current(Current), +} + +impl Debug for PartitionerUnion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Previous(partitioner) => f + .debug_tuple("Partitioner::Previous") + .field(partitioner) + .finish(), + Self::Current(partitioner) => f + .debug_tuple("Partitioner::Current") + .field(partitioner) + .finish(), + } + } +} + +impl SolutionPartitioner for PartitionerUnion +where + S: PlanningSolution, + Previous: SolutionPartitioner, + Current: SolutionPartitioner, +{ + fn partition(&self, solution: &S) -> Vec { + match self { + Self::Previous(partitioner) => partitioner.partition(solution), + Self::Current(partitioner) => partitioner.partition(solution), + } + } + + fn merge(&self, original: &S, partitions: Vec) -> S { + match self { + Self::Previous(partitioner) => partitioner.merge(original, partitions), + Self::Current(partitioner) => partitioner.merge(original, partitions), + } + } + + fn recommended_partition_count(&self) -> Option { + match self { + Self::Previous(partitioner) => partitioner.recommended_partition_count(), + Self::Current(partitioner) => partitioner.recommended_partition_count(), + } + } +} + +impl RuntimeExtensionRegistry + for PartitionerNode +where + S: PlanningSolution, + Previous: RuntimeExtensionRegistry, + Builder: Fn(&SearchContext) -> Current + Send + Sync, + Current: SolutionPartitioner, +{ + type Phase = Previous::Phase; + type Partitioner = PartitionerUnion; + + fn policy(&self) -> RuntimeExtensionPolicy { + self.previous.policy() + } + + fn contains_custom(&self, name: &str) -> bool { + self.previous.contains_custom(name) + } + + fn instantiate_custom( + &self, + name: &str, + context: &SearchContext, + ) -> Option { + self.previous.instantiate_custom(name, context) + } + + fn contains_partitioner(&self, name: &str) -> bool { + self.name == name || self.previous.contains_partitioner(name) + } + + fn instantiate_partitioner( + &self, + name: &str, + context: &SearchContext, + ) -> Option { + if self.name == name { + return Some(PartitionerUnion::Current((self.builder)(context))); + } + self.previous + .instantiate_partitioner(name, context) + .map(PartitionerUnion::Previous) + } +} diff --git a/crates/solverforge-solver/src/builder/search/tests.rs b/crates/solverforge-solver/src/builder/search/tests.rs index 73266ed0..6ab4cc48 100644 --- a/crates/solverforge-solver/src/builder/search/tests.rs +++ b/crates/solverforge-solver/src/builder/search/tests.rs @@ -195,13 +195,37 @@ fn search_builder_transfers_only_declaration_parts() { let search = search_context() .defaults() .phase("weekend_repair", |_| MarkerPhase("weekend_repair")) - .partitioned_phase("by_task", |_context, _config| MarkerPhase("by_task")); + .partitioner("by_task", |_context| MarkerPartitioner); let (context, extensions) = search.into_runtime_parts(); assert_eq!(context.seed(), Some(7)); assert!(extensions.contains_custom("weekend_repair")); - assert!(extensions.contains_partitioned("by_task")); + assert!(extensions.contains_partitioner("by_task")); + assert!(!extensions.contains_custom("by_task")); + assert!(!extensions.contains_partitioner("weekend_repair")); +} + +#[derive(Debug)] +struct MarkerPartitioner; + +impl crate::phase::partitioned::SolutionPartitioner for MarkerPartitioner { + fn partition(&self, solution: &S) -> Vec { + vec![solution.clone()] + } + + fn merge(&self, original: &S, _partitions: Vec) -> S { + original.clone() + } +} + +#[test] +#[should_panic(expected = "partitioner `by_task` was registered more than once")] +fn search_rejects_duplicate_partitioner_names() { + let _ = search_context() + .defaults() + .partitioner("by_task", |_| MarkerPartitioner) + .partitioner("by_task", |_| MarkerPartitioner); } #[test] diff --git a/crates/solverforge-solver/src/phase/partitioned/execution.rs b/crates/solverforge-solver/src/phase/partitioned/execution.rs index 8e3435fe..8603e217 100644 --- a/crates/solverforge-solver/src/phase/partitioned/execution.rs +++ b/crates/solverforge-solver/src/phase/partitioned/execution.rs @@ -1,6 +1,7 @@ //! One partitioned-search pass: split the working solution, solve each -//! partition in its own child scope, merge. Run by -//! [`super::PartitionedSearchPhase`]. +//! partition in its own child scope, merge. Shared by +//! [`super::PartitionedSearchPhase`] and the configured runtime's +//! `partitioned_search` phase. use rand::RngExt; use rayon::prelude::*; diff --git a/crates/solverforge-solver/src/run.rs b/crates/solverforge-solver/src/run.rs index 85421944..a62c5975 100644 --- a/crates/solverforge-solver/src/run.rs +++ b/crates/solverforge-solver/src/run.rs @@ -244,7 +244,9 @@ pub(crate) fn compile_runtime_runner( config: &SolverConfig, context: SearchContext, extensions: Registry, -) -> RuntimeBuildResult> +) -> RuntimeBuildResult< + CompiledRuntimePhaseRunner>, +> where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score + Copy + Ord + ParseableScore, diff --git a/crates/solverforge-solver/src/runtime/compiler/compile.rs b/crates/solverforge-solver/src/runtime/compiler/compile.rs index 2e237d86..40de8fe0 100644 --- a/crates/solverforge-solver/src/runtime/compiler/compile.rs +++ b/crates/solverforge-solver/src/runtime/compiler/compile.rs @@ -8,8 +8,9 @@ use super::construction::compile_construction; use super::default_local_search::DefaultLocalSearchPlan; use super::defaults::compile_default_runtime_bindings; use super::graph::{CompiledRuntimeExtension, CompiledRuntimeGraph, CompiledRuntimePhase}; -use super::input::RuntimeGraphInput; +use super::input::{RuntimeGraphInput, RuntimeSource}; use super::local_search::compile_local_search; +use super::partitioned::partition_child_config; use super::score_limits::validate_best_score_limits; use super::selector_values::validate_selector_values; use super::types::{RuntimeCompileError, RuntimeCompileErrorKind, RuntimeExtensionKind}; @@ -18,21 +19,22 @@ use super::types::{RuntimeCompileError, RuntimeCompileErrorKind, RuntimeExtensio /// /// This is intentionally side-effect free: no solution import, host callback, /// selector cursor, score calculation, random draw, or trace work occurs here. -pub(crate) fn compile_runtime_graph( +pub(crate) fn compile_runtime_graph( config: &SolverConfig, - input: RuntimeGraphInput, -) -> Result, RuntimeCompileError> + source: H, +) -> Result, RuntimeCompileError> where S: PlanningSolution + 'static, S::Score: ParseableScore, V: Clone, DM: Clone, IDM: Clone, - E: RuntimeExtensionRegistry, + H: RuntimeSource, { validate_best_score_limits::(config)?; validate_selector_values(config)?; - let (context, extensions) = input.into_parts(); + let context = source.input().context(); + let extensions = source.input().extensions(); if context.seed() != config.resolved_random_seed() { return Err(RuntimeCompileError { path: "runtime_extension_context.random_seed".to_string(), @@ -74,22 +76,55 @@ where &format!("phases[{index}]"), context.descriptor(), context.model(), - &extensions, + extensions, default_bindings.local_search_plan.as_ref(), ) }) .collect::, _>>()? }; + validate_partition_children(config, source.input())?; Ok(CompiledRuntimeGraph { - context, - extensions, + source, config: config.clone(), + _model: std::marker::PhantomData, default_bindings, phases, }) } +/// Compiles each partitioned phase's child configuration exactly as a +/// partition's solve will, so a child phase that cannot compile fails here, +/// with its path under the partitioned phase, instead of inside a partition. +fn validate_partition_children( + config: &SolverConfig, + input: &RuntimeGraphInput, +) -> Result<(), RuntimeCompileError> +where + S: PlanningSolution + 'static, + S::Score: ParseableScore, + V: Clone, + DM: Clone, + IDM: Clone, + E: RuntimeExtensionRegistry, +{ + for (index, phase) in config.phases.iter().enumerate() { + let PhaseConfig::PartitionedSearch(partitioned) = phase else { + continue; + }; + compile_runtime_graph(&partition_child_config(config, partitioned), input).map_err( + |error| RuntimeCompileError { + path: match error.path.strip_prefix("phases") { + Some(rest) => format!("phases[{index}].partitioned_search.child_phases{rest}"), + None => format!("phases[{index}].partitioned_search.{}", error.path), + }, + kind: error.kind, + }, + )?; + } + Ok(()) +} + pub(super) fn compile_phase( phase: &PhaseConfig, path: &str, @@ -190,7 +225,7 @@ where }, )); } - if !extensions.contains_partitioned(name) { + if !extensions.contains_partitioner(name) { return Err(extension_error( path, RuntimeCompileErrorKind::UnregisteredTypedPartitioner { diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/mod.rs b/crates/solverforge-solver/src/runtime/compiler/executor/mod.rs index 924c4034..5aed3fcf 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/mod.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/mod.rs @@ -9,6 +9,7 @@ mod execution_record; pub(crate) mod list_construction; mod list_leaf; pub(crate) mod local_search; +mod partitioned; mod prepared; mod runner; mod trace; diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs b/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs new file mode 100644 index 00000000..7cfffa81 --- /dev/null +++ b/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs @@ -0,0 +1,130 @@ +//! The configured runtime's `partitioned_search` phase: the registered +//! partitioner splits the working solution, each partition is solved by a +//! runner compiled from the phase's child configuration, and the solved +//! partitions are merged back. + +use std::fmt::Debug; + +use solverforge_config::SolverConfig; +use solverforge_core::domain::PlanningSolution; +use solverforge_core::score::{ParseableScore, Score}; +use solverforge_scoring::Director; + +use crate::builder::RuntimeExtensionRegistry; +use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; +use crate::phase::partitioned::config::PartitionedSearchConfig; +use crate::phase::partitioned::execution::solve_partitioned; +use crate::phase::Phase; +use crate::runtime::compiler::{ + compile_runtime_graph, partition_child_config, RuntimeGraphInput, RuntimeSource, +}; +use crate::runtime_build_error::RuntimeBuildError; +use crate::scope::{ProgressCallback, SolverScope}; + +use super::runner::panic_runtime_execution_error; +use super::{CompiledRuntimeExecutor, CompiledRuntimePhaseRunner}; + +/// One instantiated extension phase of a compiled runner. +#[expect( + clippy::large_enum_variant, + reason = "prepared phases remain value-owned without execution-time indirection" +)] +pub(crate) enum RuntimeExtensionInstance { + /// A registered custom phase. + Custom(Phase), + /// A `partitioned_search` phase with its registered partitioner. + Partitioned(PartitionedInstance), +} + +/// The extension instance type of a runner over source `H`. +pub(crate) type SourceExtension = + RuntimeExtensionInstance< + <>::Extensions as RuntimeExtensionRegistry< + S, + V, + DM, + IDM, + >>::Phase, + <>::Extensions as RuntimeExtensionRegistry< + S, + V, + DM, + IDM, + >>::Partitioner, + >; + +/// A `partitioned_search` phase instantiated for one solve. +pub(crate) struct PartitionedInstance { + partitioner: Partitioner, + config: PartitionedSearchConfig, + /// The configuration each partition is solved with. + child_config: SolverConfig, +} + +impl PartitionedInstance { + pub(crate) fn new( + partitioner: Partitioner, + config: &solverforge_config::PartitionedSearchConfig, + parent: &SolverConfig, + ) -> Self { + Self { + partitioner, + config: PartitionedSearchConfig::from_serialized(config), + child_config: partition_child_config(parent, config), + } + } +} + +impl Debug for PartitionedInstance { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PartitionedInstance") + .field("partitioner", &self.partitioner) + .field("config", &self.config) + .finish_non_exhaustive() + } +} + +/// Runs one partitioned phase. Each partition gets a director forked from +/// the solve's own director over the partition and a runner compiled from +/// the child configuration over the parent's declaration; the compilation +/// cannot fail here because the graph compiler already compiled the same +/// child configuration. +pub(super) fn solve_partitioned_instance( + instance: &PartitionedInstance, + input: &RuntimeGraphInput, + solver_scope: &mut SolverScope<'_, S, D, ProgressCb>, +) where + S: PlanningSolution + Clone + Send + Sync + 'static, + S::Score: Score + Copy + Ord + ParseableScore, + V: Clone + PartialEq + Into + Send + Sync + Debug + 'static, + DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + E: RuntimeExtensionRegistry, + RuntimeGraphInput: Sync, + D: Director, + ProgressCb: ProgressCallback, +{ + let solve_children = |child_scope: &mut SolverScope<'_, S, D>| { + let graph = compile_runtime_graph(&instance.child_config, input).unwrap_or_else(|error| { + let message = error.to_string(); + panic_runtime_execution_error(RuntimeBuildError::Compilation { + path: error.path, + message, + }) + }); + let mut runner = CompiledRuntimePhaseRunner::try_new(CompiledRuntimeExecutor::new(graph)) + .unwrap_or_else(|error| panic_runtime_execution_error(error)); + Phase::solve(&mut runner, child_scope); + }; + solve_partitioned( + solver_scope, + &instance.partitioner, + &instance.config, + |director: &D, partition| { + director.fork_for_solution(partition).expect( + "partitioned search requires a director built with a constraint-set constructor", + ) + }, + &solve_children, + ); +} diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/prepared.rs b/crates/solverforge-solver/src/runtime/compiler/executor/prepared.rs index bc74babc..48801250 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/prepared.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/prepared.rs @@ -11,6 +11,7 @@ use solverforge_core::domain::PlanningSolution; use crate::builder::RuntimeExtensionRegistry; use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; +use crate::runtime::compiler::RuntimeSource; use super::super::graph::{ CompiledConstruction, CompiledRuntimeExtension, CompiledRuntimeGraph, CompiledRuntimePhase, @@ -21,6 +22,8 @@ use crate::builder::context::ListConstructionKernelError; mod types; +use super::partitioned::{PartitionedInstance, RuntimeExtensionInstance, SourceExtension}; + use types::{prepare_construction, PreparedLocalSearchMarker}; pub(crate) use types::{ PreparedConstruction, PreparedDefaultRuntime, PreparedListSlot, PreparedListSourceCatalog, @@ -29,40 +32,40 @@ pub(crate) use types::{ /// One immutable graph plus the concrete extension registry that will be /// instantiated once for each solve. It owns no solution or phase instance. -pub(crate) struct CompiledRuntimeExecutor +pub(crate) struct CompiledRuntimeExecutor where S: PlanningSolution, { - graph: CompiledRuntimeGraph, + graph: CompiledRuntimeGraph, } -impl CompiledRuntimeExecutor +impl CompiledRuntimeExecutor where S: PlanningSolution, { - pub(crate) fn new(graph: CompiledRuntimeGraph) -> Self { + pub(crate) fn new(graph: CompiledRuntimeGraph) -> Self { Self { graph } } - pub(crate) fn graph(&self) -> &CompiledRuntimeGraph { + pub(crate) fn graph(&self) -> &CompiledRuntimeGraph { &self.graph } /// Consumes the executor and yields its immutable graph by ownership. /// The graph is built once per solve; consuming it lets the runner lower /// declarations without cloning slot vectors or provider plans. - pub(crate) fn into_graph(self) -> CompiledRuntimeGraph { + pub(crate) fn into_graph(self) -> CompiledRuntimeGraph { self.graph } } -impl CompiledRuntimeExecutor +impl CompiledRuntimeExecutor where S: PlanningSolution + Clone + Send + Sync + 'static, V: Clone + PartialEq + Send + Sync + fmt::Debug + 'static, DM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter, IDM: Clone + Send + Sync + fmt::Debug + CrossEntityDistanceMeter, - E: RuntimeExtensionRegistry, + H: RuntimeSource, { /// Registers one solve's structural source catalog and eagerly /// instantiates explicit extensions. @@ -73,7 +76,10 @@ where /// skipped, or not-reached stage in terminal trace provenance. pub(crate) fn instantiate( &self, - ) -> Result, RuntimeInstantiationError> { + ) -> Result< + PreparedRuntimeExecution>, + RuntimeInstantiationError, + > { let mut sources = PreparedListSourceRegistry::default(); // Registration is structural only. It deliberately does not enumerate // a declared stream, inspect current assignments, or invoke a host @@ -103,7 +109,10 @@ where phase_index: usize, phase: &CompiledRuntimePhase, sources: &PreparedListSourceRegistry, - ) -> Result, RuntimeInstantiationError> { + ) -> Result< + PreparedRuntimePhase>, + RuntimeInstantiationError, + > { match phase { CompiledRuntimePhase::Construction(construction) => { Ok(PreparedRuntimePhase::Construction( @@ -208,12 +217,13 @@ where &self, phase_index: usize, extension: &CompiledRuntimeExtension, - ) -> Result { + ) -> Result, RuntimeInstantiationError> { match extension { CompiledRuntimeExtension::Custom { name } => self .graph .extensions() .instantiate_custom(name, self.graph.context()) + .map(RuntimeExtensionInstance::Custom) .ok_or_else(|| RuntimeInstantiationError { phase_index, kind: RuntimeInstantiationErrorKind::MissingInstantiatedCustomExtension { @@ -223,7 +233,14 @@ where CompiledRuntimeExtension::Partitioned { name, config } => self .graph .extensions() - .instantiate_partitioned(name, config, self.graph.context()) + .instantiate_partitioner(name, self.graph.context()) + .map(|partitioner| { + RuntimeExtensionInstance::Partitioned(PartitionedInstance::new( + partitioner, + config, + self.graph.config(), + )) + }) .ok_or_else(|| RuntimeInstantiationError { phase_index, kind: RuntimeInstantiationErrorKind::MissingInstantiatedPartitioner { diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs index 11ea7404..c511a554 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/prepared/tests.rs @@ -203,7 +203,13 @@ fn plan(elements: Vec, routes: Vec>) -> Plan { fn executor( config: &SolverConfig, -) -> CompiledRuntimeExecutor { +) -> CompiledRuntimeExecutor< + Plan, + usize, + Meter, + Meter, + RuntimeGraphInput, +> { let context = SearchContext::new(descriptor(), model(), config.resolved_random_seed()) .expect("search context should bind"); let graph = compile_runtime_graph(config, RuntimeGraphInput::new(context, NoDynamicExtensions)) diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs index 643a9caf..582cb5d6 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner.rs @@ -8,6 +8,7 @@ mod bench; mod failure; mod local_search; mod lowering; +mod phase_plan; mod problem_change; use std::fmt::{self, Debug}; @@ -16,9 +17,10 @@ use solverforge_core::domain::PlanningSolution; use solverforge_core::score::{ParseableScore, Score}; use solverforge_scoring::Director; -use crate::builder::{CustomSearchPhase, RuntimeExtensionRegistry}; +use crate::builder::CustomSearchPhase; use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; use crate::phase::Phase; +use crate::runtime::compiler::{RuntimeGraphInput, RuntimeSource}; use crate::runtime::finalize_noop_construction; use crate::runtime_build_error::RuntimeBuildResult; use crate::scope::{ProgressCallback, SolverScope}; @@ -26,13 +28,14 @@ use crate::stats::CandidateTracePhasePlan; use super::completion::{publish_if_mandatory_complete, require_mandatory_completion}; use super::local_search::ProviderExecutionResources; -use super::trace::{default_construction_plan, phase_with_outcome}; +use super::partitioned::{solve_partitioned_instance, RuntimeExtensionInstance, SourceExtension}; use super::{ CompiledRuntimeExecutor, ConstructionExecution, DefaultRuntimeConstructionExecution, PreparedRuntimeExecution, PreparedRuntimePhase, }; use crate::runtime::compiler::DefaultRuntimeBindings; -use failure::{map_preparation_error, panic_execution_error, panic_runtime_execution_error}; +pub(crate) use failure::panic_runtime_execution_error; +use failure::{map_preparation_error, panic_execution_error}; use local_search::RuntimeLocalSearch; use lowering::lower_runner_phase; @@ -42,16 +45,20 @@ pub(crate) use failure::take_runtime_execution_failure; /// One retained per-solve executor. A public configured entrypoint creates it /// after graph compilation/preparation and hands it to the ordinary solver as /// a single `Phase`; pause and resume happen inside that same object. -pub(crate) struct CompiledRuntimePhaseRunner +pub(crate) struct CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score, V: Clone + PartialEq + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + H: RuntimeSource, { - execution: PreparedRuntimeExecution, - prepared_phases: Vec>, + /// The declaration the graph was compiled from: a partitioned phase + /// compiles each partition's runner from it. + source: H, + execution: PreparedRuntimeExecution>, + prepared_phases: Vec>>, phases: Vec>, provider_resources: ProviderExecutionResources, mandatory_bindings: DefaultRuntimeBindings, @@ -122,24 +129,22 @@ where }, } -impl CompiledRuntimePhaseRunner +impl CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score + Copy + Ord + ParseableScore, V: Clone + PartialEq + Into + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, - Extension: CustomSearchPhase, + H: RuntimeSource, + RuntimeGraphInput: Sync, { /// Instantiates extensions in frozen configuration order, lowers every /// frozen local-search node once, and creates the one solve-owned provider /// resource set. It does not bind a list source or invoke a provider. - pub(crate) fn try_new( - executor: CompiledRuntimeExecutor, - ) -> RuntimeBuildResult - where - Registry: RuntimeExtensionRegistry, - { + pub(crate) fn try_new( + executor: CompiledRuntimeExecutor, + ) -> RuntimeBuildResult { let solver_config = executor.graph().config().clone(); let mut mandatory_bindings = executor.graph().default_bindings().clone(); let provider_resources = ProviderExecutionResources::new( @@ -173,6 +178,7 @@ where }) .collect::>>()?; Ok(Self { + source: graph.source, execution, prepared_phases, phases, @@ -199,6 +205,7 @@ where { let phase_index = self.phases[index].phase_index(); let ( + source, execution, prepared_phases, phases, @@ -206,6 +213,7 @@ where mandatory_bindings, mandatory_completion_published, ) = ( + &self.source, &mut self.execution, &mut self.prepared_phases, &mut self.phases, @@ -266,7 +274,12 @@ where PreparedRuntimePhase::Extension(extension), RunnerPhase::Extension { outcome, .. }, ) => { - extension.solve(solver_scope); + match extension { + RuntimeExtensionInstance::Custom(phase) => phase.solve(solver_scope), + RuntimeExtensionInstance::Partitioned(instance) => { + solve_partitioned_instance(instance, source.input(), solver_scope); + } + } *outcome = RunnerPhaseOutcome::Executed; publish_if_mandatory_complete( execution, @@ -343,77 +356,14 @@ where } } -impl RunnerPhase -where - S: PlanningSolution + Clone + Send + Sync + 'static, - S::Score: Score, - V: Clone + PartialEq + Send + Sync + Debug + 'static, - DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, - IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, -{ - fn phase_index(&self) -> usize { - match self { - Self::Construction { phase_index, .. } - | Self::LocalSearch { phase_index, .. } - | Self::Extension { phase_index, .. } - | Self::DefaultRuntime { phase_index, .. } => *phase_index, - } - } - - fn candidate_trace_plan(&self) -> CandidateTracePhasePlan { - match self { - Self::Construction { - phase_index, - declaration, - outcome, - } - | Self::LocalSearch { - phase_index, - declaration, - outcome, - .. - } - | Self::Extension { - phase_index, - declaration, - outcome, - } => phase_with_outcome(*phase_index, outcome.trace_label(), declaration.clone()), - Self::DefaultRuntime { - phase_index, - local_search_declaration, - construction_execution, - outcome, - .. - } => { - let mut children = construction_execution - .as_ref() - .map(default_construction_plan) - .into_iter() - .collect::>(); - if let Some(local_search) = local_search_declaration { - children.push(local_search.clone()); - } - CandidateTracePhasePlan::known( - "solverforge.runtime.default_runtime", - [ - ("outcome", outcome.trace_label().to_string()), - ("phase_index", phase_index.to_string()), - ], - children, - ) - } - } - } -} - -impl Debug for CompiledRuntimePhaseRunner +impl Debug for CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score, V: Clone + PartialEq + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, - Extension: Debug, + H: RuntimeSource, { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter @@ -423,15 +373,16 @@ where } } -impl Phase - for CompiledRuntimePhaseRunner +impl Phase + for CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score + Copy + Ord + ParseableScore, V: Clone + PartialEq + Into + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, - Extension: CustomSearchPhase, + H: RuntimeSource + Send, + RuntimeGraphInput: Sync, D: Director, ProgressCb: ProgressCallback, { @@ -460,10 +411,12 @@ where self.terminal_notified = true; solver_scope.close_problem_changes(); for (prepared, runner_phase) in self.prepared_phases.iter_mut().zip(&mut self.phases) { - if let (PreparedRuntimePhase::Extension(extension), RunnerPhase::Extension { .. }) = - (prepared, runner_phase) + if let ( + PreparedRuntimePhase::Extension(RuntimeExtensionInstance::Custom(phase)), + RunnerPhase::Extension { .. }, + ) = (prepared, runner_phase) { - extension.on_solver_terminal(solver_scope); + phase.on_solver_terminal(solver_scope); } } solver_scope.finalize_candidate_trace_resolved_phase_plan(self.final_phase_plan()); diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/bench.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/bench.rs index 550983eb..bce46849 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/bench.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/bench.rs @@ -18,6 +18,7 @@ use super::super::local_search::{ProviderExecutionResources, RuntimeNeighborhood use super::super::{PreparedConstruction, PreparedRuntimePhase}; use super::local_search::RuntimeLocalSearch; use super::{CompiledRuntimePhaseRunner, RunnerPhase}; +use crate::runtime::compiler::RuntimeSource; /// The frozen input of one descriptor-placement scalar construction phase. pub(crate) struct ScalarConstructionHandoff { @@ -26,13 +27,14 @@ pub(crate) struct ScalarConstructionHandoff { pub(crate) slot_order: Vec, } -impl CompiledRuntimePhaseRunner +impl CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score, V: Clone + PartialEq + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + H: RuntimeSource, { /// Moves out the first phase's lowered acceptor/forager neighborhood and /// the solve's provider resources, or `None` when the first phase is not diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/failure.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/failure.rs index 63413096..bcaf5a76 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/failure.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/failure.rs @@ -40,6 +40,6 @@ pub(super) fn panic_execution_error(error: RuntimeInstantiationError) -> ! { }) } -pub(super) fn panic_runtime_execution_error(error: RuntimeBuildError) -> ! { +pub(crate) fn panic_runtime_execution_error(error: RuntimeBuildError) -> ! { std::panic::panic_any(RuntimeExecutionFailure { error }) } diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs new file mode 100644 index 00000000..de760649 --- /dev/null +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/phase_plan.rs @@ -0,0 +1,76 @@ +//! A runner phase's position and its candidate-trace plan with the outcome +//! it reached. + +use std::fmt::Debug; + +use solverforge_core::domain::PlanningSolution; +use solverforge_core::score::Score; + +use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; +use crate::stats::CandidateTracePhasePlan; + +use super::super::trace::{default_construction_plan, phase_with_outcome}; +use super::RunnerPhase; + +impl RunnerPhase +where + S: PlanningSolution + Clone + Send + Sync + 'static, + S::Score: Score, + V: Clone + PartialEq + Send + Sync + Debug + 'static, + DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, + IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, +{ + pub(super) fn phase_index(&self) -> usize { + match self { + Self::Construction { phase_index, .. } + | Self::LocalSearch { phase_index, .. } + | Self::Extension { phase_index, .. } + | Self::DefaultRuntime { phase_index, .. } => *phase_index, + } + } + + pub(super) fn candidate_trace_plan(&self) -> CandidateTracePhasePlan { + match self { + Self::Construction { + phase_index, + declaration, + outcome, + } + | Self::LocalSearch { + phase_index, + declaration, + outcome, + .. + } + | Self::Extension { + phase_index, + declaration, + outcome, + } => phase_with_outcome(*phase_index, outcome.trace_label(), declaration.clone()), + Self::DefaultRuntime { + phase_index, + local_search_declaration, + construction_execution, + outcome, + .. + } => { + let mut children = construction_execution + .as_ref() + .map(default_construction_plan) + .into_iter() + .collect::>(); + if let Some(local_search) = local_search_declaration { + children.push(local_search.clone()); + } + CandidateTracePhasePlan::known( + "solverforge.runtime.default_runtime", + [ + ("outcome", outcome.trace_label().to_string()), + ("phase_index", phase_index.to_string()), + ], + children, + ) + } + } + } +} diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/runner/problem_change.rs b/crates/solverforge-solver/src/runtime/compiler/executor/runner/problem_change.rs index ae63341f..c237a058 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/runner/problem_change.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/runner/problem_change.rs @@ -12,18 +12,21 @@ use crate::heuristic::selector::nearby_list_change::CrossEntityDistanceMeter; use crate::scope::{ProgressCallback, SolverScope}; use super::super::completion::publish_if_mandatory_complete; +use super::super::partitioned::RuntimeExtensionInstance; use super::super::PreparedRuntimePhase; use super::failure::panic_runtime_execution_error; use super::{CompiledRuntimePhaseRunner, RunnerPhase, RunnerPhaseOutcome}; +use crate::runtime::compiler::{RuntimeGraphInput, RuntimeSource}; -impl CompiledRuntimePhaseRunner +impl CompiledRuntimePhaseRunner where S: PlanningSolution + Clone + Send + Sync + 'static, S::Score: Score + Copy + Ord + ParseableScore, V: Clone + PartialEq + Into + Send + Sync + Debug + 'static, DM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, IDM: Clone + Send + Sync + Debug + CrossEntityDistanceMeter + 'static, - Extension: CustomSearchPhase, + H: RuntimeSource, + RuntimeGraphInput: Sync, { /// Runs the phase sequence, then applies any queued problem changes and /// runs the whole sequence again on the changed solution. The queue is @@ -77,8 +80,10 @@ where self.mandatory_completion_published = false; self.execution.reset_list_source_bindings(); for (prepared, phase) in self.prepared_phases.iter_mut().zip(&mut self.phases) { - if let PreparedRuntimePhase::Extension(extension) = prepared { - extension.on_problem_change(); + if let PreparedRuntimePhase::Extension(RuntimeExtensionInstance::Custom(phase)) = + prepared + { + phase.on_problem_change(); } phase.reset_for_problem_change(); } diff --git a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs index d973b384..3d1460b8 100644 --- a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs @@ -41,6 +41,19 @@ impl PlanningSolution for Plan { #[derive(Debug)] struct MarkerExtension; +#[derive(Debug)] +struct MarkerPartitioner; + +impl crate::phase::partitioned::SolutionPartitioner for MarkerPartitioner { + fn partition(&self, solution: &Plan) -> Vec { + vec![solution.clone()] + } + + fn merge(&self, original: &Plan, _partitions: Vec) -> Plan { + original.clone() + } +} + impl CustomSearchPhase for MarkerExtension { fn solve(&mut self, _solver_scope: &mut SolverScope<'_, Plan, D, ProgressCb>) where @@ -93,7 +106,7 @@ fn partitioned(name: Option<&str>) -> PhaseConfig { partitioner: name.map(str::to_string), thread_count: MoveThreadCount::Count(std::num::NonZeroUsize::new(3).unwrap()), log_progress: true, - child_phases: vec![custom("child_extension")], + child_phases: vec![custom("repair")], termination: None, }) } @@ -113,9 +126,9 @@ fn typed_extensions_lower_names_without_invoking_builders_and_freeze_config() { EXTENSION_BUILD_CALLS.fetch_add(1, Ordering::SeqCst); MarkerExtension }) - .partitioned_phase("by_task", |_context, _config| { + .partitioner("by_task", |_context| { EXTENSION_BUILD_CALLS.fetch_add(1, Ordering::SeqCst); - MarkerExtension + MarkerPartitioner }); let (context, extensions) = declaration.into_runtime_parts(); let input = RuntimeGraphInput::new(context, extensions); @@ -322,3 +335,27 @@ fn typed_extension_registry_rejects_duplicate_names_before_compilation() { .phase("repair", |_| MarkerExtension) .phase("repair", |_| MarkerExtension); } + +#[test] +fn partition_child_phases_compile_with_their_path() { + let config = SolverConfig { + phases: vec![PhaseConfig::PartitionedSearch(PartitionedSearchConfig { + partitioner: Some("by_task".to_string()), + child_phases: vec![custom("repair"), custom("missing")], + ..PartitionedSearchConfig::default() + })], + ..SolverConfig::default() + }; + let declaration = context(config.random_seed) + .defaults() + .phase("repair", |_| MarkerExtension) + .partitioner("by_task", |_| MarkerPartitioner); + let (context, extensions) = declaration.into_runtime_parts(); + let error = compile_runtime_graph(&config, RuntimeGraphInput::new(context, extensions)) + .expect_err("an unregistered child phase is a compile error"); + assert_eq!(error.path, "phases[0].partitioned_search.child_phases[1]"); + assert!(matches!( + error.kind, + RuntimeCompileErrorKind::UnregisteredTypedCustomExtension { ref name } if name == "missing" + )); +} diff --git a/crates/solverforge-solver/src/runtime/compiler/graph.rs b/crates/solverforge-solver/src/runtime/compiler/graph.rs index 8a136fbf..f7196b4c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/graph.rs +++ b/crates/solverforge-solver/src/runtime/compiler/graph.rs @@ -11,6 +11,7 @@ use crate::descriptor::ResolvedVariableBinding; use crate::phase::construction::{ScalarConstructionSchedule, ScalarOrMixedSlotOrder}; use super::defaults::DefaultRuntimeBindings; +use super::input::RuntimeSource; use super::types::{CompiledListSlot, CompiledScalarSlot}; mod provider; @@ -387,16 +388,17 @@ pub(crate) enum CompiledRuntimeExtension { /// Immutable per-config graph. It deliberately contains no current solution, /// callback view, thread-local state, or fresh selector cursor. Those are /// created only by `instantiate()` at the future atomic cutover. -pub(crate) struct CompiledRuntimeGraph +pub(crate) struct CompiledRuntimeGraph where S: solverforge_core::domain::PlanningSolution, { - /// One descriptor-resolved context is owned by the graph together with - /// its concrete extension registry. The executor must use this exact pair - /// rather than rebuilding model metadata or registry state per phase. - pub(super) context: SearchContext, - pub(super) extensions: E, + /// One descriptor-resolved context together with its concrete extension + /// registry, owned by a top-level solve's graph and borrowed by a + /// partition's. The executor must use this exact pair rather than + /// rebuilding model metadata or registry state per phase. + pub(super) source: H, pub(super) config: SolverConfig, + pub(super) _model: std::marker::PhantomData (S, V, DM, IDM)>, /// Frozen declaration-order bindings for omitted runtime phases. Per-solve /// default expansion reads solution state through these slots but never /// reconstructs a model/schema or delegates construction to a wrapper. @@ -404,7 +406,7 @@ where pub(super) phases: Vec>, } -impl std::fmt::Debug for CompiledRuntimeGraph +impl std::fmt::Debug for CompiledRuntimeGraph where S: solverforge_core::domain::PlanningSolution, { @@ -415,14 +417,24 @@ where } } -impl CompiledRuntimeGraph +impl CompiledRuntimeGraph where S: solverforge_core::domain::PlanningSolution, + H: RuntimeSource, { pub(crate) fn context(&self) -> &SearchContext { - &self.context + self.source.input().context() } + pub(crate) fn extensions(&self) -> &H::Extensions { + self.source.input().extensions() + } +} + +impl CompiledRuntimeGraph +where + S: solverforge_core::domain::PlanningSolution, +{ pub(crate) fn config(&self) -> &SolverConfig { &self.config } @@ -431,10 +443,6 @@ where &self.phases } - pub(crate) fn extensions(&self) -> &E { - &self.extensions - } - pub(crate) fn default_bindings(&self) -> &DefaultRuntimeBindings { &self.default_bindings } diff --git a/crates/solverforge-solver/src/runtime/compiler/input.rs b/crates/solverforge-solver/src/runtime/compiler/input.rs index 7071d107..d359296f 100644 --- a/crates/solverforge-solver/src/runtime/compiler/input.rs +++ b/crates/solverforge-solver/src/runtime/compiler/input.rs @@ -6,7 +6,7 @@ use solverforge_core::domain::PlanningSolution; -use crate::builder::SearchContext; +use crate::builder::{RuntimeExtensionRegistry, SearchContext}; /// One typed or dynamic runtime declaration ready for immutable compilation. /// @@ -32,7 +32,48 @@ where } } - pub(crate) fn into_parts(self) -> (SearchContext, E) { - (self.context, self.extensions) + pub(crate) fn context(&self) -> &SearchContext { + &self.context + } + + pub(crate) fn extensions(&self) -> &E { + &self.extensions + } +} + +/// How a compiled graph and its runner hold their declaration: the top-level +/// solve owns its [`RuntimeGraphInput`]; a partition's child runner borrows +/// its parent's. Both resolve to the same input type, so a partition nested +/// in a partition compiles to the same runner type as its parent's child. +pub(crate) trait RuntimeSource +where + S: PlanningSolution, +{ + type Extensions: RuntimeExtensionRegistry; + + fn input(&self) -> &RuntimeGraphInput; +} + +impl RuntimeSource for RuntimeGraphInput +where + S: PlanningSolution, + E: RuntimeExtensionRegistry, +{ + type Extensions = E; + + fn input(&self) -> &RuntimeGraphInput { + self + } +} + +impl RuntimeSource for &RuntimeGraphInput +where + S: PlanningSolution, + E: RuntimeExtensionRegistry, +{ + type Extensions = E; + + fn input(&self) -> &RuntimeGraphInput { + self } } diff --git a/crates/solverforge-solver/src/runtime/compiler/mod.rs b/crates/solverforge-solver/src/runtime/compiler/mod.rs index df9c24af..cd965cab 100644 --- a/crates/solverforge-solver/src/runtime/compiler/mod.rs +++ b/crates/solverforge-solver/src/runtime/compiler/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod executor; mod graph; mod input; mod local_search; +mod partitioned; mod providers; mod score_limits; mod selector_tree; @@ -47,7 +48,8 @@ pub(crate) use graph::{ CompiledRuntimeExtension, CompiledRuntimePhase, ListLeafKind, ProviderBindingPlan, ProviderBindingPolicy, ProviderMoveKind, ProviderSchedule, }; -pub(crate) use input::RuntimeGraphInput; +pub(crate) use input::{RuntimeGraphInput, RuntimeSource}; +pub(crate) use partitioned::partition_child_config; #[cfg(test)] pub(crate) use default_local_search::{ diff --git a/crates/solverforge-solver/src/runtime/compiler/partitioned.rs b/crates/solverforge-solver/src/runtime/compiler/partitioned.rs new file mode 100644 index 00000000..87d11bfa --- /dev/null +++ b/crates/solverforge-solver/src/runtime/compiler/partitioned.rs @@ -0,0 +1,33 @@ +//! The configuration a `partitioned_search` phase solves each partition +//! with. + +use solverforge_config::{PartitionedSearchConfig, SolverConfig, TerminationConfig}; + +/// The solver configuration of one partition's solve: the parent's, with +/// `child_phases` as its phases (empty means the default phases, as at the +/// top level) and as termination the bounds that reach the partition. +/// +/// A partition runs under the parent's time limit and step count budget; +/// limits that need the parent's best score are not checked inside it. The +/// child's termination therefore carries only the time and step count +/// limits, so the default local search stays construction-only in a +/// partition exactly when nothing bounds it there. +pub(crate) fn partition_child_config( + parent: &SolverConfig, + partitioned: &PartitionedSearchConfig, +) -> SolverConfig { + let mut child = parent.clone(); + child.phases = partitioned.child_phases.clone(); + child.termination = partition_bounds(parent.termination.as_ref()); + child +} + +fn partition_bounds(parent: Option<&TerminationConfig>) -> Option { + let parent = parent?; + let bounds = TerminationConfig { + seconds_spent_limit: parent.time_limit().map(|limit| limit.as_secs()), + step_count_limit: parent.step_count_limit, + ..TerminationConfig::default() + }; + (bounds.seconds_spent_limit.is_some() || bounds.step_count_limit.is_some()).then_some(bounds) +} diff --git a/crates/solverforge-solver/src/runtime/compiler/tests.rs b/crates/solverforge-solver/src/runtime/compiler/tests.rs index 0316b4e8..ddd82469 100644 --- a/crates/solverforge-solver/src/runtime/compiler/tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/tests.rs @@ -215,7 +215,13 @@ fn compile( shape: PrecedenceShape, selector: MoveSelectorConfig, ) -> Result< - super::CompiledRuntimeGraph, + super::CompiledRuntimeGraph< + Plan, + usize, + Meter, + Meter, + RuntimeGraphInput, + >, super::RuntimeCompileError, > { let config = SolverConfig { @@ -237,7 +243,13 @@ fn compile_construction( model: RuntimeModel, construction_heuristic_type: ConstructionHeuristicType, ) -> Result< - super::CompiledRuntimeGraph, + super::CompiledRuntimeGraph< + Plan, + usize, + Meter, + Meter, + RuntimeGraphInput, + >, super::RuntimeCompileError, > { let config = SolverConfig { @@ -405,7 +417,13 @@ fn compile_policy( acceptor: Option, forager: Option, ) -> Result< - super::CompiledRuntimeGraph, + super::CompiledRuntimeGraph< + Plan, + usize, + Meter, + Meter, + RuntimeGraphInput, + >, super::RuntimeCompileError, > { let local_search = LocalSearchConfig { diff --git a/crates/solverforge/Cargo.toml b/crates/solverforge/Cargo.toml index 1d2fdef5..1f17d018 100644 --- a/crates/solverforge/Cargo.toml +++ b/crates/solverforge/Cargo.toml @@ -31,5 +31,7 @@ solverforge-cvrp = { version = "=0.24.0", path = "../solverforge-cvrp" } solverforge-console = { version = "=0.24.0", path = "../solverforge-console", optional = true } [dev-dependencies] +rayon.workspace = true serde.workspace = true toml.workspace = true +tracing.workspace = true diff --git a/crates/solverforge/tests/partitioned_search.rs b/crates/solverforge/tests/partitioned_search.rs new file mode 100644 index 00000000..dde6c8b2 --- /dev/null +++ b/crates/solverforge/tests/partitioned_search.rs @@ -0,0 +1,123 @@ +//! `partitioned_search` is run by the framework: the registered partitioner +//! splits the solution, `child_phases` solve each partition on +//! `thread_count` threads, and the partitions are merged back. + +use solverforge::{SolverEvent, SolverManager}; + +#[path = "partitioned_search/domain/mod.rs"] +mod domain; + +use domain::{take_records, Plan}; + +static MANAGER: SolverManager = SolverManager::new(); + +fn solve(plan: Plan) -> Plan { + let (job_id, mut receiver) = MANAGER.solve(plan).expect("solve starts"); + let solution = loop { + match receiver + .blocking_recv() + .expect("event stream should reach a terminal event") + { + SolverEvent::Completed { solution, .. } => break solution, + SolverEvent::Failed { error, .. } => panic!("solve failed: {error}"), + SolverEvent::Cancelled { .. } => panic!("solve was cancelled"), + _ => {} + } + }; + MANAGER.delete(job_id).expect("the completed job deletes"); + solution +} + +fn distinct_threads(records: &[domain::Record]) -> usize { + let mut threads: Vec<_> = records.iter().map(|record| record.thread).collect(); + threads.sort_by_key(|thread| format!("{thread:?}")); + threads.dedup(); + threads.len() +} + +const TWO_THREADS: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" +thread_count = { count = 2 } + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "custom" +name = "record" +"#; + +#[test] +fn child_phases_solve_every_partition_on_the_configured_threads() { + let solution = solve(Plan::new(TWO_THREADS)); + + assert!(solution + .tasks + .iter() + .all(|task| task.resource_idx.is_some())); + assert_eq!(solution.score.map(|score| score.hard()), Some(0)); + + let mut records = take_records(TWO_THREADS); + records.sort_by_key(|record| record.task_ids[0]); + let partitions: Vec> = records.iter().map(|r| r.task_ids.clone()).collect(); + assert_eq!( + partitions, + vec![vec![0, 4], vec![1, 5], vec![2, 6], vec![3, 7]] + ); + for record in &records { + assert!(record.all_assigned, "construction ran before `record`"); + assert_eq!( + record.pool_threads, 2, + "partitions run on a two-thread pool" + ); + } + assert!(distinct_threads(&records) <= 2); +} + +const ONE_THREAD: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" +thread_count = "none" + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "custom" +name = "record" +"#; + +#[test] +fn thread_count_none_solves_the_partitions_on_the_solver_thread() { + let solution = solve(Plan::new(ONE_THREAD)); + + assert!(solution + .tasks + .iter() + .all(|task| task.resource_idx.is_some())); + let records = take_records(ONE_THREAD); + assert_eq!(records.len(), 4); + assert_eq!(distinct_threads(&records), 1); +} + +const DEFAULT_CHILDREN: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" +"#; + +#[test] +fn empty_child_phases_run_the_default_phases_in_each_partition() { + let solution = solve(Plan::new(DEFAULT_CHILDREN)); + + assert!(solution + .tasks + .iter() + .all(|task| task.resource_idx.is_some())); + assert_eq!(solution.score.map(|score| score.hard()), Some(0)); +} diff --git a/crates/solverforge/tests/partitioned_search/domain/mod.rs b/crates/solverforge/tests/partitioned_search/domain/mod.rs new file mode 100644 index 00000000..e4c33aa2 --- /dev/null +++ b/crates/solverforge/tests/partitioned_search/domain/mod.rs @@ -0,0 +1,11 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/partitioned_search/domain"; + + mod plan; + mod resource; + mod task; + + pub use plan::{take_records, Plan, Record}; + pub use resource::Resource; + pub use task::Task; +} diff --git a/crates/solverforge/tests/partitioned_search/domain/plan.rs b/crates/solverforge/tests/partitioned_search/domain/plan.rs new file mode 100644 index 00000000..a8ef6d67 --- /dev/null +++ b/crates/solverforge/tests/partitioned_search/domain/plan.rs @@ -0,0 +1,153 @@ +use std::fmt::Debug; +use std::sync::Mutex; + +use solverforge::prelude::*; +use solverforge::stream::ConstraintFactory; +use solverforge::{CrossEntityDistanceMeter, ProgressCallback, SolverConfig, SolverScope}; + +use super::{Resource, Task}; + +/// Tasks split into this many partitions, by task id modulo the count. +pub const PARTITIONS: usize = 4; + +#[planning_solution(constraints = "constraints", config = "solver_config", search = "search")] +pub struct Plan { + #[problem_fact_collection] + pub resources: Vec, + + #[planning_entity_collection] + pub tasks: Vec, + + #[planning_score] + pub score: Option, + + /// The solver TOML a solve of this plan runs with; also the key its + /// partition records are filed under. + pub solver_toml: &'static str, +} + +impl Plan { + pub fn new(solver_toml: &'static str) -> Self { + Self { + resources: (0..3).map(|id| Resource { id }).collect(), + tasks: (0..8) + .map(|id| Task { + id, + resource_idx: None, + }) + .collect(), + score: None, + solver_toml, + } + } +} + +fn solver_config(solution: &Plan, _base: SolverConfig) -> SolverConfig { + SolverConfig::from_toml_str(solution.solver_toml).expect("the test config parses") +} + +/// Each unassigned task costs one hard point, each assigned task its +/// resource index plus one soft point. +fn constraints() -> impl ConstraintSet { + ( + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.resource_idx.is_none()) + .penalize(HardSoftScore::ONE_HARD) + .named("unassigned task"), + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.resource_idx.is_some()) + .penalize(|task: &Task| { + HardSoftScore::of(0, task.resource_idx.unwrap_or_default() as i64 + 1) + }) + .named("placement cost"), + ) +} + +fn search(ctx: SearchContext) -> impl Search +where + DM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static, + IDM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static, +{ + ctx.defaults() + .phase("record", |_| RecordPhase) + .partitioner("by_task_id", |_| ByTaskId) +} + +/// Splits the tasks by id modulo [`PARTITIONS`]; every partition keeps all +/// resources. +#[derive(Debug)] +struct ByTaskId; + +impl SolutionPartitioner for ByTaskId { + fn partition(&self, solution: &Plan) -> Vec { + (0..PARTITIONS) + .map(|part| Plan { + tasks: solution + .tasks + .iter() + .filter(|task| task.id % PARTITIONS == part) + .cloned() + .collect(), + ..solution.clone() + }) + .collect() + } + + fn merge(&self, original: &Plan, partitions: Vec) -> Plan { + let mut merged = original.clone(); + for task in partitions.into_iter().flat_map(|partition| partition.tasks) { + let id = task.id; + merged.tasks[id] = task; + } + merged + } +} + +/// What the `record` child phase saw in one partition. +#[derive(Clone, Debug)] +pub struct Record { + pub task_ids: Vec, + pub all_assigned: bool, + pub thread: std::thread::ThreadId, + /// Threads of the rayon pool the phase runs in. + pub pool_threads: usize, +} + +static RECORDS: Mutex> = Mutex::new(Vec::new()); + +/// Removes and returns the records of solves run with `solver_toml`. +pub fn take_records(solver_toml: &'static str) -> Vec { + let mut records = RECORDS.lock().unwrap(); + let (taken, kept) = records + .drain(..) + .partition::, _>(|(key, _)| std::ptr::eq(*key, solver_toml)); + *records = kept; + taken.into_iter().map(|(_, record)| record).collect() +} + +/// A child phase recording the partition it runs on. +#[derive(Debug)] +struct RecordPhase; + +impl CustomSearchPhase for RecordPhase { + fn solve(&mut self, solver_scope: &mut SolverScope<'_, Plan, D, ProgressCb>) + where + D: Director, + ProgressCb: ProgressCallback, + { + let plan = solver_scope.working_solution(); + let record = Record { + task_ids: plan.tasks.iter().map(|task| task.id).collect(), + all_assigned: plan.tasks.iter().all(|task| task.resource_idx.is_some()), + thread: std::thread::current().id(), + pool_threads: rayon::current_num_threads(), + }; + RECORDS.lock().unwrap().push((plan.solver_toml, record)); + } + + fn phase_type_name(&self) -> &'static str { + "record" + } +} diff --git a/crates/solverforge/tests/partitioned_search/domain/resource.rs b/crates/solverforge/tests/partitioned_search/domain/resource.rs new file mode 100644 index 00000000..4a1467d6 --- /dev/null +++ b/crates/solverforge/tests/partitioned_search/domain/resource.rs @@ -0,0 +1,7 @@ +use solverforge::prelude::*; + +#[problem_fact] +pub struct Resource { + #[planning_id] + pub id: usize, +} diff --git a/crates/solverforge/tests/partitioned_search/domain/task.rs b/crates/solverforge/tests/partitioned_search/domain/task.rs new file mode 100644 index 00000000..c46507ea --- /dev/null +++ b/crates/solverforge/tests/partitioned_search/domain/task.rs @@ -0,0 +1,10 @@ +use solverforge::prelude::*; + +#[planning_entity] +pub struct Task { + #[planning_id] + pub id: usize, + + #[planning_variable(value_range_provider = "resources")] + pub resource_idx: Option, +} diff --git a/crates/solverforge/tests/partitioned_search_log_progress.rs b/crates/solverforge/tests/partitioned_search_log_progress.rs new file mode 100644 index 00000000..d59f32de --- /dev/null +++ b/crates/solverforge/tests/partitioned_search_log_progress.rs @@ -0,0 +1,173 @@ +//! `log_progress` on a `partitioned_search` phase logs the phase's start and +//! end. Its own test binary: the capturing subscriber is process-global, +//! because the solve runs on a solver thread. + +use std::sync::{Arc, Mutex, OnceLock}; + +use solverforge::{SolverEvent, SolverManager}; +use tracing::field::{Field, Visit}; +use tracing::span::{Attributes, Id, Record}; +use tracing::{Event, Metadata, Subscriber}; + +#[path = "partitioned_search/domain/mod.rs"] +mod domain; + +use domain::{take_records, Plan}; + +static MANAGER: SolverManager = SolverManager::new(); + +/// Captured `PartitionedSearch` events: name and `partition_count`. +type Events = Arc)>>>; + +#[derive(Clone, Default)] +struct CaptureSubscriber { + events: Events, +} + +#[derive(Default)] +struct PartitionedEvent { + event: Option, + phase: Option, + partition_count: Option, +} + +impl Visit for PartitionedEvent { + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + let value = format!("{value:?}").trim_matches('"').to_string(); + match field.name() { + "event" => self.event = Some(value), + "phase" => self.phase = Some(value), + _ => {} + } + } + + fn record_str(&mut self, field: &Field, value: &str) { + self.record_debug(field, &value); + } + + fn record_u64(&mut self, field: &Field, value: u64) { + if field.name() == "partition_count" { + self.partition_count = Some(value); + } + } +} + +impl Subscriber for CaptureSubscriber { + fn enabled(&self, _metadata: &Metadata<'_>) -> bool { + true + } + + fn new_span(&self, _span: &Attributes<'_>) -> Id { + Id::from_u64(1) + } + + fn record(&self, _span: &Id, _values: &Record<'_>) {} + + fn record_follows_from(&self, _span: &Id, _follows: &Id) {} + + fn event(&self, event: &Event<'_>) { + let mut captured = PartitionedEvent::default(); + event.record(&mut captured); + if captured.phase.as_deref() == Some("PartitionedSearch") { + if let Some(name) = captured.event { + self.events + .lock() + .unwrap() + .push((name, captured.partition_count)); + } + } + } + + fn enter(&self, _span: &Id) {} + + fn exit(&self, _span: &Id) {} +} + +fn captured() -> &'static Events { + static EVENTS: OnceLock = OnceLock::new(); + EVENTS.get_or_init(|| { + let subscriber = CaptureSubscriber::default(); + let events = Arc::clone(&subscriber.events); + tracing::subscriber::set_global_default(subscriber) + .expect("this test binary installs the only global subscriber"); + events + }) +} + +fn solve(plan: Plan) { + let (job_id, mut receiver) = MANAGER.solve(plan).expect("solve starts"); + loop { + match receiver + .blocking_recv() + .expect("event stream should reach a terminal event") + { + SolverEvent::Completed { .. } => break, + SolverEvent::Failed { error, .. } => panic!("solve failed: {error}"), + SolverEvent::Cancelled { .. } => panic!("solve was cancelled"), + _ => {} + } + } + MANAGER.delete(job_id).expect("the completed job deletes"); +} + +const LOGGED: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" +log_progress = true + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "custom" +name = "record" +"#; + +const QUIET: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" +"#; + +#[test] +fn log_progress_logs_the_partitioned_phase() { + let events = captured(); + + solve(Plan::new(QUIET)); + assert!( + events.lock().unwrap().is_empty(), + "log_progress defaults to off" + ); + + solve(Plan::new(LOGGED)); + let logged = std::mem::take(&mut *events.lock().unwrap()); + assert_eq!( + logged, + vec![ + ("phase_start".to_string(), Some(4)), + ("phase_end".to_string(), None), + ] + ); + let records: Vec = take_records(LOGGED); + assert_eq!(records.len(), 4); + assert!(records.iter().all(|record| record.all_assigned + && record.task_ids.len() == 2 + && record.pool_threads >= 1)); + let mut threads: Vec = records + .iter() + .map(|record| format!("{:?}", record.thread)) + .collect(); + threads.sort(); + threads.dedup(); + let cores = std::thread::available_parallelism().map_or(1, |cores| cores.get()); + assert!( + threads.len() <= cores.min(4), + "`auto` runs one thread per partition up to the cores" + ); +} diff --git a/docs/extend-solver.md b/docs/extend-solver.md index 1c173380..164a3a73 100644 --- a/docs/extend-solver.md +++ b/docs/extend-solver.md @@ -191,6 +191,37 @@ partition boundaries, when merge cost dominates child solving, or when child solutions need global coordination to stay feasible. Typed search registration must name the partitioner explicitly; unregistered config fails at build time. +The search function registers only the partitioner; SolverForge runs the phase: + +```rust,ignore +fn search(ctx: SearchContext) -> impl Search +where + DM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static, + IDM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static, +{ + ctx.defaults().partitioner("by_region", |_| ByRegion) +} +``` + +```toml +[[phases]] +type = "partitioned_search" +partitioner = "by_region" +thread_count = { count = 4 } + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "local_search" +``` + +Each partition is solved by `child_phases`, compiled exactly like top-level +`phases`; an empty list runs the default phases. `thread_count` sets how many +partitions are solved at once and `log_progress` logs the phase's start and end. +A partition runs under the solve's time and step count limits. + Partition children are internal compute scopes, not retained-job publication owners. They inherit cancellation, environment mode, remaining time limit, in-phase limits, and deterministic seeds, but pause checkpoints are emitted only From 6a9f27c92a14d0d2ce877771ddc5ee6588c02d28 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Thu, 5 Nov 2026 05:09:16 +0100 Subject: [PATCH 4/4] feat(partitioned)!: bound partitions by the phase termination A `partitioned_search` phase's `termination` was validated and never applied: the runtime ran the phase without it. It now bounds the partitions. Its time limit, counted from the phase's start, holds for every partition, and its step count limit for each partition's solve. A partition that reaches either ends like a phase: it keeps its best solution, the partitions are merged, and the solve goes on to the next phase instead of terminating. A bound made inside a partition chains to the enclosing one. A partition sees only its part of the solution, so `best_score_limit`, `unimproved_step_count_limit` and `unimproved_seconds_spent_limit` on a partitioned phase are rejected at compile time with their key path. Each partition's configuration carries the earliest of the solve's and the phase's time and step count limits, so the default local search runs in a partition exactly when something bounds it there. Closes #199. BREAKING CHANGE: a `partitioned_search` phase whose `termination` sets `best_score_limit`, `unimproved_step_count_limit` or `unimproved_seconds_spent_limit` is a configuration error. --- crates/solverforge-config/WIREFRAME.md | 2 +- crates/solverforge-config/src/phase.rs | 5 +- crates/solverforge-solver/WIREFRAME.md | 2 +- .../src/phase/partitioned/execution.rs | 60 +++++-- .../src/phase/partitioned/phase.rs | 1 + .../runtime/compiler/executor/partitioned.rs | 7 +- .../src/runtime/compiler/extension_tests.rs | 35 ++++ .../src/runtime/compiler/partitioned.rs | 48 ++++-- .../src/runtime/compiler/score_limits.rs | 33 ++++ crates/solverforge-solver/src/scope/mod.rs | 4 +- crates/solverforge-solver/src/scope/solver.rs | 1 + .../src/scope/solver/scope_child.rs | 155 ++++++++++++++++++ .../src/scope/solver/scope_core.rs | 67 +------- .../src/scope/solver/scope_progress.rs | 3 + .../src/scope/solver/scope_termination.rs | 21 ++- .../src/scope/solver/weight_mode.rs | 1 + crates/solverforge-solver/src/scope/tests.rs | 1 + .../src/scope/tests/partition_bound.rs | 84 ++++++++++ .../solverforge/tests/partitioned_search.rs | 67 ++++++++ docs/extend-solver.md | 7 +- 20 files changed, 504 insertions(+), 100 deletions(-) create mode 100644 crates/solverforge-solver/src/scope/solver/scope_child.rs create mode 100644 crates/solverforge-solver/src/scope/tests/partition_bound.rs diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index d0d9e432..4afc7fa4 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -696,7 +696,7 @@ Derives: `Debug, Clone, Default, Deserialize, Serialize`. | `thread_count` | `MoveThreadCount` | `Auto` | | `log_progress` | `bool` | `false`; logs the phase's start and end | | `child_phases` | `Vec` | `[]`; the phases each partition is solved with, compiled like `phases`; empty runs the default phases | -| `termination` | `Option` | `None` | +| `termination` | `Option` | `None`; the time limit, from the phase's start, bounds all partitions and the step count limit each partition's solve; reaching one ends the phase with the partitions merged. `best_score_limit` and the unimproved limits are rejected | ### `CustomPhaseConfig` diff --git a/crates/solverforge-config/src/phase.rs b/crates/solverforge-config/src/phase.rs index 011f13b3..c6c1220a 100644 --- a/crates/solverforge-config/src/phase.rs +++ b/crates/solverforge-config/src/phase.rs @@ -211,7 +211,10 @@ pub struct PartitionedSearchConfig { #[serde(default)] pub child_phases: Vec, - /// Phase termination configuration. + /// The phase's termination: the time limit, counted from the phase's + /// start, bounds all partitions and the step count limit each + /// partition's solve. Limits on the merged solution's score are + /// rejected. pub termination: Option, } diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 221bf07e..98a0ee61 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -721,7 +721,7 @@ working solution without cloning. **`ThreadCount`** — `Auto` (one thread per partition, at most one per available core), `Unlimited` (one per available core), `Specific(NonZeroUsize)` (at most that many, at most one per partition). `PartitionedSearchPhase` solves child partitions sequentially when the resolved count is `1`, otherwise it installs a dedicated Rayon pool whose worker count matches the resolved value. -**Configured `partitioned_search`** — The framework runs it; a search declaration only registers the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`, in a namespace separate from custom phase names. `partitioner = "name"` selects it. Each partition gets a director from `Director::fork_for_solution` over the partition and a `CompiledRuntimePhaseRunner` compiled from `partition_child_config`: the parent configuration with `child_phases` as its phases (empty means the default phases) and, as termination, only the parent's time and step count limits, the bounds that reach a partition. The graph compiler compiles that child configuration once up front, so a child phase error fails the solve with a `phases[i].partitioned_search.child_phases[j]` path. `thread_count` and `log_progress` apply as for `PartitionedSearchPhase` (`log_progress` logs `phase_start` with `partition_count` and `thread_count`, and `phase_end`). A child runner borrows its parent's `RuntimeGraphInput`, so nested partitioned phases compile to the same runner type. The `RuntimeExtensionRegistry` is `Send + Sync` for that reason: partition runners compile on the threads that solve them. +**Configured `partitioned_search`** — The framework runs it; a search declaration only registers the partitioner, with `SearchBuilder::partitioner(name, |context| partitioner)`, in a namespace separate from custom phase names. `partitioner = "name"` selects it. Each partition gets a director from `Director::fork_for_solution` over the partition and a `CompiledRuntimePhaseRunner` compiled from `partition_child_config`: the parent configuration with `child_phases` as its phases (empty means the default phases) and, as termination, the earliest of the solve's and the phase's time and step count limits, the bounds that reach a partition. The graph compiler compiles that child configuration once up front, so a child phase error fails the solve with a `phases[i].partitioned_search.child_phases[j]` path. The phase's `termination` becomes a `PartitionBound`: its time limit, counted from the phase's start, is shared by every partition, and its step count limit applies to each partition's solve (each partition counts its own steps; a bound inside a partition chains to the enclosing one, which also counts the inner steps). A partition that reaches the bound ends like a phase — `should_terminate` is true without a terminal reason and `solve_limit_reached` stays false — so its best solution is merged and the solve goes on to the next phase; a partition that starts after the deadline is merged as it was. Termination keys that need the merged solution's score (`best_score_limit`, `unimproved_step_count_limit`, `unimproved_seconds_spent_limit`) are rejected at compile time with their `phases[i].partitioned_search.termination.` path. `thread_count` and `log_progress` apply as for `PartitionedSearchPhase` (`log_progress` logs `phase_start` with `partition_count` and `thread_count`, and `phase_end`). A child runner borrows its parent's `RuntimeGraphInput`, so nested partitioned phases compile to the same runner type. The `RuntimeExtensionRegistry` is `Send + Sync` for that reason: partition runners compile on the threads that solve them. ## Scope Hierarchy diff --git a/crates/solverforge-solver/src/phase/partitioned/execution.rs b/crates/solverforge-solver/src/phase/partitioned/execution.rs index 8603e217..e9bd3b8b 100644 --- a/crates/solverforge-solver/src/phase/partitioned/execution.rs +++ b/crates/solverforge-solver/src/phase/partitioned/execution.rs @@ -11,7 +11,8 @@ use solverforge_scoring::Director; use crate::manager::SolverTerminalReason; use crate::scope::ProgressCallback; -use crate::scope::{PendingControl, SolverScope, SolverScopeChildConfig}; +use crate::scope::{PartitionBound, PendingControl, SolverScope, SolverScopeChildConfig}; +use solverforge_config::TerminationConfig; use super::config::PartitionedSearchConfig; use super::partitioner::SolutionPartitioner; @@ -36,10 +37,16 @@ enum PartitionOutcome { /// initializes it. A pause re-partitions from the parent's working solution /// once resumed; cancellation, termination and a queued problem change stop /// the pass without merging. +/// +/// `termination` is the phase's own: its time limit, counted from the +/// phase's start, bounds every partition, and its step count limit bounds +/// each partition's solve. A partition that reaches one ends like a phase: +/// its best solution is merged and the solve goes on. pub(crate) fn solve_partitioned( solver_scope: &mut SolverScope<'_, S, D, BestCb>, partitioner: &Part, config: &PartitionedSearchConfig, + termination: Option<&TerminationConfig>, mut make_director: MakeDirector, solve_children: &SolveChildren, ) where @@ -51,8 +58,9 @@ pub(crate) fn solve_partitioned PD, SolveChildren: Fn(&mut SolverScope<'_, S, PD>) + Sync, { + let bound = PartitionBound::new(solver_scope.partition_bound(), termination); 'partitioning: loop { - if solver_scope.should_terminate() { + if solver_scope.should_terminate() || bound.as_ref().is_some_and(PartitionBound::reached) { return; } @@ -77,9 +85,20 @@ pub(crate) fn solve_partitioned = directors + let partition_bounds: Vec> = bound + .iter() + .flat_map(|bound| directors.iter().map(|_| bound.for_partition())) + .collect(); + let children: Vec<(PD, u64, Option<&PartitionBound<'_>>)> = directors .into_iter() - .map(|director| (director, solver_scope.rng().random())) + .enumerate() + .map(|(index, director)| { + ( + director, + solver_scope.rng().random(), + partition_bounds.get(index), + ) + }) .collect(); let phase_budget = solver_scope.child_phase_budget(); let child_config = solver_scope.child_config(Some(&phase_budget)); @@ -105,7 +124,13 @@ pub(crate) fn solve_partitioned( - children: Vec<(PD, u64)>, + children: Vec<(PD, u64, Option<&'t PartitionBound<'t>>)>, thread_count: usize, child_config: SolverScopeChildConfig<'t, S>, solve_children: &SolveChildren, @@ -140,8 +165,9 @@ where if thread_count <= 1 || children.len() <= 1 { return children .into_iter() - .map(|(director, seed)| { - solve_partition(director, child_config.clone(), seed, solve_children) + .map(|(director, seed, bound)| { + let child_config = child_config.clone().with_partition_bound(bound); + solve_partition(director, child_config, seed, solve_children) }) .collect(); } @@ -153,8 +179,9 @@ where .install(|| { children .into_par_iter() - .map(|(director, seed)| { - solve_partition(director, child_config.clone(), seed, solve_children) + .map(|(director, seed, bound)| { + let child_config = child_config.clone().with_partition_bound(bound); + solve_partition(director, child_config, seed, solve_children) }) .collect() }) @@ -172,16 +199,19 @@ where SolveChildren: Fn(&mut SolverScope<'_, S, PD>) + Sync, { let mut solver_scope = child_config.build_scope(director, seed); - if solver_scope.should_terminate() { - return PartitionOutcome::Terminated; + // A partition starting after its phase's time limit is left as it is, + // like any unreached work at a phase end; a stop of the solve itself is + // classified below. + if !solver_scope.should_terminate() { + solver_scope.initialize_working_solution_as_best(); + solve_children(&mut solver_scope); } - solver_scope.initialize_working_solution_as_best(); - - solve_children(&mut solver_scope); match solver_scope.pending_control() { PendingControl::PauseRequested => return PartitionOutcome::Pause, PendingControl::CancelRequested => return PartitionOutcome::Cancelled, + // Only the partition bound: the phase ended, the partition is done. + PendingControl::ConfigTerminationRequested if !solver_scope.solve_limit_reached() => {} PendingControl::ConfigTerminationRequested => return PartitionOutcome::Terminated, PendingControl::ProblemChangeRequested => return PartitionOutcome::ProblemChange, PendingControl::Continue => {} diff --git a/crates/solverforge-solver/src/phase/partitioned/phase.rs b/crates/solverforge-solver/src/phase/partitioned/phase.rs index db85f64e..42f5edcd 100644 --- a/crates/solverforge-solver/src/phase/partitioned/phase.rs +++ b/crates/solverforge-solver/src/phase/partitioned/phase.rs @@ -128,6 +128,7 @@ where solver_scope, &self.partitioner, &self.config, + None, |_: &D, partition| (self.score_director_factory)(partition), &|child_scope: &mut SolverScope<'_, S, PD>| { (self.phase_factory)().solve_all(child_scope); diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs b/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs index 7cfffa81..0558ac03 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/partitioned.rs @@ -5,7 +5,7 @@ use std::fmt::Debug; -use solverforge_config::SolverConfig; +use solverforge_config::{SolverConfig, TerminationConfig}; use solverforge_core::domain::PlanningSolution; use solverforge_core::score::{ParseableScore, Score}; use solverforge_scoring::Director; @@ -57,6 +57,9 @@ pub(crate) type SourceExtension = pub(crate) struct PartitionedInstance { partitioner: Partitioner, config: PartitionedSearchConfig, + /// The phase's termination: its time and step count limits bound all + /// partitions together. + termination: Option, /// The configuration each partition is solved with. child_config: SolverConfig, } @@ -70,6 +73,7 @@ impl PartitionedInstance { Self { partitioner, config: PartitionedSearchConfig::from_serialized(config), + termination: config.termination.clone(), child_config: partition_child_config(parent, config), } } @@ -120,6 +124,7 @@ pub(super) fn solve_partitioned_instance( solver_scope, &instance.partitioner, &instance.config, + instance.termination.as_ref(), |director: &D, partition| { director.fork_for_solution(partition).expect( "partitioned search requires a director built with a constraint-set constructor", diff --git a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs index 3d1460b8..1238529c 100644 --- a/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs +++ b/crates/solverforge-solver/src/runtime/compiler/extension_tests.rs @@ -359,3 +359,38 @@ fn partition_child_phases_compile_with_their_path() { RuntimeCompileErrorKind::UnregisteredTypedCustomExtension { ref name } if name == "missing" )); } + +#[test] +fn partitioned_termination_rejects_limits_on_the_merged_score() { + for (key, toml) in [ + ("best_score_limit", "best_score_limit = \"0\""), + ( + "unimproved_step_count_limit", + "unimproved_step_count_limit = 5", + ), + ( + "unimproved_seconds_spent_limit", + "unimproved_seconds_spent_limit = 5", + ), + ] { + let config = SolverConfig::from_toml_str(&format!( + "[[phases]]\ntype = \"partitioned_search\"\npartitioner = \"by_task\"\n\ + [phases.termination]\nstep_count_limit = 3\n{toml}\n" + )) + .expect("the test config parses"); + let declaration = context(config.random_seed) + .defaults() + .partitioner("by_task", |_| MarkerPartitioner); + let (context, extensions) = declaration.into_runtime_parts(); + let error = compile_runtime_graph(&config, RuntimeGraphInput::new(context, extensions)) + .expect_err("a partition cannot check a merged-score limit"); + assert_eq!( + error.path, + format!("phases[0].partitioned_search.termination.{key}") + ); + assert!(matches!( + error.kind, + RuntimeCompileErrorKind::InvalidValue { .. } + )); + } +} diff --git a/crates/solverforge-solver/src/runtime/compiler/partitioned.rs b/crates/solverforge-solver/src/runtime/compiler/partitioned.rs index 87d11bfa..3a569efd 100644 --- a/crates/solverforge-solver/src/runtime/compiler/partitioned.rs +++ b/crates/solverforge-solver/src/runtime/compiler/partitioned.rs @@ -1,33 +1,55 @@ //! The configuration a `partitioned_search` phase solves each partition //! with. +use std::time::Duration; + use solverforge_config::{PartitionedSearchConfig, SolverConfig, TerminationConfig}; /// The solver configuration of one partition's solve: the parent's, with /// `child_phases` as its phases (empty means the default phases, as at the /// top level) and as termination the bounds that reach the partition. /// -/// A partition runs under the parent's time limit and step count budget; -/// limits that need the parent's best score are not checked inside it. The -/// child's termination therefore carries only the time and step count -/// limits, so the default local search stays construction-only in a -/// partition exactly when nothing bounds it there. +/// A partition runs under the solve's time limit and step count budget and +/// under the partitioned phase's own time and step count limits; limits +/// that need the parent's best score are not checked inside it. The child's +/// termination therefore carries the earliest time and step count limits, +/// so the default local search stays construction-only in a partition +/// exactly when nothing bounds it there. pub(crate) fn partition_child_config( parent: &SolverConfig, partitioned: &PartitionedSearchConfig, ) -> SolverConfig { let mut child = parent.clone(); child.phases = partitioned.child_phases.clone(); - child.termination = partition_bounds(parent.termination.as_ref()); + child.termination = partition_bounds( + parent.termination.as_ref(), + partitioned.termination.as_ref(), + ); child } -fn partition_bounds(parent: Option<&TerminationConfig>) -> Option { - let parent = parent?; - let bounds = TerminationConfig { - seconds_spent_limit: parent.time_limit().map(|limit| limit.as_secs()), - step_count_limit: parent.step_count_limit, +fn partition_bounds( + solve: Option<&TerminationConfig>, + phase: Option<&TerminationConfig>, +) -> Option { + let time_limit = earliest( + solve.and_then(TerminationConfig::time_limit), + phase.and_then(TerminationConfig::time_limit), + ); + let step_count_limit = earliest( + solve.and_then(|config| config.step_count_limit), + phase.and_then(|config| config.step_count_limit), + ); + (time_limit.is_some() || step_count_limit.is_some()).then(|| TerminationConfig { + seconds_spent_limit: time_limit.map(|limit: Duration| limit.as_secs()), + step_count_limit, ..TerminationConfig::default() - }; - (bounds.seconds_spent_limit.is_some() || bounds.step_count_limit.is_some()).then_some(bounds) + }) +} + +fn earliest(left: Option, right: Option) -> Option { + match (left, right) { + (Some(left), Some(right)) => Some(left.min(right)), + (left, right) => left.or(right), + } } diff --git a/crates/solverforge-solver/src/runtime/compiler/score_limits.rs b/crates/solverforge-solver/src/runtime/compiler/score_limits.rs index c873bf43..b1df70e8 100644 --- a/crates/solverforge-solver/src/runtime/compiler/score_limits.rs +++ b/crates/solverforge-solver/src/runtime/compiler/score_limits.rs @@ -34,6 +34,10 @@ fn validate_phases( config.termination.as_ref(), &format!("{path}.termination"), )?; + reject_merged_score_limits( + config.termination.as_ref(), + &format!("{path}.termination"), + )?; validate_phases::(&config.child_phases, &format!("{path}.child_phases"))?; } PhaseConfig::Custom(_) => {} @@ -42,6 +46,35 @@ fn validate_phases( Ok(()) } +/// A partitioned phase's termination bounds its partitions, which see only +/// their own part of the solution; a limit on the merged solution's score, +/// or on its improvement, cannot be checked there. +fn reject_merged_score_limits( + config: Option<&TerminationConfig>, + path: &str, +) -> Result<(), RuntimeCompileError> { + let Some(config) = config else { + return Ok(()); + }; + let key = if config.best_score_limit.is_some() { + "best_score_limit" + } else if config.unimproved_step_count_limit.is_some() { + "unimproved_step_count_limit" + } else if config.unimproved_seconds_spent_limit.is_some() { + "unimproved_seconds_spent_limit" + } else { + return Ok(()); + }; + Err(RuntimeCompileError { + path: format!("{path}.{key}"), + kind: RuntimeCompileErrorKind::InvalidValue { + message: "needs the merged solution's score, which a partition cannot check; a \ + partitioned phase is bounded by time and step count limits" + .to_string(), + }, + }) +} + fn validate_termination( config: Option<&TerminationConfig>, path: &str, diff --git a/crates/solverforge-solver/src/scope/mod.rs b/crates/solverforge-solver/src/scope/mod.rs index 74e818fb..085009fd 100644 --- a/crates/solverforge-solver/src/scope/mod.rs +++ b/crates/solverforge-solver/src/scope/mod.rs @@ -10,7 +10,9 @@ pub(crate) mod solver; pub(crate) mod step; pub(crate) use phase::PhaseScope; -pub(crate) use solver::{PendingControl, SolverScopeChildConfig, WeightModeControl}; +pub(crate) use solver::{ + PartitionBound, PendingControl, SolverScopeChildConfig, WeightModeControl, +}; pub(crate) use solver::{ProgressCallback, SolverProgressKind, SolverProgressRef, SolverScope}; pub(crate) use step::StepControlPolicy; pub(crate) use step::StepScope; diff --git a/crates/solverforge-solver/src/scope/solver.rs b/crates/solverforge-solver/src/scope/solver.rs index 937050bb..45ef6d2c 100644 --- a/crates/solverforge-solver/src/scope/solver.rs +++ b/crates/solverforge-solver/src/scope/solver.rs @@ -29,6 +29,7 @@ include!("solver/progress.rs"); include!("solver/scope_core.rs"); include!("solver/scope_frontier.rs"); include!("solver/phase_budget.rs"); +include!("solver/scope_child.rs"); include!("solver/scope_progress.rs"); include!("solver/scope_termination.rs"); include!("solver/scope_trace.rs"); diff --git a/crates/solverforge-solver/src/scope/solver/scope_child.rs b/crates/solverforge-solver/src/scope/solver/scope_child.rs new file mode 100644 index 00000000..9acaba61 --- /dev/null +++ b/crates/solverforge-solver/src/scope/solver/scope_child.rs @@ -0,0 +1,155 @@ +/* Child scopes: the configuration a partition's solver scope is built with, +the step/move/score-calculation budget children share, and the partition +bound that ends a partitioned phase. Included by `scope/solver.rs`. */ + +#[derive(Clone, Copy)] +pub(crate) struct SolverScopeChildConfig<'t, S: PlanningSolution> { + terminate: Option<&'t AtomicBool>, + runtime: Option>, + environment_mode: EnvironmentMode, + time_deadline: Option, + phase_budget: Option<&'t PhaseBudget>, + partition_bound: Option<&'t PartitionBound<'t>>, + inphase_step_count_limit: Option, + inphase_move_count_limit: Option, + inphase_score_calc_count_limit: Option, + inphase_best_score_limit: Option, +} + +impl<'t, S: PlanningSolution> SolverScopeChildConfig<'t, S> { + /// Child scopes built from this configuration also stop at `bound`. + pub(crate) fn with_partition_bound(mut self, bound: Option<&'t PartitionBound<'t>>) -> Self { + if bound.is_some() { + self.partition_bound = bound; + } + self + } + + pub(crate) fn build_scope(&self, score_director: PD, seed: u64) -> SolverScope<'t, S, PD> + where + PD: Director, + { + let terminate = self + .terminate + .or_else(|| self.runtime.map(|runtime| runtime.cancel_flag())); + let mut scope = SolverScope::new(score_director) + .with_terminate(terminate) + .with_runtime(self.runtime) + .without_publication() + .with_environment_mode(self.environment_mode) + .with_seed(seed); + scope.time_deadline = self.time_deadline; + scope.phase_budget = self.phase_budget; + scope.partition_bound = self.partition_bound; + if self.phase_budget.is_none() { + scope.inphase_step_count_limit = self.inphase_step_count_limit; + scope.inphase_move_count_limit = self.inphase_move_count_limit; + scope.inphase_score_calc_count_limit = self.inphase_score_calc_count_limit; + } + scope.inphase_best_score_limit = self.inphase_best_score_limit; + scope + } +} + +/// The time and step count limits of a partitioned phase. The deadline is +/// the phase's, shared by all partitions; the step count limit applies to +/// each partition's solve, through the per-partition copies +/// [`Self::for_partition`] makes. Reaching one ends a partition's solve the +/// way a phase ends: it keeps its best solution for the merge, and the solve +/// is not terminated. A bound made inside a partition chains to the +/// enclosing one, so the enclosing partition's limits still count the inner +/// partitions' steps. +pub(crate) struct PartitionBound<'p> { + parent: Option<&'p PartitionBound<'p>>, + deadline: Option, + step_count_limit: Option, + step_count: AtomicU64, +} + +impl<'p> PartitionBound<'p> { + /// The bound of a phase with termination `config`, starting now, chained + /// to `parent`; `None` when `config` sets neither a time nor a step + /// count limit. A time limit past what `Instant` represents never ends. + pub(crate) fn new( + parent: Option<&'p PartitionBound<'p>>, + config: Option<&TerminationConfig>, + ) -> Option { + let config = config?; + let time_limit = config.time_limit(); + if time_limit.is_none() && config.step_count_limit.is_none() { + return None; + } + Some(Self { + parent, + deadline: time_limit.and_then(|limit| Instant::now().checked_add(limit)), + step_count_limit: config.step_count_limit, + step_count: AtomicU64::new(0), + }) + } + + /// This bound for one partition: the same deadline, step count limit + /// and enclosing bound, with the partition's own step count. + pub(crate) fn for_partition(&self) -> Self { + Self { + parent: self.parent, + deadline: self.deadline, + step_count_limit: self.step_count_limit, + step_count: AtomicU64::new(0), + } + } + + fn record_step(&self) { + self.step_count.fetch_add(1, Ordering::SeqCst); + if let Some(parent) = self.parent { + parent.record_step(); + } + } + + /// Whether a limit of this bound or an enclosing one is reached. + pub(crate) fn reached(&self) -> bool { + self.deadline + .is_some_and(|deadline| Instant::now() >= deadline) + || self + .step_count_limit + .is_some_and(|limit| self.step_count.load(Ordering::SeqCst) >= limit) + || self.parent.is_some_and(PartitionBound::reached) + } +} + +impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> + SolverScope<'t, S, D, ProgressCb> +{ + pub(crate) fn child_phase_budget(&self) -> PhaseBudget { + PhaseBudget::from_scope(self) + } + + pub(crate) fn child_config<'a>( + &'a self, + phase_budget: Option<&'a PhaseBudget>, + ) -> SolverScopeChildConfig<'a, S> { + let phase_budget = self + .phase_budget + .or_else(|| phase_budget.filter(|budget| budget.has_limits())); + SolverScopeChildConfig { + terminate: self.terminate, + runtime: self.runtime, + environment_mode: self.environment_mode, + time_deadline: self.child_time_deadline(), + phase_budget, + partition_bound: self.partition_bound, + inphase_step_count_limit: self.inphase_step_count_limit, + inphase_move_count_limit: self.inphase_move_count_limit, + inphase_score_calc_count_limit: self.inphase_score_calc_count_limit, + inphase_best_score_limit: self.inphase_best_score_limit, + } + } + + /// The bound of the partitioned phase this scope solves a partition of. + pub(crate) fn partition_bound(&self) -> Option<&'t PartitionBound<'t>> { + self.partition_bound + } + + fn partition_bound_reached(&self) -> bool { + self.partition_bound.is_some_and(PartitionBound::reached) + } +} diff --git a/crates/solverforge-solver/src/scope/solver/scope_core.rs b/crates/solverforge-solver/src/scope/solver/scope_core.rs index 7fa691e1..88f736a0 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_core.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_core.rs @@ -33,6 +33,7 @@ pub struct SolverScope<'t, S: PlanningSolution, D: Director, ProgressCb = ()> working_solution_generation: u64, construction_frontier: ConstructionFrontier, phase_budget: Option<&'t PhaseBudget>, + partition_bound: Option<&'t PartitionBound<'t>>, /// Stops the solve once the total step count reaches this many steps; /// `None` means no limit. pub inphase_step_count_limit: Option, @@ -48,45 +49,6 @@ pub struct SolverScope<'t, S: PlanningSolution, D: Director, ProgressCb = ()> weight_mode_switch_pending: bool, } -#[derive(Clone, Copy)] -pub(crate) struct SolverScopeChildConfig<'t, S: PlanningSolution> { - terminate: Option<&'t AtomicBool>, - runtime: Option>, - environment_mode: EnvironmentMode, - time_deadline: Option, - phase_budget: Option<&'t PhaseBudget>, - inphase_step_count_limit: Option, - inphase_move_count_limit: Option, - inphase_score_calc_count_limit: Option, - inphase_best_score_limit: Option, -} - -impl<'t, S: PlanningSolution> SolverScopeChildConfig<'t, S> { - pub(crate) fn build_scope(&self, score_director: PD, seed: u64) -> SolverScope<'t, S, PD> - where - PD: Director, - { - let terminate = self - .terminate - .or_else(|| self.runtime.map(|runtime| runtime.cancel_flag())); - let mut scope = SolverScope::new(score_director) - .with_terminate(terminate) - .with_runtime(self.runtime) - .without_publication() - .with_environment_mode(self.environment_mode) - .with_seed(seed); - scope.time_deadline = self.time_deadline; - scope.phase_budget = self.phase_budget; - if self.phase_budget.is_none() { - scope.inphase_step_count_limit = self.inphase_step_count_limit; - scope.inphase_move_count_limit = self.inphase_move_count_limit; - scope.inphase_score_calc_count_limit = self.inphase_score_calc_count_limit; - } - scope.inphase_best_score_limit = self.inphase_best_score_limit; - scope - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum PendingControl { Continue, @@ -126,6 +88,7 @@ impl<'t, S: PlanningSolution, D: Director> SolverScope<'t, S, D, ()> { working_solution_generation: 0, construction_frontier, phase_budget: None, + partition_bound: None, inphase_step_count_limit: None, inphase_move_count_limit: None, inphase_score_calc_count_limit: None, @@ -175,6 +138,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> working_solution_generation: 0, construction_frontier, phase_budget: None, + partition_bound: None, inphase_step_count_limit: None, inphase_move_count_limit: None, inphase_score_calc_count_limit: None, @@ -233,30 +197,6 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> self } - pub(crate) fn child_phase_budget(&self) -> PhaseBudget { - PhaseBudget::from_scope(self) - } - - pub(crate) fn child_config<'a>( - &'a self, - phase_budget: Option<&'a PhaseBudget>, - ) -> SolverScopeChildConfig<'a, S> { - let phase_budget = self - .phase_budget - .or_else(|| phase_budget.filter(|budget| budget.has_limits())); - SolverScopeChildConfig { - terminate: self.terminate, - runtime: self.runtime, - environment_mode: self.environment_mode, - time_deadline: self.child_time_deadline(), - phase_budget, - inphase_step_count_limit: self.inphase_step_count_limit, - inphase_move_count_limit: self.inphase_move_count_limit, - inphase_score_calc_count_limit: self.inphase_score_calc_count_limit, - inphase_best_score_limit: self.inphase_best_score_limit, - } - } - /// Runs one configured phase with a phase-relative termination overlay. /// /// The overlay is intentionally independent from solver-wide termination: @@ -353,6 +293,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> working_solution_generation: self.working_solution_generation, construction_frontier: self.construction_frontier, phase_budget: self.phase_budget, + partition_bound: self.partition_bound, inphase_step_count_limit: self.inphase_step_count_limit, inphase_move_count_limit: self.inphase_move_count_limit, inphase_score_calc_count_limit: self.inphase_score_calc_count_limit, diff --git a/crates/solverforge-solver/src/scope/solver/scope_progress.rs b/crates/solverforge-solver/src/scope/solver/scope_progress.rs index 42c4ffbd..09ea35a9 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_progress.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_progress.rs @@ -187,6 +187,9 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> if let Some(phase_budget) = self.phase_budget { phase_budget.record_step(); } + if let Some(bound) = self.partition_bound { + bound.record_step(); + } self.total_step_count } diff --git a/crates/solverforge-solver/src/scope/solver/scope_termination.rs b/crates/solverforge-solver/src/scope/solver/scope_termination.rs index dbfcf738..e9f3d531 100644 --- a/crates/solverforge-solver/src/scope/solver/scope_termination.rs +++ b/crates/solverforge-solver/src/scope/solver/scope_termination.rs @@ -30,7 +30,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> if self.phase_budget_reached() { return PendingControl::ConfigTerminationRequested; } - if self.phase_termination_reached() { + if self.phase_termination_reached() || self.partition_bound_reached() { return PendingControl::ConfigTerminationRequested; } if self.inphase_best_score_limit_reached() { @@ -53,6 +53,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> || self.time_deadline.is_some() || self.phase_budget.is_some() || self.phase_termination.is_some() + || self.partition_bound.is_some() || self.inphase_best_score_limit.is_some() || self.inphase_step_count_limit.is_some() || self.inphase_move_count_limit.is_some() @@ -65,6 +66,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> || self.time_limit_reached() || self.phase_budget_reached() || self.phase_termination_reached() + || self.partition_bound_reached() || self.inphase_best_score_limit_reached() || self.inphase_step_count_limit_reached() || self.inphase_move_count_limit_reached() @@ -113,7 +115,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> self.mark_terminated_by_config(); return true; } - if self.phase_termination_reached() { + if self.phase_termination_reached() || self.partition_bound_reached() { return true; } if self.inphase_best_score_limit_reached() { @@ -151,7 +153,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> self.mark_terminated_by_config(); return true; } - if self.phase_termination_reached() { + if self.phase_termination_reached() || self.partition_bound_reached() { return true; } if self.inphase_best_score_limit_reached() { @@ -173,6 +175,19 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> false } + /// Whether a limit of the solve itself is reached: the time limit, the + /// shared budget, or a best-score, step, move or score-calculation + /// limit. Phase ends — a phase termination or a partition bound — are + /// not limits of the solve. + pub(crate) fn solve_limit_reached(&self) -> bool { + self.time_limit_reached() + || self.phase_budget_reached() + || self.inphase_best_score_limit_reached() + || self.inphase_step_count_limit_reached() + || self.inphase_move_count_limit_reached() + || self.inphase_score_calc_count_limit_reached() + } + /// Records `Cancelled` as the terminal reason unless one is already set. pub fn mark_cancelled(&mut self) { self.terminal_reason diff --git a/crates/solverforge-solver/src/scope/solver/weight_mode.rs b/crates/solverforge-solver/src/scope/solver/weight_mode.rs index 5c71b7b9..dc8788d2 100644 --- a/crates/solverforge-solver/src/scope/solver/weight_mode.rs +++ b/crates/solverforge-solver/src/scope/solver/weight_mode.rs @@ -97,6 +97,7 @@ impl<'t, S: PlanningSolution, D: Director, ProgressCb: ProgressCallback> working_solution_generation: self.working_solution_generation, construction_frontier: self.construction_frontier, phase_budget: self.phase_budget, + partition_bound: self.partition_bound, inphase_step_count_limit: self.inphase_step_count_limit, inphase_move_count_limit: self.inphase_move_count_limit, inphase_score_calc_count_limit: self.inphase_score_calc_count_limit, diff --git a/crates/solverforge-solver/src/scope/tests.rs b/crates/solverforge-solver/src/scope/tests.rs index d339e28d..2239ab16 100644 --- a/crates/solverforge-solver/src/scope/tests.rs +++ b/crates/solverforge-solver/src/scope/tests.rs @@ -471,5 +471,6 @@ fn working_solution_generation_is_monotonic_across_commits_and_replacement() { } mod environment_mode; +mod partition_bound; mod problem_change; mod weight_mode; diff --git a/crates/solverforge-solver/src/scope/tests/partition_bound.rs b/crates/solverforge-solver/src/scope/tests/partition_bound.rs new file mode 100644 index 00000000..accf20f8 --- /dev/null +++ b/crates/solverforge-solver/src/scope/tests/partition_bound.rs @@ -0,0 +1,84 @@ +// The partition bound: a partitioned phase's limits end its partitions' +// solves without terminating the solve, and chain into nested partitions. + +use solverforge_config::TerminationConfig; + +use crate::manager::SolverTerminalReason; +use crate::scope::{PartitionBound, PendingControl, SolverScope}; +use crate::test_utils::create_simple_nqueens_director; + +fn steps(limit: u64) -> TerminationConfig { + TerminationConfig { + step_count_limit: Some(limit), + ..TerminationConfig::default() + } +} + +#[test] +fn a_reached_bound_ends_the_partition_without_terminating_it() { + let parent = SolverScope::new(create_simple_nqueens_director(4)); + let bound = PartitionBound::new(None, Some(&steps(2))).expect("a step limit bounds"); + let budget = parent.child_phase_budget(); + let mut child = parent + .child_config(Some(&budget)) + .with_partition_bound(Some(&bound)) + .build_scope(create_simple_nqueens_director(4), 1); + + child.increment_step_count(); + assert!(!child.should_terminate()); + child.increment_step_count(); + assert!(child.should_terminate()); + assert_eq!( + child.pending_control(), + PendingControl::ConfigTerminationRequested + ); + assert!(!child.solve_limit_reached()); + assert_eq!(child.terminal_reason(), SolverTerminalReason::Completed); +} + +#[test] +fn a_nested_bound_counts_against_the_enclosing_one() { + let outer = PartitionBound::new(None, Some(&steps(3))).expect("a step limit bounds"); + let parent = SolverScope::new(create_simple_nqueens_director(4)); + let budget = parent.child_phase_budget(); + let partition = parent + .child_config(Some(&budget)) + .with_partition_bound(Some(&outer)) + .build_scope(create_simple_nqueens_director(4), 1); + + let inner = PartitionBound::new(partition.partition_bound(), Some(&steps(10))) + .expect("a step limit bounds"); + let inner_budget = partition.child_phase_budget(); + let mut nested = partition + .child_config(Some(&inner_budget)) + .with_partition_bound(Some(&inner)) + .build_scope(create_simple_nqueens_director(4), 2); + + for _ in 0..3 { + assert!(!nested.should_terminate()); + nested.increment_step_count(); + } + assert!( + nested.should_terminate(), + "the enclosing phase's 3 steps are spent" + ); + assert!(outer.reached()); + assert!(!PartitionBound::new(None, Some(&steps(10))) + .unwrap() + .reached()); +} + +#[test] +fn only_time_and_step_limits_make_a_bound() { + assert!(PartitionBound::new(None, None).is_none()); + assert!(PartitionBound::new(None, Some(&TerminationConfig::default())).is_none()); + let bound = PartitionBound::new( + None, + Some(&TerminationConfig { + seconds_spent_limit: Some(0), + ..TerminationConfig::default() + }), + ) + .expect("a time limit bounds"); + assert!(bound.reached(), "a zero time limit is reached at once"); +} diff --git a/crates/solverforge/tests/partitioned_search.rs b/crates/solverforge/tests/partitioned_search.rs index dde6c8b2..88003b04 100644 --- a/crates/solverforge/tests/partitioned_search.rs +++ b/crates/solverforge/tests/partitioned_search.rs @@ -121,3 +121,70 @@ fn empty_child_phases_run_the_default_phases_in_each_partition() { .all(|task| task.resource_idx.is_some())); assert_eq!(solution.score.map(|score| score.hard()), Some(0)); } + +const BOUNDED: &str = r#" +[termination] +seconds_spent_limit = 60 + +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id" +thread_count = "none" + +[phases.termination] +step_count_limit = 12 + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "local_search" + +[phases.child_phases.acceptor] +type = "late_acceptance" +late_acceptance_size = 4 + +[phases.child_phases.move_selector] +type = "change_move_selector" + +[[phases]] +type = "custom" +name = "record" +"#; + +#[test] +fn the_phase_termination_ends_the_partitions_and_keeps_their_work() { + let started = std::time::Instant::now(); + let (job_id, mut receiver) = MANAGER.solve(Plan::new(BOUNDED)).expect("solve starts"); + let (solution, reason) = loop { + match receiver + .blocking_recv() + .expect("event stream should reach a terminal event") + { + SolverEvent::Completed { metadata, solution } => { + break (solution, metadata.terminal_reason) + } + SolverEvent::Failed { error, .. } => panic!("solve failed: {error}"), + SolverEvent::Cancelled { .. } => panic!("solve was cancelled"), + _ => {} + } + }; + MANAGER.delete(job_id).expect("the completed job deletes"); + + // The child local search has no limit of its own: only the phase's 12 + // steps per partition end it, well before the solve's 60 s. + assert!(started.elapsed() < std::time::Duration::from_secs(30)); + assert_eq!(reason, Some(solverforge::SolverTerminalReason::Completed)); + assert!(solution + .tasks + .iter() + .all(|task| task.resource_idx.is_some())); + + // The phase end merged the partitions and the solve went on to the next + // phase, which saw the whole, merged plan. + let records = take_records(BOUNDED); + assert_eq!(records.len(), 1); + assert_eq!(records[0].task_ids, (0..8).collect::>()); + assert!(records[0].all_assigned); +} diff --git a/docs/extend-solver.md b/docs/extend-solver.md index 164a3a73..b75c3446 100644 --- a/docs/extend-solver.md +++ b/docs/extend-solver.md @@ -220,7 +220,12 @@ type = "local_search" Each partition is solved by `child_phases`, compiled exactly like top-level `phases`; an empty list runs the default phases. `thread_count` sets how many partitions are solved at once and `log_progress` logs the phase's start and end. -A partition runs under the solve's time and step count limits. +A partition runs under the solve's time and step count limits. The phase's own +`termination` bounds it too: its time limit, counted from the phase's start, +holds for all partitions, and its step count limit for each partition's solve. +Reaching one ends the phase like any phase end: the partitions are merged and the +solve goes on. `best_score_limit` and the unimproved limits need the merged +solution's score and are rejected on a partitioned phase. Partition children are internal compute scopes, not retained-job publication owners. They inherit cancellation, environment mode, remaining time limit,