diff --git a/AGENTS.md b/AGENTS.md index 39170205..e17e9f5e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -301,6 +301,11 @@ runs: - The descriptor-placement scalar construction placer (`RuntimeScalarConstructionPlacer`) and the compiled runtime phase runner that solves first-fit construction. +- Grouped-scalar required construction (`assignment_required`): the default + runtime's dense required batch over an assignment group with capacity, + sequence and rule keys, solved through the compiled runtime runner; and the + compiled grouped-scalar local-search neighborhood of the same group + (`assignment_neighborhood`), including its augmenting-path repairs. - Route moves executed against a scored model: the score director's cascading list-shadow row maintenance (`route_rows`), and grouped list ruin-and-recreate with joint placement of each element group diff --git a/crates/solverforge-solver/benches/selector_cursor_gate.rs b/crates/solverforge-solver/benches/selector_cursor_gate.rs index d2768b4d..68b4835e 100644 --- a/crates/solverforge-solver/benches/selector_cursor_gate.rs +++ b/crates/solverforge-solver/benches/selector_cursor_gate.rs @@ -18,11 +18,11 @@ use std::time::Instant; use solverforge_config::{ CartesianProductConfig, ChangeMoveConfig, ConstructionHeuristicConfig, - ConstructionHeuristicType, KOptMoveSelectorConfig, ListChangeMoveConfig, ListSwapMoveConfig, - LocalSearchConfig, MoveSelectorConfig, NearbyListChangeMoveConfig, NearbyListSwapMoveConfig, - PhaseConfig, RuinRecreateMoveSelectorConfig, SelectionOrder, SolverConfig, - SublistChangeMoveConfig, SublistSwapMoveConfig, SwapMoveConfig, UnionMoveSelectorConfig, - VariableTargetConfig, + ConstructionHeuristicType, GroupedScalarMoveSelectorConfig, KOptMoveSelectorConfig, + ListChangeMoveConfig, ListSwapMoveConfig, LocalSearchConfig, MoveSelectorConfig, + NearbyListChangeMoveConfig, NearbyListSwapMoveConfig, PhaseConfig, + RuinRecreateMoveSelectorConfig, SelectionOrder, SolverConfig, SublistChangeMoveConfig, + SublistSwapMoveConfig, SwapMoveConfig, UnionMoveSelectorConfig, VariableTargetConfig, }; use solverforge_core::domain::{ EntityCollectionExtractor, EntityDescriptor, PlanningSolution, SolutionDescriptor, @@ -33,8 +33,9 @@ use solverforge_scoring::ScoreDirector; use solverforge_solver::__bench::{CandidateVisitor, CompiledNeighborhood, CompiledRuntimeRunner}; use solverforge_solver::{ CandidateTraceCoordinate, CandidateTraceIdentity, CrossEntityDistanceMeter, ListVariableSlot, - Move, MoveCandidateRef, MoveStreamContext, Phase, RuntimeModel, ScalarVariableSlot, - SearchContext, SolverScope, ValueSource, VariableSlot, + Move, MoveCandidateRef, MoveStreamContext, Phase, RuntimeModel, ScalarGroup, + ScalarGroupBinding, ScalarTarget, ScalarVariableSlot, SearchContext, SolverScope, ValueSource, + VariableSlot, }; struct MeasuringAllocator; @@ -148,6 +149,7 @@ include!("selector_cursor_gate/neighborhood_driver.rs"); include!("selector_cursor_gate/list_cases.rs"); include!("selector_cursor_gate/scalar_cases.rs"); include!("selector_cursor_gate/construction_cases.rs"); +include!("selector_cursor_gate/assignment_cases.rs"); include!("selector_cursor_gate/scoring_cases.rs"); include!("selector_cursor_gate/route_model.rs"); include!("selector_cursor_gate/route_cases.rs"); @@ -189,6 +191,13 @@ fn main() { "construction_first_fit", construction_first_fit ); + run_case!(case, matched, "assignment_required", assignment_required); + run_case!( + case, + matched, + "assignment_neighborhood", + assignment_neighborhood + ); run_case!(case, matched, "route_rows", route_rows); run_case!(case, matched, "group_ruin", group_ruin); run_case!(case, matched, "scoring", scoring); diff --git a/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs b/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs new file mode 100644 index 00000000..2859ec4d --- /dev/null +++ b/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs @@ -0,0 +1,182 @@ +/* Grouped-scalar required construction through the compiled runtime. + +`assignment_required` solves a rostering-shaped assignment group with the +default runtime: every shift is a required row, a nurse holds one shift per +day (capacity key), the day is the sequence key, and a late shift may not +precede an early shift of the same nurse on the next day (assignment rule). +The default runtime commits the dense required batch first and finishes any +row the batch could not place with the required cursor, which is the work a +generated rostering model pays before local search. + +`assignment_neighborhood` enumerates the compiled grouped-scalar +local-search neighborhood of the same group over the constructed roster: +every assignment family a grouped local-search step opens, including the +augmenting-path repairs that discover through the pending-assignment overlay. The configuration sets no +termination, so the default runtime ends the solve after construction. The +cross-tree order hash is the constructed roster. */ + +const ASSIGNMENT_DAYS: usize = 28; +const ASSIGNMENT_SHIFTS_PER_DAY: usize = 18; +const ASSIGNMENT_NURSES: usize = 24; +const ASSIGNMENT_ROWS: usize = ASSIGNMENT_DAYS * ASSIGNMENT_SHIFTS_PER_DAY; +const ASSIGNMENT_NEIGHBORHOOD_CANDIDATES: usize = 2_016; + +fn assignment_day(entity: usize) -> usize { + entity / ASSIGNMENT_SHIFTS_PER_DAY +} + +fn assignment_shift_type(entity: usize) -> usize { + entity % ASSIGNMENT_SHIFTS_PER_DAY % 3 +} + +fn assignment_row_required(_: &Plan, _: usize) -> bool { + true +} + +fn assignment_capacity_key(_: &Plan, entity: usize, nurse: usize) -> Option { + Some(nurse * ASSIGNMENT_DAYS + assignment_day(entity)) +} + +fn assignment_sequence_key(_: &Plan, entity: usize, _: usize) -> Option { + Some(assignment_day(entity)) +} + +fn assignment_rule( + _: &Plan, + left: usize, + left_nurse: usize, + right: usize, + right_nurse: usize, +) -> bool { + left_nurse != right_nurse + || assignment_day(left) + 1 != assignment_day(right) + || !(assignment_shift_type(left) == 2 && assignment_shift_type(right) == 0) +} + +fn assignment_nurse(entity: &dyn std::any::Any) -> Option { + entity + .downcast_ref::() + .expect("an assignment row is a Vehicle") + .visits + .first() + .copied() +} + +fn assign_nurse(entity: &mut dyn std::any::Any, nurse: Option) { + let visits = &mut entity + .downcast_mut::() + .expect("an assignment row is a Vehicle") + .visits; + visits.clear(); + visits.extend(nurse); +} + +fn assignment_variables() -> [VariableDescriptor; 1] { + [VariableDescriptor::genuine("first") + .with_allows_unassigned(true) + .with_usize_accessors(assignment_nurse, assign_nurse)] +} + +fn assignment_slot() -> ScalarVariableSlot { + ScalarVariableSlot::new( + 0, + 0, + "Vehicle", + entity_count, + "first", + first_get, + first_set, + ValueSource::CountableRange { + from: 0, + to: ASSIGNMENT_NURSES, + }, + true, + ) +} + +fn assignment_context() -> Context { + let slot = assignment_slot(); + let group = ScalarGroupBinding::bind( + ScalarGroup::assignment( + "shift_assignment", + ScalarTarget::from_descriptor_index(0, "first"), + ) + .with_required_entity(assignment_row_required) + .with_capacity_key(assignment_capacity_key) + .with_sequence_key(assignment_sequence_key) + .with_assignment_rule(assignment_rule), + &[slot], + ); + SearchContext::new( + descriptor(&assignment_variables()), + RuntimeModel::new(vec![VariableSlot::Scalar(slot)]).with_scalar_groups(vec![group]), + Some(SEED), + ) + .expect("the assignment gate model must bind to its descriptor") +} + +fn assignment_config() -> SolverConfig { + SolverConfig { + random_seed: Some(SEED), + ..SolverConfig::default() + } +} + +fn assignment_runner() -> Runner { + Runner::compile(&assignment_config(), assignment_context()) + .expect("the assignment gate configuration must compile") +} + +fn assignment_required() { + let mut runners = (0..iterations()) + .map(|_| assignment_runner()) + .collect::>(); + let variables = assignment_variables(); + emit("assignment_required", ASSIGNMENT_ROWS, || { + let mut count = 0; + let mut roster = FNV_OFFSET; + for runner in &mut runners { + let mut scope = + SolverScope::new(plan_director(unassigned_plan(ASSIGNMENT_ROWS), &variables)); + scope.start_solving(); + runner.solve(&mut scope); + for shift in &scope.working_solution().vehicles { + let nurse = *shift + .visits + .first() + .expect("required construction assigns every shift"); + mix(&mut roster, nurse); + count += 1; + } + } + (count, roster, roster) + }); +} + +/* The roster the default runtime constructs; local search starts here. */ +fn assignment_roster() -> Plan { + let variables = assignment_variables(); + let mut scope = SolverScope::new(plan_director(unassigned_plan(ASSIGNMENT_ROWS), &variables)); + scope.start_solving(); + assignment_runner().solve(&mut scope); + scope.working_solution().clone() +} + +fn assignment_neighborhood() { + neighborhood_case( + "assignment_neighborhood", + ASSIGNMENT_NEIGHBORHOOD_CANDIDATES, + plan_director(assignment_roster(), &assignment_variables()), + compile_neighborhood( + assignment_context(), + MoveSelectorConfig::GroupedScalarMoveSelector(GroupedScalarMoveSelectorConfig { + selection_order: CANONICAL, + selection_metric: None, + group_name: "shift_assignment".to_string(), + value_candidate_limit: None, + max_moves_per_step: None, + require_hard_improvement: false, + }), + ), + ); +} diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path.rs index 548e08a8..8b9010d6 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path.rs @@ -164,7 +164,8 @@ impl AugmentingPathSearch<'_, S> { if state.is_required(blocker) { continue; } - work.overlay.set_value(state, blocker, None); + work.overlay + .set_value(state, self.group, self.solution, blocker, None); work.edits.push(self.group.edit(blocker, None)); } // State changed after the displacements; re-derive both blockers @@ -195,7 +196,8 @@ impl AugmentingPathSearch<'_, S> { } if work.blockers.is_empty() { - work.overlay.set_value(state, entity_index, Some(value)); + work.overlay + .set_value(state, self.group, self.solution, entity_index, Some(value)); work.edits.push(self.group.edit(entity_index, Some(value))); return true; } @@ -257,16 +259,19 @@ impl AugmentingPathSearch<'_, S> { ), } { - work.overlay.rollback(overlay_checkpoint); + work.overlay + .rollback(self.group, self.solution, overlay_checkpoint); work.edits.truncate(edit_checkpoint); continue; } - work.overlay.set_value(state, entity_index, Some(value)); + work.overlay + .set_value(state, self.group, self.solution, entity_index, Some(value)); work.edits.push(self.group.edit(entity_index, Some(value))); work.visiting.remove(&entity_index); return true; } - work.overlay.rollback(overlay_checkpoint); + work.overlay + .rollback(self.group, self.solution, overlay_checkpoint); work.edits.truncate(edit_checkpoint); } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path_overlay.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path_overlay.rs index 849fd6bf..efdf4677 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path_overlay.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_path_overlay.rs @@ -3,20 +3,67 @@ use solverforge_core::fast_hash::FastMap; use super::assignment_state::ScalarAssignmentState; use crate::builder::ScalarAssignmentBinding; +const NO_ENTITY: u32 = u32::MAX; +const UNASSIGNED: usize = usize::MAX; + +/* Pending assignments of one discovery. Every pending assigned row is linked +into the chain of its capacity key and the chain of its (value, sequence) +coordinate, so blocker and rule-member queries walk the rows of one key +instead of every pending row. The required batch keeps one pending row per +placed required entity, so a scan of all pending rows per query made the +batch quadratic in the required rows. Chains are intrusive: a row's links +live in its pending entry, and the head maps, allocated on the first link, +hold one row per key. */ #[derive(Default)] pub(super) struct AssignmentPathOverlay { - changed: FastMap>, + changed: FastMap, journal: Vec<(usize, Option>)>, - left_members: Vec, - right_members: Vec, + chains: Option>, +} + +#[derive(Default)] +struct ChainHeads { + capacity: FastMap, + sequence: FastMap<(usize, usize), u32>, +} + +/* `value` is the pending value index, or `UNASSIGNED` for a pending +unassignment; value indexes never reach `usize::MAX`. Links are row indexes +below `u32::MAX`, which keeps a pending entry as small as the bare value. */ +struct PendingValue { + value: usize, + capacity_next: u32, + sequence_next: u32, +} + +impl PendingValue { + fn value(&self) -> Option { + (self.value != UNASSIGNED).then_some(self.value) + } } impl AssignmentPathOverlay { pub(super) fn clear(&mut self) { self.changed.clear(); self.journal.clear(); - self.left_members.clear(); - self.right_members.clear(); + if let Some(chains) = &mut self.chains { + if !chains.capacity.is_empty() { + chains.capacity.clear(); + } + if !chains.sequence.is_empty() { + chains.sequence.clear(); + } + } + } + + /// Sizes the pending rows and their key chains for `rows` more pending + /// assignments, so a discovery of known size grows each table once. + pub(super) fn reserve(&mut self, rows: usize) { + self.changed.reserve(rows); + self.journal.reserve(rows); + let chains = self.chains.get_or_insert_with(Box::default); + chains.capacity.reserve(rows); + chains.sequence.reserve(rows); } pub(super) fn checkpoint(&self) -> usize { @@ -30,39 +77,171 @@ impl AssignmentPathOverlay { ) -> Option { self.changed .get(&entity) - .copied() - .unwrap_or_else(|| state.current_value(entity)) + .map_or_else(|| state.current_value(entity), PendingValue::value) } - pub(super) fn set_value( + pub(super) fn set_value( &mut self, state: &ScalarAssignmentState, + group: &ScalarAssignmentBinding, + solution: &S, entity: usize, value: Option, ) { if self.current_value(state, entity) == value { return; } - let previous = self.changed.insert(entity, value); + let previous = self.changed.get(&entity).map(PendingValue::value); + self.replace(group, solution, entity, previous.flatten(), Some(value)); self.journal.push((entity, previous)); } - pub(super) fn rollback(&mut self, checkpoint: usize) { + pub(super) fn rollback( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + checkpoint: usize, + ) { while self.journal.len() > checkpoint { let (entity, previous) = self.journal.pop().expect("journal length was checked"); - match previous { - Some(value) => { - self.changed.insert(entity, value); - } - None => { - self.changed.remove(&entity); - } - } + let current = self.changed.get(&entity).and_then(PendingValue::value); + self.replace(group, solution, entity, current, previous); } } - pub(super) fn blockers( + /* Moves `entity` from the chains of its pending value `from` to those of + `to`; `to == None` drops the pending row so the base value shows again. */ + fn replace( &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + entity: usize, + from: Option, + to: Option>, + ) { + if let Some(value) = from { + self.unlink(group, solution, entity, value); + } + let Some(value) = to else { + self.changed.remove(&entity); + return; + }; + debug_assert_ne!( + value, + Some(UNASSIGNED), + "value indexes stay below usize::MAX" + ); + let pending = PendingValue { + value: value.unwrap_or(UNASSIGNED), + capacity_next: NO_ENTITY, + sequence_next: NO_ENTITY, + }; + self.changed.insert(entity, pending); + if let Some(value) = value { + self.link(group, solution, entity, value); + } + } + + fn link( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + entity: usize, + value: usize, + ) { + let capacity_key = group.capacity_key(solution, entity, value); + let sequence_key = group.sequence_key(solution, entity, value); + if capacity_key.is_none() && sequence_key.is_none() { + return; + } + let row = link_row(entity); + let chains = self.chains.get_or_insert_with(Box::default); + let capacity_next = capacity_key.map_or(NO_ENTITY, |key| { + chains.capacity.insert(key, row).unwrap_or(NO_ENTITY) + }); + let sequence_next = sequence_key.map_or(NO_ENTITY, |sequence| { + chains + .sequence + .insert((value, sequence), row) + .unwrap_or(NO_ENTITY) + }); + let pending = self + .changed + .get_mut(&entity) + .expect("a linked row has a pending value"); + pending.capacity_next = capacity_next; + pending.sequence_next = sequence_next; + } + + fn unlink( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + entity: usize, + value: usize, + ) { + let capacity_key = group.capacity_key(solution, entity, value); + let sequence_key = group.sequence_key(solution, entity, value); + if capacity_key.is_none() && sequence_key.is_none() { + return; + } + let chains = self + .chains + .as_deref_mut() + .expect("a linked row has chain heads"); + if let Some(key) = capacity_key { + unlink_from_chain( + &mut self.changed, + &mut chains.capacity, + key, + entity, + |pending| &mut pending.capacity_next, + ); + } + if let Some(sequence) = sequence_key { + unlink_from_chain( + &mut self.changed, + &mut chains.sequence, + (value, sequence), + entity, + |pending| &mut pending.sequence_next, + ); + } + } + + fn capacity_chain(&self, key: usize) -> impl Iterator + '_ { + let head = self + .chains + .as_deref() + .and_then(|chains| chains.capacity.get(&key).copied()); + chain(&self.changed, head, |pending| pending.capacity_next) + } + + /* Rows whose current value is `value` at `sequence`: recorded members the + overlay leaves on `value`, then pending arrivals not recorded there. */ + fn members<'a>( + &'a self, + state: &'a ScalarAssignmentState, + value: usize, + sequence: usize, + ) -> impl Iterator + 'a { + let recorded = state.sequence_members(value, sequence); + let head = self + .chains + .as_deref() + .and_then(|chains| chains.sequence.get(&(value, sequence)).copied()); + recorded + .iter() + .copied() + .filter(move |entity| self.current_value(state, *entity) == Some(value)) + .chain( + chain(&self.changed, head, |pending| pending.sequence_next) + .filter(move |arrival| !recorded.contains(arrival)), + ) + } + + pub(super) fn blockers( + &self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -72,7 +251,8 @@ impl AssignmentPathOverlay { ) -> Option { blockers.clear(); if let Some(key) = group.capacity_key(solution, entity, value) { - for occupant in state.capacity_occupants(key) { + let occupants = state.capacity_occupants(key); + for occupant in occupants { if *occupant != entity && self.current_value(state, *occupant).is_some_and(|current| { group.capacity_key(solution, *occupant, current) == Some(key) @@ -81,17 +261,10 @@ impl AssignmentPathOverlay { blockers.push(*occupant); } } - for (changed, next) in &self.changed { - if *changed == entity - || state.capacity_occupants(key).contains(changed) - || !next.is_some_and(|next| { - group.capacity_key(solution, *changed, next) == Some(key) - }) - { - continue; - } - blockers.push(*changed); - } + blockers.extend( + self.capacity_chain(key) + .filter(|arrival| *arrival != entity && !occupants.contains(arrival)), + ); } let verdict = self.push_rule_blockers(state, group, solution, entity, value, blockers); @@ -101,7 +274,7 @@ impl AssignmentPathOverlay { } pub(super) fn assignment_allowed( - &mut self, + &self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -113,7 +286,7 @@ impl AssignmentPathOverlay { } fn push_rule_blockers( - &mut self, + &self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -134,11 +307,8 @@ impl AssignmentPathOverlay { .into_iter() .flatten() { - self.collect_members(state, group, solution, value, adjacent, true); blockers.extend( - self.left_members - .iter() - .copied() + self.members(state, value, adjacent) .filter(|blocker| *blocker != entity), ); } @@ -146,7 +316,7 @@ impl AssignmentPathOverlay { } fn rule_allows( - &mut self, + &self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -160,8 +330,7 @@ impl AssignmentPathOverlay { return true; }; if let Some(previous) = sequence.checked_sub(1) { - self.collect_members(state, group, solution, value, previous, true); - if self.left_members.iter().copied().any(|left| { + if self.members(state, value, previous).any(|left| { left != entity && !group.assignment_edge_allowed(solution, left, value, entity, value) }) { @@ -169,8 +338,7 @@ impl AssignmentPathOverlay { } } if let Some(next) = sequence.checked_add(1) { - self.collect_members(state, group, solution, value, next, false); - if self.right_members.iter().copied().any(|right| { + if self.members(state, value, next).any(|right| { right != entity && !group.assignment_edge_allowed(solution, entity, value, right, value) }) { @@ -179,41 +347,53 @@ impl AssignmentPathOverlay { } true } +} - fn collect_members( - &mut self, - state: &ScalarAssignmentState, - group: &ScalarAssignmentBinding, - solution: &S, - value: usize, - sequence: usize, - left: bool, - ) { - let changed = &self.changed; - let members = if left { - &mut self.left_members +fn link_row(entity: usize) -> u32 { + u32::try_from(entity) + .ok() + .filter(|row| *row != NO_ENTITY) + .expect("an assignment group holds fewer than u32::MAX rows") +} + +fn chain( + changed: &FastMap, + head: Option, + next: fn(&PendingValue) -> u32, +) -> impl Iterator + '_ { + std::iter::successors(head.map(|row| row as usize), move |entity| { + let following = next(&changed[entity]); + (following != NO_ENTITY).then_some(following as usize) + }) +} + +fn unlink_from_chain( + changed: &mut FastMap, + heads: &mut FastMap, + key: K, + entity: usize, + link: fn(&mut PendingValue) -> &mut u32, +) where + K: std::hash::Hash + Eq, +{ + let row = link_row(entity); + let following = *link(changed.get_mut(&entity).expect("a linked row is pending")); + let head = heads.get_mut(&key).expect("a linked row has a chain head"); + if *head == row { + if following == NO_ENTITY { + heads.remove(&key); } else { - &mut self.right_members - }; - members.clear(); - for entity in state.sequence_members(value, sequence) { - if changed - .get(entity) - .copied() - .unwrap_or_else(|| state.current_value(*entity)) - == Some(value) - { - members.push(*entity); - } + *head = following; } - for (entity, next) in &self.changed { - if state.sequence_members(value, sequence).contains(entity) - || *next != Some(value) - || group.sequence_key(solution, *entity, value) != Some(sequence) - { - continue; - } - members.push(*entity); + return; + } + let mut previous = *head as usize; + loop { + let next = link(changed.get_mut(&previous).expect("chain rows are pending")); + if *next == row { + *next = following; + return; } + previous = *next as usize; } } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs index af83bebe..65aa39b9 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs @@ -44,11 +44,11 @@ where should_stop, )?; let mut scalar_edits = Vec::new(); - let mut edited_entities = FastSet::default(); let mut visiting = FastSet::default(); let mut blockers = Vec::new(); let mut overlay = state.take_path_overlay(); overlay.clear(); + overlay.reserve(entities.len()); let search = AugmentingPathSearch::new(group, solution, options, AssignmentMoveIntent::required()); for entity_index in entities { @@ -93,7 +93,7 @@ where &mut work, should_stop, ) { - overlay.rollback(overlay_checkpoint); + overlay.rollback(group, solution, overlay_checkpoint); scalar_edits.truncate(edit_checkpoint); if should_stop() { overlay.clear(); @@ -102,29 +102,21 @@ where } continue; } + // A depth-0 discovery ends with the root edit, so a single edit + // assigns this still-unassigned root and touches no row the batch + // already placed. let candidate_edits = &scalar_edits[edit_checkpoint..]; - if candidate_edits - .iter() - .any(|edit| edited_entities.contains(&edit.entity_index())) - { - overlay.rollback(overlay_checkpoint); - scalar_edits.truncate(edit_checkpoint); - continue; - } if candidate_edits.len() != 1 { - overlay.rollback(overlay_checkpoint); + overlay.rollback(group, solution, overlay_checkpoint); scalar_edits.truncate(edit_checkpoint); continue; } let candidate = &candidate_edits[0]; if !group.value_is_legal(solution, candidate.entity_index(), candidate.to_value()) { - overlay.rollback(overlay_checkpoint); + overlay.rollback(group, solution, overlay_checkpoint); scalar_edits.truncate(edit_checkpoint); continue; } - for edit in candidate_edits { - edited_entities.insert(edit.entity_index()); - } break; } } @@ -133,8 +125,10 @@ where state.restore_path_overlay(overlay); return None; } - overlay.clear(); - state.restore_path_overlay(overlay); + // The batch overlay holds one pending row per placed required row; release + // it before final validation builds its own view of the same edits, rather + // than keeping both alive. + drop(overlay); if scalar_edits.is_empty() { return None; } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs index c51c11df..067cd323 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs @@ -12,6 +12,8 @@ mod neighborhood_contracts; mod optional; #[path = "tests/overlay_differential.rs"] mod overlay_differential; +#[path = "tests/path_overlay_index.rs"] +mod path_overlay_index; #[path = "tests/placement_streaming.rs"] mod placement_streaming; #[path = "tests/pool_differential.rs"] diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/path_overlay_index.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/path_overlay_index.rs new file mode 100644 index 00000000..df9ba0c3 --- /dev/null +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/path_overlay_index.rs @@ -0,0 +1,298 @@ +/* The path overlay's arrival indexes against an exact oracle, and the +required batch's hook work against the size of the batch. + +The oracle keeps its own map of pending values, mirrors every recorded value +and rollback, and derives blockers by scanning every entity: capacity +blockers are the entities whose current value has the requested capacity key, +and rule blockers are the current members of the neighbouring sequences when +the rule rejects the assignment. */ + +use std::cell::Cell; +use std::collections::HashMap; + +use super::super::assignment_path_overlay::AssignmentPathOverlay; +use super::super::assignment_required_batch::required_batch_move; +use super::*; + +const ENTITIES: usize = 24; +const VALUES: usize = 6; + +fn mixed_capacity(_: &AssignmentPlan, entity: usize, value: usize) -> Option { + if (entity + value).is_multiple_of(7) { + None + } else { + Some(value * 2 + entity % 2) + } +} + +fn mixed_sequence(_: &AssignmentPlan, entity: usize, value: usize) -> Option { + if entity % 11 == 10 { + None + } else { + Some((entity + value) % 6) + } +} + +fn mixed_rule(_: &AssignmentPlan, left: usize, value: usize, right: usize, _: usize) -> bool { + !(left * 7 + right * 3 + value).is_multiple_of(5) +} + +fn binding_with( + capacity: fn(&AssignmentPlan, usize, usize) -> Option, + sequence: fn(&AssignmentPlan, usize, usize) -> Option, + rule: fn(&AssignmentPlan, usize, usize, usize, usize) -> bool, +) -> ScalarAssignmentBinding { + let slot = ScalarVariableSlot::new( + 0, + 0, + "Task", + entity_count, + "worker", + current_value, + set_value, + ValueSource::EntitySlice { + values_for_entity: candidates, + }, + true, + ) + .with_candidate_values(candidates); + let groups = bind_scalar_groups( + vec![ScalarGroup::assignment( + "indexed_overlay", + ScalarTarget::from_descriptor_index(0, "worker"), + ) + .with_required_entity(required) + .with_capacity_key(capacity) + .with_sequence_key(sequence) + .with_assignment_rule(rule)], + &[slot], + ); + match groups.into_iter().next().unwrap().kind { + ScalarGroupBindingKind::Assignment(binding) => binding, + _ => panic!("expected assignment group"), + } +} + +struct Oracle { + pending: HashMap>, + journal: Vec<(usize, Option>)>, +} + +impl Oracle { + fn current(&self, state: &ScalarAssignmentState, entity: usize) -> Option { + self.pending + .get(&entity) + .copied() + .unwrap_or_else(|| state.current_value(entity)) + } + + fn set(&mut self, state: &ScalarAssignmentState, entity: usize, value: Option) { + if self.current(state, entity) == value { + return; + } + let previous = self.pending.insert(entity, value); + self.journal.push((entity, previous)); + } + + fn rollback(&mut self, checkpoint: usize) { + while self.journal.len() > checkpoint { + let (entity, previous) = self.journal.pop().unwrap(); + match previous { + Some(value) => self.pending.insert(entity, value), + None => self.pending.remove(&entity), + }; + } + } + + fn members( + &self, + state: &ScalarAssignmentState, + plan: &AssignmentPlan, + value: usize, + sequence: usize, + ) -> Vec { + (0..ENTITIES) + .filter(|entity| { + self.current(state, *entity) == Some(value) + && mixed_sequence(plan, *entity, value) == Some(sequence) + }) + .collect() + } + + fn blockers( + &self, + state: &ScalarAssignmentState, + plan: &AssignmentPlan, + entity: usize, + value: usize, + ) -> (Vec, Option) { + let mut blockers = Vec::new(); + if let Some(key) = mixed_capacity(plan, entity, value) { + blockers.extend((0..ENTITIES).filter(|other| { + *other != entity + && self + .current(state, *other) + .is_some_and(|current| mixed_capacity(plan, *other, current) == Some(key)) + })); + } + let verdict = match mixed_sequence(plan, entity, value) { + None => true, + Some(sequence) => { + let left = sequence.checked_sub(1).map_or_else(Vec::new, |previous| { + self.members(state, plan, value, previous) + }); + let right = self.members(state, plan, value, sequence + 1); + let allowed = left + .iter() + .all(|l| *l == entity || mixed_rule(plan, *l, value, entity, value)) + && right + .iter() + .all(|r| *r == entity || mixed_rule(plan, entity, value, *r, value)); + if !allowed { + blockers.extend(left.into_iter().chain(right).filter(|m| *m != entity)); + } + allowed + } + }; + blockers.sort_unstable(); + blockers.dedup(); + (blockers, Some(verdict)) + } +} + +struct Lcg(u64); + +impl Lcg { + fn below(&mut self, bound: usize) -> usize { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + ((self.0 >> 33) as usize) % bound + } +} + +#[test] +fn indexed_overlay_blockers_match_full_scan_oracle_across_rollbacks() { + let binding = binding_with(mixed_capacity, mixed_sequence, mixed_rule); + for seed in 0..64u64 { + let mut rng = Lcg(seed); + let plan = AssignmentPlan { + score: None, + assignments: (0..ENTITIES) + .map(|_| match rng.below(VALUES + 2) { + value if value < VALUES => Some(value), + _ => None, + }) + .collect(), + candidates: vec![(0..VALUES).collect(); ENTITIES], + }; + let state = ScalarAssignmentState::new(&binding, &plan); + let mut overlay = AssignmentPathOverlay::default(); + let mut oracle = Oracle { + pending: HashMap::new(), + journal: Vec::new(), + }; + let mut checkpoints = Vec::new(); + let mut blockers = Vec::new(); + for step in 0..400 { + match rng.below(10) { + 0..=4 => { + let entity = rng.below(ENTITIES); + let value = match rng.below(VALUES + 1) { + value if value < VALUES => Some(value), + _ => None, + }; + overlay.set_value(&state, &binding, &plan, entity, value); + oracle.set(&state, entity, value); + } + 5 | 6 => { + assert_eq!(overlay.checkpoint(), oracle.journal.len()); + checkpoints.push(overlay.checkpoint()); + } + 7 | 8 => { + if let Some(checkpoint) = checkpoints.pop() { + overlay.rollback(&binding, &plan, checkpoint); + oracle.rollback(checkpoint); + } + } + _ => { + if rng.below(4) == 0 { + overlay.clear(); + oracle.pending.clear(); + oracle.journal.clear(); + checkpoints.clear(); + } + } + } + for entity in 0..ENTITIES { + assert_eq!( + overlay.current_value(&state, entity), + oracle.current(&state, entity), + "seed {seed} step {step} entity {entity}" + ); + } + let entity = rng.below(ENTITIES); + let value = rng.below(VALUES); + let verdict = overlay.blockers(&state, &binding, &plan, entity, value, &mut blockers); + let (expected, expected_verdict) = oracle.blockers(&state, &plan, entity, value); + assert_eq!( + (blockers.clone(), verdict), + (expected, expected_verdict), + "seed {seed} step {step} entity {entity} value {value}" + ); + } + } +} + +thread_local! { + static KEY_HOOK_CALLS: Cell = const { Cell::new(0) }; +} + +fn count_key_hook() { + KEY_HOOK_CALLS.with(|calls| calls.set(calls.get() + 1)); +} + +fn counted_capacity(_: &AssignmentPlan, _: usize, value: usize) -> Option { + count_key_hook(); + Some(value) +} + +fn counted_sequence(_: &AssignmentPlan, entity: usize, _: usize) -> Option { + count_key_hook(); + Some(entity) +} + +fn allows_every_edge(_: &AssignmentPlan, _: usize, _: usize, _: usize, _: usize) -> bool { + true +} + +#[test] +fn required_batch_key_work_grows_linearly_with_required_rows() { + let binding = binding_with(counted_capacity, counted_sequence, allows_every_edge); + let calls_for = |rows: usize| { + let plan = AssignmentPlan { + score: None, + assignments: vec![None; rows], + candidates: (0..rows).map(|entity| vec![entity]).collect(), + }; + let mut state = ScalarAssignmentState::new(&binding, &plan); + KEY_HOOK_CALLS.with(|calls| calls.set(0)); + let batch = required_batch_move( + &binding, + &plan, + &mut state, + ScalarAssignmentMoveOptions::for_construction(ScalarGroupLimits::new()), + &mut || false, + ) + .expect("every required row has a free value"); + assert_eq!(batch.edits().len(), rows); + KEY_HOOK_CALLS.with(Cell::get) + }; + let small = calls_for(256); + let large = calls_for(1024); + assert!( + large <= small * 5, + "key hook calls grew from {small} at 256 rows to {large} at 1024 rows" + ); +} diff --git a/scripts/bench-zero-regression.sh b/scripts/bench-zero-regression.sh index 77514adb..793bbe52 100755 --- a/scripts/bench-zero-regression.sh +++ b/scripts/bench-zero-regression.sh @@ -90,7 +90,7 @@ RESULTS=${RESULTS:-"/tmp/solverforge-zero-regression-$(date +%Y%m%d-%H%M%S)"} # scoring_weights_one scoring_weights_mixed" measures incremental score-director # churn through uni, join, shared grouped, and balance constraints; see # crates/solverforge-solver/benches/selector_cursor_gate/scoring_cases.rs. -DEFAULT_CASES=(list_change list_swap nearby_change nearby_swap sublist_change sublist_swap union cartesian k_opt ruin scalar_change scalar_swap construction_full construction_first_fit route_rows group_ruin) +DEFAULT_CASES=(list_change list_swap nearby_change nearby_swap sublist_change sublist_swap union cartesian k_opt ruin scalar_change scalar_swap construction_full construction_first_fit assignment_required assignment_neighborhood route_rows group_ruin) if [[ -n ${BENCH_CASES:-} ]]; then read -r -a CASES <<<"$BENCH_CASES" else