diff --git a/crates/solverforge-config/WIREFRAME.md b/crates/solverforge-config/WIREFRAME.md index 4afc7fa4..22712ee9 100644 --- a/crates/solverforge-config/WIREFRAME.md +++ b/crates/solverforge-config/WIREFRAME.md @@ -774,7 +774,7 @@ sizes partitioned search separately. Every policy reaches the sequential trajectory; `auto` changes speed only. `PartitionedSearchConfig::thread_count`: `auto` runs one thread per partition -up to the available CPU cores, `none` one thread, `{ count = n }` at most `n`. +up to the available CPU cores and the partitioner's recommended partition count, `none` one thread, `{ count = n }` at most `n`. ### `PhaseConfig` diff --git a/crates/solverforge-config/src/phase.rs b/crates/solverforge-config/src/phase.rs index c6c1220a..5230bd2f 100644 --- a/crates/solverforge-config/src/phase.rs +++ b/crates/solverforge-config/src/phase.rs @@ -198,7 +198,8 @@ pub struct PartitionedSearchConfig { pub partitioner: Option, /// Threads solving the partitions: `auto` runs one per partition up to the - /// available CPU cores, `none` runs one, and `{ count = n }` at most `n`. + /// available CPU cores and the partitioner's recommended partition count, + /// `none` runs one, and `{ count = n }` at most `n`. #[serde(default)] pub thread_count: MoveThreadCount, diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 98a0ee61..ff149e5b 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -621,7 +621,7 @@ Requires: `Send + Sync + Debug`. Bounds: `S: PlanningSolution`. |--------|-----------|---------| | `partition` | `fn(&self, solution: &S) -> Vec` | — | | `merge` | `fn(&self, original: &S, partitions: Vec) -> S` | — | -| `recommended_partition_count` | `fn(&self) -> Option` | `None` | +| `recommended_partition_count` | `fn(&self) -> Option` | `None`; with `ThreadCount::Auto`, partitioned search runs at most this many threads | ### `CrossEntityDistanceMeter` — `nearby_list_change.rs` @@ -719,7 +719,7 @@ working solution without cloning. **`FunctionalPartitioner`** — Closure-based partitioner. -**`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. +**`ThreadCount`** — `resolve(partition_count, recommended)`. `Auto` (one thread per partition, at most one per available core and at most the partitioner's `recommended_partition_count`), `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, 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. diff --git a/crates/solverforge-solver/public-api.txt b/crates/solverforge-solver/public-api.txt index b1c96351..23393eb1 100644 --- a/crates/solverforge-solver/public-api.txt +++ b/crates/solverforge-solver/public-api.txt @@ -75,7 +75,7 @@ struct ExhaustiveSearchPhase: pub struct ExhaustiveSearchPhase { /* private ExhaustiveSearchPhase: pub fn phase_type_name(&self) -> &'static str struct FunctionalPartitioner: pub struct FunctionalPartitioner where S: PlanningSolution, PF: Fn(&S) -> Vec + Send + Sync, MF: Fn(&S, Vec) -> S + Send + Sync,{ /* private fields */ } FunctionalPartitioner: pub fn new(partition_fn: PF, merge_fn: MF) -> Self - FunctionalPartitioner: pub fn with_recommended_count(self, count: usize) -> Self + FunctionalPartitioner: pub fn with_recommended_count(self, count: NonZeroUsize) -> Self struct ListVariableMetadata: pub struct ListVariableMetadata { pub cross_distance_meter: DM, pub intra_distance_meter: IDM, pub route_get_fn: Option Vec>, pub route_set_fn: Option)>, pub route_depot_fn: Option usize>, pub route_distance_fn: Option i64>, pub route_feasible_fn: Option bool>, pub savings_depot_fn: Option usize>, pub savings_metric_class_fn: Option usize>, pub savings_distance_fn: Option i64>, pub savings_feasible_fn: Option bool>, pub element_owner_fn: Option Option>, /* private fields */ } ListVariableMetadata: pub fn new( cross_distance_meter: DM, intra_distance_meter: IDM, route_get_fn: Option Vec>, route_set_fn: Option)>, route_depot_fn: Option usize>, route_distance_fn: Option i64>, route_feasible_fn: Option bool>, savings_depot_fn: Option usize>, savings_metric_class_fn: Option usize>, savings_distance_fn: Option i64>, savings_feasible_fn: Option bool>, ) -> Self ListVariableMetadata: pub fn with_element_owner_fn( self, element_owner_fn: Option Option>, ) -> Self @@ -563,7 +563,7 @@ enum SolverManagerError: pub enum SolverManagerError { NoFreeJobSlots, JobNotFou enum SolverProgressKind: pub enum SolverProgressKind { Progress, BestSolution, } enum SolverTerminalReason: pub enum SolverTerminalReason { Completed, TerminatedByConfig, Cancelled, Failed, } enum ThreadCount: pub enum ThreadCount { Auto, Unlimited, Specific(NonZeroUsize), } - ThreadCount: pub fn resolve(&self, partition_count: usize) -> usize + ThreadCount: pub fn resolve( &self, partition_count: usize, recommended: Option, ) -> usize enum ValueSource: pub enum ValueSource { Empty, CountableRange { from: usize, to: usize, }, SolutionCount { count_fn: fn(&S, usize) -> usize, provider_index: usize, }, EntitySlice { values_for_entity: for<'a> fn(&'a S, usize, usize) -> &'a [usize], }, } enum VariableSlot: pub enum VariableSlot { Scalar(ScalarVariableSlot), List(ListVariableSlot), DynamicScalar(DynamicScalarVariableSlot), DynamicList(DynamicListVariableSlot), } trait Acceptor: pub trait Acceptor: Send + Debug { // Required method fn is_accepted( &mut self, last_step_score: &S::Score, move_score: &S::Score, move_signature: Option<&MoveTabuSignature>, ) -> bool; // Provided methods fn requires_move_signatures(&self) -> bool { ... } fn phase_started(&mut self, _initial_score: &S::Score) { ... } fn phase_ended(&mut self) { ... } fn step_started(&mut self) { ... } fn step_ended( &mut self, _step_score: &S::Score, _accepted_move_signature: Option, ) { ... } } @@ -656,10 +656,10 @@ trait ScoreBounder: pub trait ScoreBounder>: ScoreBounder: fn calculate_pessimistic_bound(&self, score_director: &D) -> Option trait Search: pub trait Search where S: PlanningSolution + 'static, S::Score: Score + ParseableScore, V: Clone + Copy + PartialEq + Eq + Hash + Into + Send + Sync + Debug + 'static, DM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static, IDM: CrossEntityDistanceMeter + Clone + Debug + Send + 'static,{ type Extensions: RuntimeExtensionRegistry; } Search: type Extensions: RuntimeExtensionRegistry -trait SolutionPartitioner: pub trait SolutionPartitioner: Send + Sync + Debug { // Required methods fn partition(&self, solution: &S) -> Vec; fn merge(&self, original: &S, partitions: Vec) -> S; // Provided method fn recommended_partition_count(&self) -> Option { ... } } +trait SolutionPartitioner: pub trait SolutionPartitioner: Send + Sync + Debug { // Required methods fn partition(&self, solution: &S) -> Vec; fn merge(&self, original: &S, partitions: Vec) -> S; // Provided method fn recommended_partition_count(&self) -> Option { ... } } SolutionPartitioner: fn partition(&self, solution: &S) -> Vec SolutionPartitioner: fn merge(&self, original: &S, partitions: Vec) -> S - SolutionPartitioner: fn recommended_partition_count(&self) -> Option + SolutionPartitioner: fn recommended_partition_count(&self) -> Option trait Solvable: pub trait Solvable: PlanningSolution + Send + 'static { // Required method fn solve( self, runtime: SolverRuntime, qualified_candidate_trace_provenance: Option, ) -> RuntimeBuildResult<()>; } Solvable: fn solve( self, runtime: SolverRuntime, qualified_candidate_trace_provenance: Option, ) -> RuntimeBuildResult<()> fn analyze: pub fn analyze(solution: &S) -> ScoreAnalysis where S: Analyzable, S::Score: Score, diff --git a/crates/solverforge-solver/src/builder/search/partitioner.rs b/crates/solverforge-solver/src/builder/search/partitioner.rs index f4aa0c86..15ea147b 100644 --- a/crates/solverforge-solver/src/builder/search/partitioner.rs +++ b/crates/solverforge-solver/src/builder/search/partitioner.rs @@ -92,7 +92,7 @@ where } } - fn recommended_partition_count(&self) -> Option { + fn recommended_partition_count(&self) -> Option { match self { Self::Previous(partitioner) => partitioner.recommended_partition_count(), Self::Current(partitioner) => partitioner.recommended_partition_count(), diff --git a/crates/solverforge-solver/src/phase/partitioned/config.rs b/crates/solverforge-solver/src/phase/partitioned/config.rs index bbc6dd8a..db4b876b 100644 --- a/crates/solverforge-solver/src/phase/partitioned/config.rs +++ b/crates/solverforge-solver/src/phase/partitioned/config.rs @@ -26,7 +26,8 @@ impl Default for PartitionedSearchConfig { impl PartitionedSearchConfig { /// Converts the TOML configuration: thread count `auto` is one thread per - /// partition up to the available CPU cores, `none` is one thread, and an + /// partition up to the available CPU cores and the partitioner's + /// recommended partition count, `none` is one thread, and an /// explicit count is at most that many threads. pub fn from_serialized(config: &solverforge_config::PartitionedSearchConfig) -> Self { Self { diff --git a/crates/solverforge-solver/src/phase/partitioned/execution.rs b/crates/solverforge-solver/src/phase/partitioned/execution.rs index e9bd3b8b..f5ccc07e 100644 --- a/crates/solverforge-solver/src/phase/partitioned/execution.rs +++ b/crates/solverforge-solver/src/phase/partitioned/execution.rs @@ -71,7 +71,9 @@ pub(crate) fn solve_partitioned: Send + Sync + Debug { /// The merged complete solution. fn merge(&self, original: &S, partitions: Vec) -> S; - /// Returns the recommended number of partitions. - /// - /// This can be used by the partitioned search phase to determine - /// how many threads to use. Returns `None` if no recommendation. - fn recommended_partition_count(&self) -> Option { + /// The number of partitions worth solving at once, if this partitioner + /// knows it. With [`ThreadCount::Auto`], partitioned search runs at most + /// this many threads; an explicit thread count is unaffected. + fn recommended_partition_count(&self) -> Option { None } } @@ -75,7 +74,7 @@ where { partition_fn: PF, merge_fn: MF, - recommended_count: Option, + recommended_count: Option, _phantom: std::marker::PhantomData S>, } @@ -95,8 +94,9 @@ where } } - /// Sets the recommended partition count. - pub fn with_recommended_count(mut self, count: usize) -> Self { + /// Sets the recommended partition count (see + /// [`SolutionPartitioner::recommended_partition_count`]). + pub fn with_recommended_count(mut self, count: NonZeroUsize) -> Self { self.recommended_count = Some(count); self } @@ -129,7 +129,7 @@ where (self.merge_fn)(original, partitions) } - fn recommended_partition_count(&self) -> Option { + fn recommended_partition_count(&self) -> Option { self.recommended_count } } @@ -137,7 +137,8 @@ where /// Thread count configuration for partitioned search. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ThreadCount { - /// One thread per partition, at most one per available CPU core. + /// One thread per partition, at most one per available CPU core and at + /// most the partitioner's recommended partition count. #[default] Auto, /// One thread per available CPU core. @@ -147,22 +148,17 @@ pub enum ThreadCount { } impl ThreadCount { - /// Resolves the thread count to an actual number. - /// - /// # Arguments - /// - /// * `partition_count` - Number of partitions to process - /// - /// # Returns - /// - /// The number of threads to use. - pub fn resolve(&self, partition_count: usize) -> usize { + /// The number of threads that solve `partition_count` partitions, given + /// the partitioner's `recommended` partition count, which only bounds + /// [`ThreadCount::Auto`]. + pub fn resolve(&self, partition_count: usize, recommended: Option) -> usize { match self { ThreadCount::Auto => { let cpus = std::thread::available_parallelism() .map(|p| p.get()) .unwrap_or(1); - std::cmp::min(cpus, partition_count) + let recommended = recommended.map_or(usize::MAX, NonZeroUsize::get); + cpus.min(partition_count).min(recommended) } ThreadCount::Unlimited => std::thread::available_parallelism() .map(|p| p.get()) diff --git a/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs b/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs index eebb291e..44204da8 100644 --- a/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs +++ b/crates/solverforge-solver/src/phase/partitioned/partitioner_tests.rs @@ -40,21 +40,34 @@ fn test_thread_count_display() { #[test] fn test_thread_count_resolve_specific() { assert_eq!( - ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10), + ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10, None), 4 ); assert_eq!( - ThreadCount::Specific(std::num::NonZeroUsize::new(10).unwrap()).resolve(4), + ThreadCount::Specific(std::num::NonZeroUsize::new(10).unwrap()).resolve(4, None), 4 ); } #[test] fn test_thread_count_resolve_auto() { - let count = ThreadCount::Auto.resolve(100); + let count = ThreadCount::Auto.resolve(100, None); assert!(count > 0); } +#[test] +fn a_recommended_partition_count_bounds_only_auto() { + let two = std::num::NonZeroUsize::new(2); + let cores = std::thread::available_parallelism().map_or(1, |cores| cores.get()); + assert_eq!(ThreadCount::Auto.resolve(100, two), cores.min(2)); + assert_eq!(ThreadCount::Auto.resolve(1, two), 1); + assert_eq!( + ThreadCount::Specific(std::num::NonZeroUsize::new(4).unwrap()).resolve(10, two), + 4 + ); + assert_eq!(ThreadCount::Unlimited.resolve(10, two), cores); +} + #[test] fn test_functional_partitioner() { let partitioner = FunctionalPartitioner::new( @@ -103,7 +116,7 @@ fn test_partitioner_debug() { |_: &TestSolution| Vec::new(), |original: &TestSolution, _| original.clone(), ) - .with_recommended_count(4); + .with_recommended_count(std::num::NonZeroUsize::new(4).unwrap()); let debug = format!("{:?}", partitioner); assert!(debug.contains("FunctionalPartitioner")); diff --git a/crates/solverforge/tests/partitioned_search.rs b/crates/solverforge/tests/partitioned_search.rs index 88003b04..acd8053a 100644 --- a/crates/solverforge/tests/partitioned_search.rs +++ b/crates/solverforge/tests/partitioned_search.rs @@ -188,3 +188,35 @@ fn the_phase_termination_ends_the_partitions_and_keeps_their_work() { assert_eq!(records[0].task_ids, (0..8).collect::>()); assert!(records[0].all_assigned); } + +const RECOMMENDED: &str = r#" +[[phases]] +type = "partitioned_search" +partitioner = "by_task_id_two_at_once" + +[[phases.child_phases]] +type = "construction_heuristic" +construction_heuristic_type = "first_fit" + +[[phases.child_phases]] +type = "custom" +name = "record" +"#; + +#[test] +fn auto_threads_follow_the_recommended_partition_count() { + let solution = solve(Plan::new(RECOMMENDED)); + assert!(solution + .tasks + .iter() + .all(|task| task.resource_idx.is_some())); + + let records = take_records(RECOMMENDED); + assert_eq!(records.len(), 4); + let cores = std::thread::available_parallelism().map_or(1, |cores| cores.get()); + let expected = cores.min(2); + if expected > 1 { + assert!(records.iter().all(|record| record.pool_threads == expected)); + } + assert!(distinct_threads(&records) <= expected); +} diff --git a/crates/solverforge/tests/partitioned_search/domain/plan.rs b/crates/solverforge/tests/partitioned_search/domain/plan.rs index a8ef6d67..32e5a547 100644 --- a/crates/solverforge/tests/partitioned_search/domain/plan.rs +++ b/crates/solverforge/tests/partitioned_search/domain/plan.rs @@ -73,6 +73,7 @@ where ctx.defaults() .phase("record", |_| RecordPhase) .partitioner("by_task_id", |_| ByTaskId) + .partitioner("by_task_id_two_at_once", |_| TwoAtOnce) } /// Splits the tasks by id modulo [`PARTITIONS`]; every partition keeps all @@ -105,6 +106,24 @@ impl SolutionPartitioner for ByTaskId { } } +/// [`ByTaskId`], recommending two partitions at once. +#[derive(Debug)] +struct TwoAtOnce; + +impl SolutionPartitioner for TwoAtOnce { + fn partition(&self, solution: &Plan) -> Vec { + ByTaskId.partition(solution) + } + + fn merge(&self, original: &Plan, partitions: Vec) -> Plan { + ByTaskId.merge(original, partitions) + } + + fn recommended_partition_count(&self) -> Option { + std::num::NonZeroUsize::new(2) + } +} + /// What the `record` child phase saw in one partition. #[derive(Clone, Debug)] pub struct Record {