From 08879eeace08d82ad981276504612de9ee05ebb7 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Tue, 1 Dec 2026 05:14:39 +0100 Subject: [PATCH 1/3] fix(solver): keep the pooled assignment state boxed in the grouped cursor #286 added path-search scratch to the assignment state and an edit buffer to its cursor, which grew the grouped-scalar leaf cursor from 1424 to 1552 bytes. The grouped cursor is the largest local-search leaf variant, so every local-search case allocated 128 more bytes per leaf: the gate against v0.31.4 failed allocated_bytes and peak_live_bytes on 14 cases (e.g. scalar_change +4096 / +128 bytes) with equal allocation counts. The cursor held the solve-owned pooled state inline, unboxed from the slot on open and boxed again on close. It now keeps the slot's box until activation moves the state into the assignment cursor, so the leaf carries one pointer instead of a 552-byte state, and a step that never activates hands the same box back. Gate smoke against v0.31.4 (4 iterations, identical order hashes): scalar_swap 33636 / 8409 bytes allocated / peak (v0.31.4: 35300 / 8825), list_change 33581352 / 4201066 (33583016 / 4201482). --- .../src/builder/selector/grouped_scalar.rs | 15 ++++++++++----- .../grouped_scalar/tests/pool_differential.rs | 3 +-- .../compiler/executor/local_search/cursor.rs | 2 +- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs b/crates/solverforge-solver/src/builder/selector/grouped_scalar.rs index bd04b3bc..5b5176b2 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/phase/construction/grouped_scalar/tests/pool_differential.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/pool_differential.rs index fca47a62..b9efb1ec 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 dd02f3f0..f413f379 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(); } } } From 8bdbf9b8882bc26ef82c81bf69838c49fdfd7b3a Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Tue, 1 Dec 2026 05:41:15 +0100 Subject: [PATCH 2/3] perf(solver): lend a single-entity compound move's index from its edit A compound scalar move kept a sorted list of the entities its edits name, allocated on every move. Required construction now commits one single-row move per placement, so that list was one allocation and one free per placed row. A move whose edits all name one entity now lends that index from its first edit and allocates no list. --- .../src/heuristic/move/compound_scalar.rs | 32 +++++++++++++++---- .../heuristic/move/tests/compound_scalar.rs | 25 +++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs b/crates/solverforge-solver/src/heuristic/move/compound_scalar.rs index 4527fc62..16d5a108 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 2b52a871..225f2f92 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()); +} From 2f9aadf77dc6031b0dec3c5b614b620657e0f190 Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Tue, 1 Dec 2026 05:55:13 +0100 Subject: [PATCH 3/3] perf(solver): keep short assignment index member lists inline The assignment state indexes rows by capacity key, by value and by (value, sequence); each key held its rows in a heap Vec. Required construction now records every placed row in the state, so a placement allocated a member list for each new capacity and sequence key, and dropping the state freed them all. Member lists keep up to two rows inline: a capacity or sequence key holds one row in a feasible plan, so placing a row allocates no list. --- .../grouped_scalar/assignment_overlay.rs | 4 +-- .../grouped_scalar/assignment_state.rs | 27 ++++++++++++------- .../assignment_state/membership.rs | 4 +-- 3 files changed, 22 insertions(+), 13 deletions(-) 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 8d47d9a7..1acb8e6d 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 f151cc80..dd9783ed 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 4a5b1257..1df828bf 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);