From 29d77708d3d7d6d027267805eb7c0ca694b2a7e7 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Mon, 30 Nov 2026 21:24:09 +0100 Subject: [PATCH] fix(solver): keep required construction's buffers across placements Placing required rows one move at a time (f4cc2fa2) allocated again on every placement: the augmenting search's blocker list and visited set, its edit list, each row's candidate values, a fresh candidate store and target list, the completed-slot set and one probe placement per probed row, and the affected-row list of every grouped move. The gate measured assignment_required at 496,897 allocations against 134,145 on 0.31.4 (+270%) and 52.7 MB against 32.0 MB allocated. The construction cursor now owns those buffers and refills them: - the assignment state pools the search's blocker list and visited set, and the move cursor its edit list; - candidate values are refilled into the cursor's buffers (`candidate_values_into`, `extend_candidate_values`); - the store, targets, touched rows, completed slots and resume scratch travel with the generator through `recycle`; - completion is probed through one reusable placement (`retarget`); - a grouped move iterates its affected rows from its edits instead of storing a list, and checks repeated rows by a scan instead of a set. One iteration of assignment_required now allocates 3,698 times and 478,017 bytes (0.31.4: 4,193 and 1,000,709), peak 240,620 (0.31.4: 360,984), with the same roster; assignment_neighborhood allocates 180,248 times (0.31.4: 206,448) with the same candidates. --- .../context/scalar/group/assignment.rs | 21 +++- .../builder/context/scalar/group/member.rs | 26 +++-- .../src/heuristic/move/compound_scalar.rs | 45 +++++---- .../grouped_scalar/assignment_entity.rs | 24 +++-- .../grouped_scalar/assignment_path.rs | 19 ++-- .../grouped_scalar/assignment_scarcity.rs | 10 +- .../grouped_scalar/assignment_state.rs | 24 ++++- .../grouped_scalar/assignment_stream.rs | 43 ++++++-- .../assignment_stream/dispatch.rs | 5 +- .../construction/grouped_scalar/move_build.rs | 11 ++- .../construction/grouped_scalar/placer.rs | 12 ++- .../grouped_scalar/placer_resume.rs | 99 +++++++++++++------ .../grouped_scalar/placer_stream.rs | 48 ++++++--- .../construction/grouped_scalar/tests.rs | 2 + .../tests/augmenting_overlay.rs | 3 + .../grouped_scalar/tests/control.rs | 1 + .../tests/neighborhood_contracts.rs | 8 +- .../src/phase/construction/placer.rs | 24 +++++ 18 files changed, 311 insertions(+), 114 deletions(-) diff --git a/crates/solverforge-solver/src/builder/context/scalar/group/assignment.rs b/crates/solverforge-solver/src/builder/context/scalar/group/assignment.rs index c9e9404ab..f2f7775a7 100644 --- a/crates/solverforge-solver/src/builder/context/scalar/group/assignment.rs +++ b/crates/solverforge-solver/src/builder/context/scalar/group/assignment.rs @@ -282,13 +282,26 @@ impl ScalarAssignmentBinding { entity_index: usize, value_candidate_limit: Option, ) -> Vec { - let mut values = - self.target - .candidate_values(solution, entity_index, value_candidate_limit); - values.sort_by_key(|value| (self.value_order_key(solution, entity_index, *value), *value)); + let mut values = Vec::new(); + self.candidate_values_into(solution, entity_index, value_candidate_limit, &mut values); values } + /// Refills `values` with the candidate values of `entity_index` in value + /// order, reusing its allocation. + pub(crate) fn candidate_values_into( + &self, + solution: &S, + entity_index: usize, + value_candidate_limit: Option, + values: &mut Vec, + ) { + values.clear(); + self.target + .extend_candidate_values(solution, entity_index, value_candidate_limit, values); + values.sort_by_key(|value| (self.value_order_key(solution, entity_index, *value), *value)); + } + pub(crate) fn value_is_legal( &self, solution: &S, diff --git a/crates/solverforge-solver/src/builder/context/scalar/group/member.rs b/crates/solverforge-solver/src/builder/context/scalar/group/member.rs index 31061c411..f117b949c 100644 --- a/crates/solverforge-solver/src/builder/context/scalar/group/member.rs +++ b/crates/solverforge-solver/src/builder/context/scalar/group/member.rs @@ -162,22 +162,28 @@ impl ScalarGroupMemberBinding { } } - pub(crate) fn candidate_values( + /// Appends the candidate values of `entity_index` to `values`, so a + /// caller refilling its own buffer allocates at most once. + pub(crate) fn extend_candidate_values( &self, solution: &S, entity_index: usize, value_candidate_limit: Option, - ) -> Vec { + values: &mut Vec, + ) { match &self.access { - ScalarGroupMemberAccess::Static(slot) => { - slot.candidate_values_for_entity(solution, entity_index, value_candidate_limit) - } + ScalarGroupMemberAccess::Static(slot) => slot.extend_candidate_values_for_entity( + solution, + entity_index, + value_candidate_limit, + values, + ), ScalarGroupMemberAccess::Dynamic(slot) => { - let values = slot.candidate_values(solution, entity_index); - match value_candidate_limit { - Some(limit) => values.iter().copied().take(limit).collect(), - None => values.to_vec(), - } + let candidates = slot.candidate_values(solution, entity_index); + let limit = value_candidate_limit + .unwrap_or(usize::MAX) + .min(candidates.len()); + values.extend_from_slice(&candidates[..limit]); } } } diff --git a/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs b/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs index 5e48ba5f2..4527fc62c 100644 --- a/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs +++ b/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs @@ -161,7 +161,6 @@ pub(crate) struct CompoundScalarMove { variable_label: &'static str, edits: Vec>, entity_indices: Vec, - affected: Vec<(usize, usize)>, require_hard_improvement: bool, construction_value_order_key: Option, } @@ -176,13 +175,6 @@ impl CompoundScalarMove { variable_label: &'static str, edits: Vec>, ) -> Self { - let mut affected = Vec::new(); - for edit in edits.iter() { - let key = (edit.descriptor_index, edit.entity_index); - if !affected.contains(&key) { - affected.push(key); - } - } let mut entity_indices = edits .iter() .map(|edit| edit.entity_index) @@ -194,7 +186,6 @@ impl CompoundScalarMove { variable_label, edits, entity_indices, - affected, require_hard_improvement: false, construction_value_order_key: None, } @@ -237,6 +228,24 @@ impl CompoundScalarMove { } } +impl CompoundScalarMove { + /* The (descriptor, entity) rows the edits change, each once, in edit + order. A move holds a handful of edits, so a scan replaces a stored + list built per move. */ + fn affected(&self) -> impl DoubleEndedIterator + '_ { + self.edits + .iter() + .enumerate() + .filter(|(position, edit)| { + !self.edits[..*position].iter().any(|earlier| { + earlier.descriptor_index == edit.descriptor_index + && earlier.entity_index == edit.entity_index + }) + }) + .map(|(_, edit)| (edit.descriptor_index, edit.entity_index)) + } +} + impl Debug for CompoundScalarMove { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("CompoundScalarMove") @@ -264,33 +273,31 @@ where fn do_move>(&self, score_director: &mut D) -> Self::Undo { let mut undo = SmallVec::<[Option; 8]>::with_capacity(self.edits.len()); - let affected = &self.affected; for edit in &self.edits { let old_value = edit.current_value(score_director.working_solution()); undo.push(old_value); } - for (descriptor_index, entity_index) in affected.iter() { - score_director.before_variable_changed(*descriptor_index, *entity_index); + for (descriptor_index, entity_index) in self.affected() { + score_director.before_variable_changed(descriptor_index, entity_index); } for edit in &self.edits { edit.set_value(score_director.working_solution_mut(), edit.to_value); } - for (descriptor_index, entity_index) in affected.iter().rev() { - score_director.after_variable_changed(*descriptor_index, *entity_index); + for (descriptor_index, entity_index) in self.affected().rev() { + score_director.after_variable_changed(descriptor_index, entity_index); } undo } fn undo_move>(&self, score_director: &mut D, undo: Self::Undo) { - let affected = &self.affected; - for (descriptor_index, entity_index) in affected.iter() { - score_director.before_variable_changed(*descriptor_index, *entity_index); + for (descriptor_index, entity_index) in self.affected() { + score_director.before_variable_changed(descriptor_index, entity_index); } for (edit, old_value) in self.edits.iter().zip(undo) { edit.set_value(score_director.working_solution_mut(), old_value); } - for (descriptor_index, entity_index) in affected.iter().rev() { - score_director.after_variable_changed(*descriptor_index, *entity_index); + for (descriptor_index, entity_index) in self.affected().rev() { + score_director.after_variable_changed(descriptor_index, entity_index); } } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs index ba7666acb..66eaa7d84 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_entity.rs @@ -10,6 +10,7 @@ use super::assignment_scarcity::sort_values_by_required_scarcity; use super::assignment_state::{CapacityConflict, ScalarAssignmentState}; use crate::builder::ScalarAssignmentBinding; use crate::heuristic::r#move::CompoundScalarMove; +use crate::planning::ScalarEdit; use solverforge_core::fast_hash::{FastMap, FastSet}; pub(super) struct EntityValueCursor { @@ -32,6 +33,7 @@ impl EntityValueCursor { group: &ScalarAssignmentBinding, solution: &S, state: &mut ScalarAssignmentState, + edits: &mut Vec>, should_stop: &mut ShouldStop, ) -> Option> where @@ -54,10 +56,11 @@ impl EntityValueCursor { continue; } if self.values.is_empty() { - self.values = group.candidate_values( + group.candidate_values_into( solution, entity_index, self.options.value_candidate_limit, + &mut self.values, ); if self.kind == AssignmentMoveKind::Required && self.options.required_scarcity_ordering @@ -88,6 +91,7 @@ impl EntityValueCursor { AssignmentRequest::root(entity_index, value, self.request_depth()), self.options, intent, + edits, should_stop, ); if should_stop() { @@ -141,17 +145,22 @@ impl EntityValueCursor { group: &ScalarAssignmentBinding, solution: &S, entity_index: usize, + values: &mut Vec, ) { if self.value_degrees.is_empty() { return; } - for value in - group.candidate_values(solution, entity_index, self.options.value_candidate_limit) - { - if let Some(degree) = self.value_degrees.get_mut(&value) { + group.candidate_values_into( + solution, + entity_index, + self.options.value_candidate_limit, + values, + ); + for value in values.iter() { + if let Some(degree) = self.value_degrees.get_mut(value) { *degree -= 1; if *degree == 0 { - self.value_degrees.remove(&value); + self.value_degrees.remove(value); } } } @@ -208,6 +217,7 @@ impl CapacityCursor { group: &ScalarAssignmentBinding, solution: &S, state: &mut ScalarAssignmentState, + edits: &mut Vec>, should_stop: &mut ShouldStop, ) -> Option> where @@ -219,7 +229,7 @@ impl CapacityCursor { return None; } if let Some(cursor) = &mut self.repair_cursor { - if let Some(mov) = cursor.next(group, solution, state, should_stop) { + if let Some(mov) = cursor.next(group, solution, state, edits, should_stop) { return Some(mov); } if should_stop() { 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 548e08a8e..cc63f6cb6 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 @@ -9,6 +9,7 @@ use crate::heuristic::r#move::CompoundScalarMove; use crate::planning::ScalarEdit; use solverforge_core::fast_hash::FastSet; +#[allow(clippy::too_many_arguments)] pub(super) fn assignment_move_for_entity_value( group: &ScalarAssignmentBinding, solution: &S, @@ -16,6 +17,7 @@ pub(super) fn assignment_move_for_entity_value( assignment: AssignmentRequest, options: ScalarAssignmentMoveOptions, intent: AssignmentMoveIntent, + edits: &mut Vec>, should_stop: &mut ShouldStop, ) -> Option> where @@ -32,17 +34,22 @@ where } let mut overlay = state.take_path_overlay(); overlay.clear(); - let mut edits = Vec::new(); - let mut visiting = FastSet::default(); - let mut blockers = Vec::new(); + edits.clear(); + let mut scratch = state.take_path_scratch(); let search = AugmentingPathSearch::new(group, solution, options, intent); - let mut work = AssignmentPathWork::new(&mut overlay, &mut visiting, &mut edits, &mut blockers); + let mut work = AssignmentPathWork::new( + &mut overlay, + &mut scratch.visiting, + edits, + &mut scratch.blockers, + ); let produced = search.discover(state, assignment, &mut work, should_stop); - let feasible = produced && state.refresh_trial_edits(group, solution, &edits); + state.restore_path_scratch(scratch); + let feasible = produced && state.refresh_trial_edits(group, solution, edits); overlay.clear(); state.restore_path_overlay(overlay); feasible - .then_some(move_from_edits(group, solution, &edits, intent.reason)) + .then_some(move_from_edits(group, solution, edits, intent.reason)) .flatten() } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs index d2f4217e3..05e038d8e 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs @@ -17,6 +17,7 @@ where ShouldStop: FnMut() -> bool, { let mut entities = Vec::new(); + let mut values = Vec::new(); for entity_index in 0..group.entity_count(solution) { if should_stop() { return None; @@ -24,9 +25,8 @@ where if !state.is_required(entity_index) || state.current_value(entity_index).is_some() { continue; } - let candidate_count = group - .candidate_values(solution, entity_index, value_candidate_limit) - .len(); + group.candidate_values_into(solution, entity_index, value_candidate_limit, &mut values); + let candidate_count = values.len(); if should_stop() { return None; } @@ -61,11 +61,13 @@ where { let mut degrees = FastMap::default(); let mut processed_edges = 0usize; + let mut values = Vec::new(); for entity_index in entities { if should_stop() { return None; } - for value in group.candidate_values(solution, *entity_index, value_candidate_limit) { + group.candidate_values_into(solution, *entity_index, value_candidate_limit, &mut values); + for value in values.iter().copied() { *degrees.entry(value).or_insert(0) += 1; processed_edges += 1; if processed_edges.is_multiple_of(GENERATION_POLL_INTERVAL) && should_stop() { diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state.rs index 1a2c5381a..f151cc805 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state.rs @@ -8,7 +8,7 @@ mod pressure; use super::assignment_path_overlay::AssignmentPathOverlay; use overlay::OverlayScratch; -use solverforge_core::fast_hash::FastMap; +use solverforge_core::fast_hash::{FastMap, FastSet}; mod membership; @@ -28,6 +28,16 @@ pub(crate) struct ScalarAssignmentState { serves one nesting level (take/restore, allocated once grown). */ overlay: OverlayScratch, path_overlay: AssignmentPathOverlay, + path_scratch: PathScratch, +} + +/* The visited set and blocker list one augmenting-path discovery uses, +kept across discoveries so a discovery allocates nothing once they have +grown. */ +#[derive(Default)] +pub(super) struct PathScratch { + pub(super) visiting: FastSet, + pub(super) blockers: Vec, } pub(super) struct CapacityConflict { @@ -83,6 +93,7 @@ impl ScalarAssignmentState { assigned_by_sequence: FastMap::default(), overlay: OverlayScratch::default(), path_overlay: AssignmentPathOverlay::default(), + path_scratch: PathScratch::default(), }; for entity in 0..entity_count { state.refresh_rows( @@ -125,6 +136,17 @@ impl ScalarAssignmentState { self.path_overlay = overlay; } + pub(super) fn take_path_scratch(&mut self) -> PathScratch { + let mut scratch = std::mem::take(&mut self.path_scratch); + scratch.visiting.clear(); + scratch.blockers.clear(); + scratch + } + + pub(super) fn restore_path_scratch(&mut self, scratch: PathScratch) { + self.path_scratch = scratch; + } + pub(super) fn refresh_trial_edits( &mut self, group: &ScalarAssignmentBinding, diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream.rs index 6b477d4a1..e32f48fca 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream.rs @@ -12,8 +12,17 @@ use super::assignment_value_index::{assigned_value_sequence_index, AssignedValue use crate::builder::ScalarAssignmentBinding; use crate::heuristic::r#move::CompoundScalarMove; use crate::phase::construction::ConstructionSlotId; +use crate::planning::ScalarEdit; use solverforge_core::fast_hash::FastSet; +/* Buffers `resume_after_placement` refills on every placement: the rows +whose value changed and the candidate values of a retired row. */ +#[derive(Default)] +pub(super) struct ResumeScratch { + changed: Vec<(usize, Option)>, + values: Vec, +} + pub(crate) struct ScalarAssignmentMoveCursor where S: PlanningSolution, @@ -29,6 +38,8 @@ where family_pos: usize, seen: FastSet, yielded: usize, + // The edit list every augmenting-path discovery of this cursor refills. + edit_scratch: Vec>, } mod dispatch; @@ -170,6 +181,7 @@ where index_cache: None, seen: FastSet::default(), yielded: 0, + edit_scratch: Vec::new(), } } @@ -185,26 +197,31 @@ where solution: &S, touched: &[usize], placed: usize, + scratch: &mut ResumeScratch, ) -> bool { - let changed = touched - .iter() - .map(|entity| (*entity, group.current_value(solution, *entity))) - .filter(|(entity, value)| self.state.current_value(*entity) != *value) - .collect::>(); - for (entity, value) in &changed { + let ResumeScratch { changed, values } = scratch; + changed.clear(); + changed.extend( + touched + .iter() + .map(|entity| (*entity, group.current_value(solution, *entity))) + .filter(|(entity, value)| self.state.current_value(*entity) != *value), + ); + for (entity, value) in changed.iter() { if value.is_some() && self.state.current_value(*entity).is_none() && self.state.is_required(*entity) { for slot in &mut self.family_slots { if let AssignmentFamilyCursor::EntityValues(cursor) = &mut slot.cursor { - cursor.retire_required_row(group, solution, *entity); + cursor.retire_required_row(group, solution, *entity, values); } } } } let any_changed = !changed.is_empty(); - self.state.refresh_rows(group, solution, changed); + self.state + .refresh_rows(group, solution, changed.iter().copied()); for slot in &mut self.family_slots { slot.cursor.resume_after_placement(placed); } @@ -289,7 +306,15 @@ where let candidate = { let cursor = &mut self.family_slots[slot_index].cursor; let index = self.index_cache.as_ref(); - next_family_move(cursor, index, group, solution, &mut self.state, should_stop) + next_family_move( + cursor, + index, + group, + solution, + &mut self.state, + &mut self.edit_scratch, + should_stop, + ) }; if candidate.is_none() && !should_stop() { self.family_slots[slot_index].exhausted = true; diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream/dispatch.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream/dispatch.rs index 4632a8be2..877a06633 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream/dispatch.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_stream/dispatch.rs @@ -6,6 +6,7 @@ pub(super) fn next_family_move( group: &ScalarAssignmentBinding, solution: &S, state: &mut ScalarAssignmentState, + edits: &mut Vec>, should_stop: &mut ShouldStop, ) -> Option> where @@ -17,14 +18,14 @@ where } match cursor { AssignmentFamilyCursor::EntityValues(entity_cursor) => { - let candidate = entity_cursor.next(group, solution, state, should_stop); + let candidate = entity_cursor.next(group, solution, state, edits, should_stop); if candidate.is_none() && !should_stop() { *cursor = AssignmentFamilyCursor::Empty; } candidate } AssignmentFamilyCursor::Capacity(capacity_cursor) => { - let candidate = capacity_cursor.next(group, solution, state, should_stop); + let candidate = capacity_cursor.next(group, solution, state, edits, should_stop); if candidate.is_none() && !should_stop() { *cursor = AssignmentFamilyCursor::Empty; } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/move_build.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/move_build.rs index 3f64fe3d8..c294140bf 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/move_build.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/move_build.rs @@ -3,7 +3,6 @@ use solverforge_core::domain::PlanningSolution; use crate::builder::context::{ScalarAssignmentBinding, ScalarCandidate, ScalarGroupBinding}; use crate::heuristic::r#move::CompoundScalarMove; use crate::planning::ScalarEdit; -use solverforge_core::fast_hash::FastSet; pub(crate) fn compound_move_for_group_candidate( group: &ScalarGroupBinding, @@ -52,10 +51,14 @@ where return None; } - let mut targets = FastSet::default(); + // An assignment path names each row once; its few edits are checked for + // a repeated row by a scan instead of a hashed set built per move. let mut compound_edits = Vec::with_capacity(edits.len()); - for edit in edits { - if !targets.insert(edit.entity_index()) { + for (position, edit) in edits.iter().enumerate() { + if edits[..position] + .iter() + .any(|earlier| earlier.entity_index() == edit.entity_index()) + { return None; } if !group.value_is_legal(solution, edit.entity_index(), edit.to_value()) { diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs index 433ef55c6..1fe02a1ed 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs @@ -8,7 +8,7 @@ use solverforge_scoring::Director; use super::assignment_candidate::{remaining_required_count, ScalarAssignmentMoveOptions}; use super::assignment_stream::ScalarAssignmentMoveCursor; use super::placement::{group_slot_id, scalar_slots_for_candidate}; -use super::placer_resume::ResumableAssignment; +use super::placer_resume::{AssignmentProbe, PlacementPools, ResumableAssignment}; use super::placer_stream::{ assignment_placement_move_limit, next_assignment_placement, next_candidate_placement, AssignmentPlacementGenerator, CandidatePlacementSeed, ScalarGroupCandidateCursor, @@ -118,6 +118,9 @@ where /// The last assignment placement's generator, carried into the next /// placement so its state and row order are not rebuilt per placement. resumable: Option>, + /// Reused to ask the phase whether a row's construction slots are + /// completed. + probe: AssignmentProbe, } impl EntityPlacerCursor> for ScalarGroupPlacerCursor<'_, S> @@ -161,6 +164,7 @@ where solution, &mut is_completed, &mut should_stop, + &mut self.probe, ); if placement.is_some() || should_stop() { return placement; @@ -172,6 +176,7 @@ where solution, &mut is_completed, &mut should_stop, + &mut self.probe, ) } } @@ -197,6 +202,10 @@ where placer: self, candidate_seeds: None, resumable: None, + probe: Placement::new( + EntityReference::new(0, 0), + ScalarGroupCandidateCursor::empty(), + ), } } } @@ -355,6 +364,7 @@ where options, accepted: 0, completion_rows: None, + pools: PlacementPools::default(), }) } } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs index 2f623474f..9935a8ac7 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs @@ -1,11 +1,47 @@ use solverforge_core::domain::PlanningSolution; use solverforge_core::fast_hash::FastSet; +use super::assignment_stream::ResumeScratch; use super::placement::assignment_group_slot; use super::placer_stream::{AssignmentPlacementGenerator, ScalarGroupCandidateCursor}; use crate::heuristic::r#move::CompoundScalarMove; +use crate::heuristic::selector::move_selector::CandidateStore; use crate::heuristic::selector::EntityReference; -use crate::phase::construction::{ConstructionSlotId, Placement}; +use crate::phase::construction::{ConstructionSlotId, ConstructionTarget, Placement}; + +pub(crate) type AssignmentProbe = + Placement, ScalarGroupCandidateCursor>; + +/* Buffers an assignment placement fills and the next placement refills: +the candidate store and targets of its candidate cursor, the rows its +candidates name, its completed slots and the resume scratch. They travel +with the generator from placement to placement, so a placement allocates +nothing once they have grown. */ +pub(crate) struct PlacementPools +where + S: PlanningSolution + 'static, +{ + pub(super) store: CandidateStore>, + pub(super) targets: Vec, + pub(super) touched: Vec, + pub(super) completed: FastSet, + pub(super) resume: ResumeScratch, +} + +impl Default for PlacementPools +where + S: PlanningSolution + 'static, +{ + fn default() -> Self { + Self { + store: CandidateStore::new(), + targets: Vec::new(), + touched: Vec::new(), + completed: FastSet::default(), + resume: ResumeScratch::default(), + } + } +} /* A finished assignment placement handed back to the placer cursor: the generator, the row it placed and every row its candidates' edits named. */ @@ -49,46 +85,49 @@ where solution, &touched, placed, + &mut generator.pools.resume, ); + touched.clear(); + generator.pools.touched = touched; generator.pending = None; generator.accepted = 0; - match &mut generator.completion_rows { - Some(rows) if !changed => rows.push(placed), - rows => *rows = Some(vec![placed]), + if let Some(rows) = &mut generator.completion_rows { + if changed { + rows.clear(); + } + rows.push(placed); } generator } } +/* The construction slots of this group completed at the current revision, +probed through the reusable `probe` placement. */ pub(super) fn completed_assignment_slots( generator: &mut AssignmentPlacementGenerator, solution: &S, is_completed: &mut IsCompleted, + probe: &mut AssignmentProbe, ) -> FastSet where S: PlanningSolution + 'static, - IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> bool, + IsCompleted: FnMut(&AssignmentProbe) -> bool, { let rows = generator.completion_rows.take().unwrap_or_else(|| { (0..generator.assignment.entity_count(solution)) .filter(|entity_index| { - assignment_slot_completed(generator, solution, *entity_index, is_completed) + assignment_slot_completed(generator, solution, *entity_index, is_completed, probe) }) .collect() }); - let completed = rows - .iter() - .copied() - .filter(|entity_index| { - assignment_slot_completed(generator, solution, *entity_index, is_completed) - }) - .map(|entity_index| { - ConstructionSlotId::new( - generator.assignment.target().construction_binding_index(), - entity_index, - ) - }) - .collect(); + let mut completed = std::mem::take(&mut generator.pools.completed); + completed.clear(); + let binding_index = generator.assignment.target().construction_binding_index(); + for entity_index in rows.iter().copied() { + if assignment_slot_completed(generator, solution, entity_index, is_completed, probe) { + completed.insert(ConstructionSlotId::new(binding_index, entity_index)); + } + } generator.completion_rows = Some(rows); completed } @@ -98,30 +137,28 @@ fn assignment_slot_completed( solution: &S, entity_index: usize, is_completed: &mut IsCompleted, + probe: &mut AssignmentProbe, ) -> bool where S: PlanningSolution + 'static, - IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> bool, + IsCompleted: FnMut(&AssignmentProbe) -> bool, { let slot_id = ConstructionSlotId::new( generator.assignment.target().construction_binding_index(), entity_index, ); - let mut placement = Placement::new( - EntityReference::new(generator.assignment.target.descriptor_index, entity_index), - ScalarGroupCandidateCursor::empty(), - ) - .with_scalar_slots(vec![slot_id]); // Assignment decisions complete group slots, not scalar slots. Only // protect kept-unassigned roots here; assigned rows remain available as // blockers in a later required augmenting rematch. - if generator + let group_slot = generator .assignment .current_value(solution, entity_index) .is_none() - { - placement = - placement.with_group_slot(assignment_group_slot(generator.group_index, entity_index)); - } - is_completed(&placement) + .then(|| assignment_group_slot(generator.group_index, entity_index)); + probe.retarget( + EntityReference::new(generator.assignment.target.descriptor_index, entity_index), + slot_id, + group_slot, + ); + is_completed(probe) } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_stream.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_stream.rs index 3fa8c8268..4f7229f07 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_stream.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_stream.rs @@ -5,7 +5,9 @@ use super::assignment_candidate::ScalarAssignmentMoveOptions; use super::assignment_stream::ScalarAssignmentMoveCursor; use super::move_build::compound_move_for_prevalidated_group_candidate; use super::placement::{assignment_group_slot, assignment_move_target, principal_assignment_edit}; -use super::placer_resume::{completed_assignment_slots, ResumableAssignment}; +use super::placer_resume::{ + completed_assignment_slots, AssignmentProbe, PlacementPools, ResumableAssignment, +}; use crate::builder::context::{ScalarAssignmentBinding, ScalarCandidate, ScalarGroupBinding}; use crate::heuristic::r#move::CompoundScalarMove; use crate::heuristic::selector::move_selector::{ @@ -46,6 +48,7 @@ where move advances the revision, which voids every earlier completion, so a change narrows the list to the placed row. */ pub(super) completion_rows: Option>, + pub(super) pools: PlacementPools, } #[allow(clippy::large_enum_variant)] @@ -103,20 +106,18 @@ where } fn assignment( - generator: AssignmentPlacementGenerator, + mut generator: AssignmentPlacementGenerator, active_entity: usize, completed_slots: FastSet, first: (CompoundScalarMove, ConstructionTarget), ) -> Self { - let touched = first - .0 - .edits() - .iter() - .map(|edit| edit.entity_index) - .collect(); + let store = std::mem::take(&mut generator.pools.store); + let targets = std::mem::take(&mut generator.pools.targets); + let mut touched = std::mem::take(&mut generator.pools.touched); + touched.extend(first.0.edits().iter().map(|edit| edit.entity_index)); Self { - store: CandidateStore::new(), - targets: Vec::new(), + store, + targets, source: ScalarGroupCandidateSource::Assignment { generator, active_entity, @@ -128,15 +129,30 @@ where } /* Hands an assignment placement's generator back for the next - placement; other sources keep nothing. */ + placement, with this cursor's buffers emptied into its pools; other + sources keep nothing. */ pub(super) fn into_resumable(self) -> Option> { - match self.source { + let Self { + mut store, + mut targets, + source, + } = self; + match source { ScalarGroupCandidateSource::Assignment { - generator, + mut generator, active_entity, + mut completed_slots, touched, .. - } => Some(ResumableAssignment::new(generator, active_entity, touched)), + } => { + store.reset(); + targets.clear(); + completed_slots.clear(); + generator.pools.store = store; + generator.pools.targets = targets; + generator.pools.completed = completed_slots; + Some(ResumableAssignment::new(generator, active_entity, touched)) + } _ => None, } } @@ -260,13 +276,15 @@ pub(super) fn next_assignment_placement( solution: &S, mut is_completed: IsCompleted, mut should_stop: ShouldStop, + probe: &mut AssignmentProbe, ) -> Option, ScalarGroupCandidateCursor>> where S: PlanningSolution + 'static, IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> bool, ShouldStop: FnMut() -> bool, { - let completed_slots = completed_assignment_slots(&mut generator, solution, &mut is_completed); + let completed_slots = + completed_assignment_slots(&mut generator, solution, &mut is_completed, probe); if generator.accepted < generator.options.max_moves && !should_stop() { generator.cursor.exclude_completed_optional_entities( &generator.assignment, 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 94b667c7a..839efdb77 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs @@ -350,6 +350,7 @@ fn augmenting_assignment_restores_index_after_final_feasibility() { AssignmentRequest::root(2, 0, limits.max_augmenting_depth.unwrap_or(3)), ScalarAssignmentMoveOptions::for_construction(limits), AssignmentMoveIntent::required(), + &mut Vec::new(), &mut || false, ) .expect("displacement candidate"); @@ -367,6 +368,7 @@ fn augmenting_assignment_restores_index_after_final_feasibility() { AssignmentRequest::root(2, 0, limits.max_augmenting_depth.unwrap_or(3)), ScalarAssignmentMoveOptions::for_construction(limits), AssignmentMoveIntent::required(), + &mut Vec::new(), &mut || false, ); assert_eq!( diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/augmenting_overlay.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/augmenting_overlay.rs index 396a4d575..670bd97d8 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/augmenting_overlay.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/augmenting_overlay.rs @@ -66,6 +66,7 @@ fn failed_augmenting_search_does_not_reorder_committed_indexes() { AssignmentRequest::root(1, 0, 2), ScalarAssignmentMoveOptions::for_construction(ScalarGroupLimits::new()), AssignmentMoveIntent::required(), + &mut Vec::new(), &mut || false, ); @@ -97,6 +98,7 @@ fn interrupted_augmenting_search_does_not_reorder_committed_indexes() { AssignmentRequest::root(2, 0, limits.max_augmenting_depth.unwrap()), ScalarAssignmentMoveOptions::for_construction(limits), AssignmentMoveIntent::required(), + &mut Vec::new(), &mut || { polls += 1; polls >= 5 @@ -455,6 +457,7 @@ fn sparse_augmenting_search_matches_small_reference_simulation() { AssignmentRequest::root(entity, value, options.max_depth), options, intent, + &mut Vec::new(), &mut || false, ) .map(|mov| { diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/control.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/control.rs index 19ba06b5b..300720d08 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/control.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/control.rs @@ -23,6 +23,7 @@ fn augmenting_assignment_observes_control_during_recursive_search() { AssignmentRequest::root(2, 0, limits.max_augmenting_depth.unwrap_or(3)), ScalarAssignmentMoveOptions::for_construction(limits), AssignmentMoveIntent::required(), + &mut Vec::new(), &mut || { polls += 1; polls >= 5 diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/neighborhood_contracts.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/neighborhood_contracts.rs index 71515317f..2048c9cfc 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/neighborhood_contracts.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/neighborhood_contracts.rs @@ -153,7 +153,13 @@ fn reassignment_preserves_required_blocker_rematching() { augmenting: false, }; let candidate = cursor - .next(&binding, &solution, &mut state, &mut || false) + .next( + &binding, + &solution, + &mut state, + &mut Vec::new(), + &mut || false, + ) .expect("the blocked target has a legal required-entity rematch"); assert_eq!(candidate.edits().len(), 2); assert!(candidate diff --git a/crates/solverforge-solver/src/phase/construction/placer.rs b/crates/solverforge-solver/src/phase/construction/placer.rs index 2fab5c665..27dd185ad 100644 --- a/crates/solverforge-solver/src/phase/construction/placer.rs +++ b/crates/solverforge-solver/src/phase/construction/placer.rs @@ -56,6 +56,18 @@ impl ConstructionTarget { pub(crate) fn is_empty(&self) -> bool { self.scalar_slots.is_empty() && self.group_slot.is_none() } + + /// Points the target at one scalar slot and an optional group slot, + /// reusing its slot buffer. + pub(crate) fn retarget( + &mut self, + scalar_slot: ConstructionSlotId, + group_slot: Option, + ) { + self.scalar_slots.clear(); + self.scalar_slots.push(scalar_slot); + self.group_slot = group_slot; + } } /// A placement represents an entity that needs a value assigned, @@ -159,6 +171,18 @@ where &mut self.candidates } + /// Points a reusable probe placement at another entity's construction + /// slots without allocating. + pub(crate) fn retarget( + &mut self, + entity_ref: EntityReference, + scalar_slot: ConstructionSlotId, + group_slot: Option, + ) { + self.entity_ref = entity_ref; + self.target.retarget(scalar_slot, group_slot); + } + /// Ends the placement, handing back its candidate cursor. pub(crate) fn into_candidates(self) -> C { self.candidates