diff --git a/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs b/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs index bd04b3bcc..5b5176b24 100644 --- a/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs +++ b/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs @@ -73,7 +73,11 @@ where activation: Option>, assignment_cursor: Option>, - pooled_assignment: Option, + /* The solve-owned assignment base, kept boxed until activation moves it + into the assignment cursor, so every leaf cursor carries one pointer for + it instead of the whole state. */ + pooled_assignment: + Option>, require_hard_improvement: bool, } @@ -169,7 +173,7 @@ where pooled.refresh_rows(assignment, solution, rows); } crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::with_pooled_state( - assignment, solution, options, pooled, + assignment, solution, options, *pooled, ) } // Structural change (entity count moved): the sparse @@ -234,11 +238,12 @@ impl GroupedScalarCursor<'_, S> { /// Hands the assignment base back to the solve-owned slot when the step /// closes. Steps that never activated keep the returned pool as retained /// state; steps after activation move the maintained base back. - pub(crate) fn into_pooled_assignment(mut self) -> Option { + pub(crate) fn into_pooled_assignment(mut self) -> Option> { let returned = self .assignment_cursor .take() - .map(crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::into_state); + .map(crate::phase::construction::grouped_scalar::ScalarAssignmentMoveCursor::into_state) + .map(Box::new); let pooled = returned.or_else(|| self.pooled_assignment.take()); drop(self); pooled @@ -350,7 +355,7 @@ impl GroupedScalarSelector { context: MoveStreamContext, ) -> GroupedScalarCursor<'a, S> { let mut cursor = self.open_cursor_with_context(score_director, context); - cursor.pooled_assignment = state.take().map(|boxed| *boxed); + cursor.pooled_assignment = state.take(); cursor } } diff --git a/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs b/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs index 4527fc62c..16d5a108e 100644 --- a/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs +++ b/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs @@ -160,6 +160,10 @@ pub(crate) struct CompoundScalarMove { reason: &'static str, variable_label: &'static str, edits: Vec>, + /* The sorted, distinct entities of a move that edits more than one; + empty when every edit names the first edit's entity, which + `entity_indices` then lends from that edit, so a single-entity move + allocates no index list. */ entity_indices: Vec, require_hard_improvement: bool, construction_value_order_key: Option, @@ -175,12 +179,21 @@ impl CompoundScalarMove { variable_label: &'static str, edits: Vec>, ) -> Self { - let mut entity_indices = edits - .iter() - .map(|edit| edit.entity_index) - .collect::>(); - entity_indices.sort_unstable(); - entity_indices.dedup(); + let single_entity = edits.split_first().is_none_or(|(first, rest)| { + rest.iter() + .all(|edit| edit.entity_index == first.entity_index) + }); + let entity_indices = if single_entity { + Vec::new() + } else { + let mut entity_indices = edits + .iter() + .map(|edit| edit.entity_index) + .collect::>(); + entity_indices.sort_unstable(); + entity_indices.dedup(); + entity_indices + }; Self { reason, variable_label, @@ -309,7 +322,12 @@ where } fn entity_indices(&self) -> &[usize] { - &self.entity_indices + match self.edits.first() { + Some(first) if self.entity_indices.is_empty() => { + std::slice::from_ref(&first.entity_index) + } + _ => &self.entity_indices, + } } fn variable_name(&self) -> &str { diff --git a/crates/solverforge-solver/src/heuristic/move/tests/compound_scalar.rs b/crates/solverforge-solver/src/heuristic/move/tests/compound_scalar.rs index 2b52a871d..225f2f920 100644 --- a/crates/solverforge-solver/src/heuristic/move/tests/compound_scalar.rs +++ b/crates/solverforge-solver/src/heuristic/move/tests/compound_scalar.rs @@ -310,3 +310,28 @@ fn compound_scalar_rejects_noop_and_illegal_edits() { let illegal = CompoundScalarMove::new("illegal", vec![illegal_edit]); assert!(!illegal.is_doable(&director)); } + +#[test] +fn compound_move_lists_each_edited_entity_once_in_order() { + let single = CompoundScalarMove::new( + "test", + vec![ + compound_edit(0, 4, 0, "left", Some(3), get_left, set_left), + compound_edit(0, 4, 1, "right", Some(3), get_right, set_right), + ], + ); + assert_eq!(single.entity_indices(), &[4]); + + let several = CompoundScalarMove::new( + "test", + vec![ + compound_edit(0, 2, 0, "left", Some(3), get_left, set_left), + compound_edit(0, 0, 0, "left", Some(3), get_left, set_left), + compound_edit(0, 2, 1, "right", Some(3), get_right, set_right), + ], + ); + assert_eq!(several.entity_indices(), &[0, 2]); + + let empty = CompoundScalarMove::::new("test", Vec::new()); + assert!(empty.entity_indices().is_empty()); +} diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_overlay.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_overlay.rs index 8d47d9a77..1acb8e6d2 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_overlay.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_overlay.rs @@ -129,7 +129,7 @@ impl OverlayScratch { value: usize, ) -> bool { if let Some(key) = group.capacity_key(solution, entity, value) { - let count = state.occupancy.get(&key).map_or(0, Vec::len); + let count = state.occupancy.get(&key).map_or(0, |members| members.len()); let delta = self.capacity_deltas.get(&key).copied().unwrap_or(0); if !count.checked_add_signed(delta).is_some_and(|n| n <= 1) { return false; @@ -164,7 +164,7 @@ impl OverlayScratch { fn capacity_feasible(&self, state: &ScalarAssignmentState) -> bool { self.capacity_deltas.iter().all(|(key, delta)| { - let count = state.occupancy.get(key).map_or(0, Vec::len); + let count = state.occupancy.get(key).map_or(0, |members| members.len()); count.checked_add_signed(*delta).is_some_and(|n| n <= 1) }) } 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 f151cc805..dd9783edb 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,6 +8,7 @@ mod pressure; use super::assignment_path_overlay::AssignmentPathOverlay; use overlay::OverlayScratch; +use smallvec::SmallVec; use solverforge_core::fast_hash::{FastMap, FastSet}; mod membership; @@ -16,14 +17,19 @@ mod membership; #[path = "tests/membership_keys.rs"] mod membership_keys; +/* The sorted rows of one index key. A capacity or sequence key holds one row +in a feasible plan, so its members stay inline and placing a row allocates +no member list. */ +type Members = SmallVec<[usize; 2]>; + pub(crate) struct ScalarAssignmentState { values: Vec>, capacity_keys: Vec>, sequence_keys: Vec>, required: Vec, - occupancy: FastMap>, - assigned_by_value: FastMap>, - assigned_by_sequence: FastMap<(usize, usize), Vec>, + occupancy: FastMap, + assigned_by_value: FastMap, + assigned_by_sequence: FastMap<(usize, usize), Members>, /* Pooled scratch for the hot per-candidate feasibility path; each field serves one nesting level (take/restore, allocated once grown). */ overlay: OverlayScratch, @@ -59,19 +65,19 @@ impl ScalarAssignmentState { let mut occupancy = self .occupancy .iter() - .map(|(key, entities)| (*key, entities.clone())) + .map(|(key, entities)| (*key, entities.to_vec())) .collect::>(); occupancy.sort_by_key(|(key, _)| *key); let mut assigned_by_value = self .assigned_by_value .iter() - .map(|(key, entities)| (*key, entities.clone())) + .map(|(key, entities)| (*key, entities.to_vec())) .collect::>(); assigned_by_value.sort_by_key(|(key, _)| *key); let mut assigned_by_sequence = self .assigned_by_sequence .iter() - .map(|(key, entities)| (*key, entities.clone())) + .map(|(key, entities)| (*key, entities.to_vec())) .collect::>(); assigned_by_sequence.sort_by_key(|(key, _)| *key); AssignmentIndexSnapshot { @@ -124,7 +130,7 @@ impl ScalarAssignmentState { pub(super) fn assigned_count(&self, value: usize) -> usize { self.assigned_by_value .get(&value) - .map(Vec::len) + .map(Members::len) .unwrap_or(0) } @@ -161,13 +167,16 @@ impl ScalarAssignmentState { } pub(super) fn capacity_occupants(&self, key: usize) -> &[usize] { - self.occupancy.get(&key).map(Vec::as_slice).unwrap_or(&[]) + self.occupancy + .get(&key) + .map(Members::as_slice) + .unwrap_or(&[]) } pub(super) fn sequence_members(&self, value: usize, sequence: usize) -> &[usize] { self.assigned_by_sequence .get(&(value, sequence)) - .map(Vec::as_slice) + .map(Members::as_slice) .unwrap_or(&[]) } diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state/membership.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state/membership.rs index 4a5b12570..1df828bf0 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state/membership.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_state/membership.rs @@ -59,7 +59,7 @@ impl ScalarAssignmentState { } } -fn remove_member(map: &mut FastMap>, key: K, entity: usize) { +fn remove_member(map: &mut FastMap, key: K, entity: usize) { let Some(members) = map.get_mut(&key) else { return; }; @@ -71,7 +71,7 @@ fn remove_member(map: &mut FastMap>, key: } } -fn insert_member(map: &mut FastMap>, key: K, entity: usize) { +fn insert_member(map: &mut FastMap, key: K, entity: usize) { let members = map.entry(key).or_default(); if let Err(position) = members.binary_search(&entity) { members.insert(position, entity); diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/pool_differential.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/pool_differential.rs index fca47a628..b9efb1ecf 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/pool_differential.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/pool_differential.rs @@ -140,8 +140,7 @@ fn pooled_assignment_base_matches_rebuild_across_random_sequences() { let pooled_rows = pooled_stream(&mut pooled_cursor, director.working_solution()); pool = pooled_cursor .into_pooled_assignment() - .filter(|state| state.row_count() == director.working_solution().values.len()) - .map(Box::new); + .filter(|state| state.row_count() == director.working_solution().values.len()); let rebuilt = ScalarAssignmentState::new(binding, director.working_solution()); if let Some(state) = &pool { diff --git a/crates/solverforge-solver/src/runtime/compiler/executor/local_search/cursor.rs b/crates/solverforge-solver/src/runtime/compiler/executor/local_search/cursor.rs index dd02f3f01..f413f379e 100644 --- a/crates/solverforge-solver/src/runtime/compiler/executor/local_search/cursor.rs +++ b/crates/solverforge-solver/src/runtime/compiler/executor/local_search/cursor.rs @@ -243,7 +243,7 @@ where ) = (&mut leaf_cursor.inner, slot) { if let Some(grouped) = grouped.take() { - *pooled = grouped.into_pooled_assignment().map(Box::new); + *pooled = grouped.into_pooled_assignment(); } } }