From ff11cd47ea1789877f7603fd520e48172e264d9d Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Thu, 5 Nov 2026 06:47:32 +0100 Subject: [PATCH] test(construction): pin what each scalar construction heuristic assigns No test solved with first_fit_decreasing, weakest_fit, weakest_fit_decreasing, strongest_fit, strongest_fit_decreasing, allocate_entity_from_queue or allocate_to_value_from_queue and checked the result, so mapping one heuristic to another's entity order, value order or forager passed every test. One solve per scalar construction heuristic now asserts its assignment on a domain where every heuristic's documented order and forager gives a different result, plus two solves whose order keys change as construction assigns: one pins the per-step entity re-sort (live refresh), the other the per-placement value order. Removing each heuristic's entity order, value order, forager choice or live refresh fails at least one of them. Closes #203. --- .../tests/construction_heuristics.rs | 129 ++++++++++++++++++ .../construction_heuristics/domain/mod.rs | 11 ++ .../construction_heuristics/domain/plan.rs | 103 ++++++++++++++ .../construction_heuristics/domain/task.rs | 42 ++++++ .../construction_heuristics/domain/worker.rs | 13 ++ 5 files changed, 298 insertions(+) create mode 100644 crates/solverforge/tests/construction_heuristics.rs create mode 100644 crates/solverforge/tests/construction_heuristics/domain/mod.rs create mode 100644 crates/solverforge/tests/construction_heuristics/domain/plan.rs create mode 100644 crates/solverforge/tests/construction_heuristics/domain/task.rs create mode 100644 crates/solverforge/tests/construction_heuristics/domain/worker.rs diff --git a/crates/solverforge/tests/construction_heuristics.rs b/crates/solverforge/tests/construction_heuristics.rs new file mode 100644 index 00000000..2d561bf4 --- /dev/null +++ b/crates/solverforge/tests/construction_heuristics.rs @@ -0,0 +1,129 @@ +//! Each scalar construction heuristic assigns in its documented entity +//! order, value order and forager. Tasks have difficulties 1, 3, 2; workers +//! have strengths 2, 0, 1 plus `load_weight` per task already on them and +//! costs 3, 2, 1; a task only goes to a free worker. + +use solverforge::{SolverEvent, SolverManager}; + +#[path = "construction_heuristics/domain/mod.rs"] +mod domain; + +use domain::Plan; + +static MANAGER: SolverManager = SolverManager::new(); + +fn construct(heuristic: &'static str, load_weight: i64) -> Vec> { + construct_plan(Plan::new(heuristic, load_weight)) +} + +fn construct_plan(plan: Plan) -> Vec> { + let heuristic = plan.heuristic; + 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!("{heuristic} failed: {error}"), + SolverEvent::Cancelled { .. } => panic!("{heuristic} was cancelled"), + _ => {} + } + }; + MANAGER.delete(job_id).expect("the completed job deletes"); + solution.workers_by_task() +} + +#[test] +fn first_fit_takes_tasks_in_order_and_the_first_free_worker() { + assert_eq!(construct("first_fit", 0), [Some(0), Some(1), Some(2)]); +} + +#[test] +fn first_fit_decreasing_takes_the_hardest_task_first() { + // Tasks 1, 2, 0 in that order, each on the first free worker. + assert_eq!( + construct("first_fit_decreasing", 0), + [Some(2), Some(0), Some(1)] + ); +} + +#[test] +fn allocate_entity_from_queue_takes_the_easiest_task_first() { + // Tasks 0, 2, 1. + assert_eq!( + construct("allocate_entity_from_queue", 0), + [Some(0), Some(2), Some(1)] + ); +} + +#[test] +fn allocate_to_value_from_queue_offers_the_weakest_worker_first() { + // Workers in strength order 1, 2, 0. + assert_eq!( + construct("allocate_to_value_from_queue", 0), + [Some(1), Some(2), Some(0)] + ); +} + +#[test] +fn weakest_fit_picks_the_weakest_free_worker() { + // Loaded workers get stronger, so the weakest is always a free one: + // task 0 → 1, task 1 → 2, task 2 → 0. + assert_eq!(construct("weakest_fit", 10), [Some(1), Some(2), Some(0)]); +} + +#[test] +fn weakest_fit_decreasing_picks_the_weakest_worker_for_the_hardest_task() { + // Task 1 → 1, task 2 → 2, task 0 → 0. + assert_eq!( + construct("weakest_fit_decreasing", 10), + [Some(0), Some(1), Some(2)] + ); +} + +#[test] +fn strongest_fit_picks_the_strongest_free_worker() { + // Loaded workers get weaker: task 0 → 0, task 1 → 2, task 2 → 1. + assert_eq!(construct("strongest_fit", -10), [Some(0), Some(2), Some(1)]); +} + +#[test] +fn strongest_fit_decreasing_picks_the_strongest_worker_for_the_hardest_task() { + // Task 1 → 0, task 2 → 2, task 0 → 1. + assert_eq!( + construct("strongest_fit_decreasing", -10), + [Some(1), Some(0), Some(2)] + ); +} + +#[test] +fn cheapest_insertion_picks_the_best_scoring_worker() { + // The cheapest free worker: task 0 → 2, task 1 → 1, task 2 → 0. + assert_eq!( + construct("cheapest_insertion", 0), + [Some(2), Some(1), Some(0)] + ); +} + +#[test] +fn allocate_to_value_from_queue_reorders_the_workers_after_each_assignment() { + // Worker 0's key falls by 10 per assigned task: after task 0 takes + // worker 1, worker 0 comes before worker 2 for task 1. + let plan = Plan { + drift: -10, + ..Plan::new("allocate_to_value_from_queue", 0) + }; + assert_eq!(construct_plan(plan), [Some(1), Some(0), Some(2)]); +} + +#[test] +fn first_fit_decreasing_reorders_the_tasks_after_each_assignment() { + // Task 0's difficulty rises by 10 per assigned task: after task 1 takes + // worker 0, task 0 comes before task 2. + let plan = Plan { + difficulty_drift: 10, + ..Plan::new("first_fit_decreasing", 0) + }; + assert_eq!(construct_plan(plan), [Some(1), Some(0), Some(2)]); +} diff --git a/crates/solverforge/tests/construction_heuristics/domain/mod.rs b/crates/solverforge/tests/construction_heuristics/domain/mod.rs new file mode 100644 index 00000000..5072fa55 --- /dev/null +++ b/crates/solverforge/tests/construction_heuristics/domain/mod.rs @@ -0,0 +1,11 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/construction_heuristics/domain"; + + mod plan; + mod task; + mod worker; + + pub use plan::Plan; + pub use task::Task; + pub use worker::Worker; +} diff --git a/crates/solverforge/tests/construction_heuristics/domain/plan.rs b/crates/solverforge/tests/construction_heuristics/domain/plan.rs new file mode 100644 index 00000000..a7e1eba7 --- /dev/null +++ b/crates/solverforge/tests/construction_heuristics/domain/plan.rs @@ -0,0 +1,103 @@ +use solverforge::prelude::*; +use solverforge::stream::{joiner::equal, ConstraintFactory}; +use solverforge::SolverConfig; + +use super::{Task, Worker}; + +#[planning_solution(constraints = "constraints", config = "solver_config")] +pub struct Plan { + #[problem_fact_collection] + pub workers: Vec, + + #[planning_entity_collection] + pub tasks: Vec, + + #[planning_score] + pub score: Option, + + /// How much each assigned task moves its worker's strength key. + pub load_weight: i64, + + /// How much each assigned task moves worker 0's strength key. + pub drift: i64, + + /// How much each assigned task moves task 0's difficulty key. + pub difficulty_drift: i64, + + pub heuristic: &'static str, +} + +impl Plan { + /// Three tasks with difficulties 1, 3, 2 and three workers with + /// strengths 2, 0, 1 and costs 3, 2, 1. + pub fn new(heuristic: &'static str, load_weight: i64) -> Self { + Self { + workers: [2, 0, 1] + .into_iter() + .enumerate() + .map(|(id, strength)| Worker { + id, + strength, + cost: 3 - id as i64, + }) + .collect(), + tasks: [1, 3, 2] + .into_iter() + .enumerate() + .map(|(id, difficulty)| Task { + id, + difficulty, + worker: None, + }) + .collect(), + score: None, + load_weight, + drift: 0, + difficulty_drift: 0, + heuristic, + } + } + + pub fn workers_by_task(&self) -> Vec> { + self.tasks.iter().map(|task| task.worker).collect() + } +} + +fn solver_config(plan: &Plan, _base: SolverConfig) -> SolverConfig { + SolverConfig::from_toml_str(&format!( + "[[phases]]\ntype = \"construction_heuristic\"\nconstruction_heuristic_type = \"{}\"\n", + plan.heuristic + )) + .expect("the test config parses") +} + +/// An unassigned task costs one hard point and two tasks sharing a worker +/// two, so a task goes only to a free worker; each assigned task costs its +/// worker's soft cost. +fn constraints() -> impl ConstraintSet { + ( + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .filter(|task: &Task| task.worker.is_none()) + .penalize(HardSoftScore::ONE_HARD) + .named("unassigned task"), + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .join(equal(|task: &Task| task.worker)) + .penalize(|left: &Task, _right: &Task| { + HardSoftScore::of(if left.worker.is_some() { 2 } else { 0 }, 0) + }) + .named("shared worker"), + ConstraintFactory::::new() + .for_each(Plan::tasks()) + .join(( + Plan::workers(), + solverforge::stream::joiner::equal_bi( + |task: &Task| task.worker, + |worker: &Worker| Some(worker.id), + ), + )) + .penalize(|_task: &Task, worker: &Worker| HardSoftScore::of_soft(worker.cost)) + .named("worker cost"), + ) +} diff --git a/crates/solverforge/tests/construction_heuristics/domain/task.rs b/crates/solverforge/tests/construction_heuristics/domain/task.rs new file mode 100644 index 00000000..796bfc05 --- /dev/null +++ b/crates/solverforge/tests/construction_heuristics/domain/task.rs @@ -0,0 +1,42 @@ +use solverforge::prelude::*; + +use super::Plan; + +#[planning_entity] +pub struct Task { + #[planning_id] + pub id: usize, + + /// Construction difficulty: task 1 is the hardest, task 0 the easiest. + pub difficulty: i64, + + #[planning_variable( + value_range_provider = "workers", + allows_unassigned = true, + construction_entity_order_key = "task_difficulty", + construction_value_order_key = "worker_strength" + )] + pub worker: Option, +} + +/// A task's difficulty, moved for task 0 only by `difficulty_drift` for +/// every assigned task. +pub(super) fn task_difficulty(plan: &Plan, task: &Task) -> i64 { + let assigned = plan.tasks.iter().filter(|task| task.worker.is_some()).count() as i64; + let drift = if task.id == 0 { plan.difficulty_drift * assigned } else { 0 }; + task.difficulty + drift +} + +/// A worker's base strength, moved by `load_weight` for every task already +/// on it and, for worker 0 only, by `drift` for every assigned task, so the +/// key changes as construction assigns. +pub(super) fn worker_strength(plan: &Plan, _task: &Task, worker: usize) -> i64 { + let load = plan + .tasks + .iter() + .filter(|task| task.worker == Some(worker)) + .count() as i64; + let assigned = plan.tasks.iter().filter(|task| task.worker.is_some()).count() as i64; + let drift = if worker == 0 { plan.drift * assigned } else { 0 }; + plan.workers[worker].strength + plan.load_weight * load + drift +} diff --git a/crates/solverforge/tests/construction_heuristics/domain/worker.rs b/crates/solverforge/tests/construction_heuristics/domain/worker.rs new file mode 100644 index 00000000..b5af079b --- /dev/null +++ b/crates/solverforge/tests/construction_heuristics/domain/worker.rs @@ -0,0 +1,13 @@ +use solverforge::prelude::*; + +#[problem_fact] +pub struct Worker { + #[planning_id] + pub id: usize, + + /// Base strength: worker 1 is the weakest, worker 0 the strongest. + pub strength: i64, + + /// Soft cost of each task on this worker: worker 2 is the cheapest. + pub cost: i64, +}