From d5ebb89ec9acc000d6ceeae14af01acbf0330cbf Mon Sep 17 00:00:00 2001 From: Vittorio Distefano Date: Mon, 30 Nov 2026 16:24:43 +0100 Subject: [PATCH 1/2] bench(solver): measure only the neighborhood in assignment_neighborhood The neighborhood case built its starting roster with a construction solve, so the case also ran the construction code under change and its heap layout moved with it. Build a feasible roster directly instead: shift s of day d goes to nurse (s + 6d) mod 24, which keeps each nurse on one shift a day and on the same shift type from day to day. One iteration enumerates every grouped-scalar family in about 15 ms, so the case now measures four iterations per trial (about 60 ms) instead of the default, which brings the full gate back to its usual length. --- .../selector_cursor_gate/assignment_cases.rs | 44 +++++++++++-------- scripts/bench-zero-regression.sh | 7 ++- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs b/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs index 2859ec4d..ab4e52b9 100644 --- a/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs +++ b/crates/solverforge-solver/benches/selector_cursor_gate/assignment_cases.rs @@ -1,19 +1,19 @@ -/* Grouped-scalar required construction through the compiled runtime. +/* Grouped-scalar assignment cases over a rostering-shaped assignment group: +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). -`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_required` solves the group with the default runtime, whose +required cursor places every row one move at a time: the work a generated +rostering model pays before local search. The configuration sets no termination, so the default +runtime ends the solve after construction. The cross-tree order hash is the +constructed roster. `assignment_neighborhood` enumerates the compiled grouped-scalar -local-search neighborhood of the same group over the constructed roster: +local-search neighborhood of the same group over a fixed feasible 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. */ +augmenting-path repairs. The roster is built directly, so the case measures +only the neighborhood. */ const ASSIGNMENT_DAYS: usize = 28; const ASSIGNMENT_SHIFTS_PER_DAY: usize = 18; @@ -153,13 +153,21 @@ fn assignment_required() { }); } -/* The roster the default runtime constructs; local search starts here. */ +/* A feasible roster: shift `s` of day `d` goes to nurse `(s + 6d) mod 24`, +so a nurse works at most one shift a day and keeps its shift type from one +day to the next, which never puts a late shift before an early one. */ 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() + Plan { + vehicles: (0..ASSIGNMENT_ROWS) + .map(|entity| Vehicle { + visits: vec![ + (entity % ASSIGNMENT_SHIFTS_PER_DAY + 6 * assignment_day(entity)) + % ASSIGNMENT_NURSES, + ], + }) + .collect(), + score: None, + } } fn assignment_neighborhood() { diff --git a/scripts/bench-zero-regression.sh b/scripts/bench-zero-regression.sh index 793bbe52..04be9ced 100755 --- a/scripts/bench-zero-regression.sh +++ b/scripts/bench-zero-regression.sh @@ -84,6 +84,9 @@ FULL_LIST_MEASURE_ITERATIONS=${FULL_LIST_MEASURE_ITERATIONS:-4} # `group_ruin`. ROUTE_ROWS_MEASURE_ITERATIONS=${ROUTE_ROWS_MEASURE_ITERATIONS:-2} GROUP_RUIN_MEASURE_ITERATIONS=${GROUP_RUIN_MEASURE_ITERATIONS:-1} +# One assignment_neighborhood iteration enumerates every grouped-scalar family +# (about 15 ms), so four iterations keep its trial near 60 ms. +ASSIGNMENT_NEIGHBORHOOD_MEASURE_ITERATIONS=${ASSIGNMENT_NEIGHBORHOOD_MEASURE_ITERATIONS:-4} TOOLCHAIN=${TOOLCHAIN:-1.95.0} RESULTS=${RESULTS:-"/tmp/solverforge-zero-regression-$(date +%Y%m%d-%H%M%S)"} # Opt-in scoring cases (not in the default selector set): BENCH_CASES="scoring @@ -151,6 +154,8 @@ measure_iterations_for_case() { printf '%s\n' "$ROUTE_ROWS_MEASURE_ITERATIONS" elif [[ $case_name == group_ruin ]]; then printf '%s\n' "$GROUP_RUIN_MEASURE_ITERATIONS" + elif [[ $case_name == assignment_neighborhood ]]; then + printf '%s\n' "$ASSIGNMENT_NEIGHBORHOOD_MEASURE_ITERATIONS" else printf '%s\n' "$MEASURE_ITERATIONS" fi @@ -396,7 +401,7 @@ if [[ $BENCH_ISOLATE == 1 ]]; then fi cat >"$RESULTS/environment.json" < Date: Mon, 30 Nov 2026 16:24:43 +0100 Subject: [PATCH 2/2] fix(solver): place required assignments through the construction cursor n120w8 rostering instances (2844 and 2872 required shifts) ended a 1 s solve with every required shift unassigned (#283). Required construction committed one dense batch move that placed all directly placeable rows outside the cursor and outside incremental scoring; after 3992802b its pending view made that batch quadratic, and it timed out before publishing anything. Remove the batch. Required rows are placed one move at a time by the required cursor and scored incrementally, and the cursor no longer redoes whole-problem work per placement: - The placer cursor keeps the assignment generator across placements (`recycle`), refreshes only the rows the placement's candidates touched, drops newly assigned rows from the value degrees and resumes after the placed row. A generator that finds nothing more is rebuilt from the solution once, so rows skipped earlier get another pass. - Completed construction slots are probed only for rows that can be completed at the current revision instead of every row of the group. - A required row tries every value directly before any value with augmenting rematches, so a row with a free value never pays for a rematch search. This also reverts the path-overlay index of 9ab0b17c, which only served the batch, and keeps the scanning overlay of 0.31.4. Both instances now finish feasible at 1 s: H0 0hard/-224820soft (2844 placements in 69 ms), H1 0hard/-223990soft (2872 in 75 ms). Fixes #283 --- AGENTS.md | 2 +- crates/solverforge-solver/WIREFRAME.md | 5 +- .../grouped_scalar/assignment_entity.rs | 152 ++++---- .../grouped_scalar/assignment_family.rs | 16 +- .../grouped_scalar/assignment_path.rs | 15 +- .../grouped_scalar/assignment_path_overlay.rs | 328 ++++-------------- .../assignment_required_batch.rs | 139 -------- .../grouped_scalar/assignment_scarcity.rs | 96 +++++ .../grouped_scalar/assignment_stream.rs | 79 +++-- .../phase/construction/grouped_scalar/mod.rs | 3 +- .../construction/grouped_scalar/placer.rs | 45 ++- .../grouped_scalar/placer_resume.rs | 127 +++++++ .../grouped_scalar/placer_stream.rs | 71 ++-- .../construction/grouped_scalar/tests.rs | 54 +-- .../tests/construction_resume.rs | 82 +++++ .../grouped_scalar/tests/control.rs | 84 ----- .../tests/neighborhood_contracts.rs | 1 + .../tests/path_overlay_index.rs | 298 ---------------- docs/configuration.md | 5 +- 19 files changed, 580 insertions(+), 1022 deletions(-) delete mode 100644 crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs create mode 100644 crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs create mode 100644 crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs create mode 100644 crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs delete mode 100644 crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/path_overlay_index.rs diff --git a/AGENTS.md b/AGENTS.md index e17e9f5e..80ea4700 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -302,7 +302,7 @@ runs: (`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, + runtime's required cursor 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. diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 98b1dd3d..596534d0 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -240,8 +240,8 @@ src/ │ │ ├── grouped_scalar/assignment_family.rs — Shared assignment candidate-family deduplication │ │ ├── grouped_scalar/assignment_pair.rs — Deterministic bounded pair, rematch, and sequence-window move generation │ │ ├── grouped_scalar/assignment_path.rs — Bounded augmenting-path move construction for required and optional scalar assignments -│ │ ├── grouped_scalar/assignment_path_overlay.rs — Sparse reversible augmenting-path and required-batch discovery state -│ │ ├── grouped_scalar/assignment_required_batch.rs — Dense hard-first required assignment allocation +│ │ ├── grouped_scalar/assignment_path_overlay.rs — Sparse reversible augmenting-path discovery state +│ │ ├── grouped_scalar/assignment_scarcity.rs — Required-row scarcity order and value degrees │ │ ├── grouped_scalar/assignment_state.rs — Committed assignment occupancy, capacity, and conflict bookkeeping │ │ ├── grouped_scalar/assignment_overlay.rs — Sparse final-edit capacity and sequence-rule validation without mutating assignment indexes │ │ ├── grouped_scalar/assignment_pressure.rs — Current-value and sequence-pressure candidate ordering @@ -255,6 +255,7 @@ src/ │ │ ├── grouped_scalar/placement.rs — Grouped scalar construction-target and move-strength helpers │ │ ├── grouped_scalar/phase.rs — ScalarGroupConstruction builder that feeds grouped scalar placements into stock ConstructionHeuristicPhase │ │ ├── grouped_scalar/placer.rs — ScalarGroupPlacer adapter that opens one cursor-backed placement at a time for provider and assignment groups +│ │ ├── grouped_scalar/placer_resume.rs — Assignment placement generator carried across committed placements │ │ └── grouped_scalar/placer_stream.rs — Concrete candidate and assignment placement stream helpers │ ├── localsearch/ │ │ ├── mod.rs — Acceptor, local-search acceptor/forager, and LocalSearchPhase re-exports 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 11d94ef5..ba7666ac 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 @@ -6,10 +6,10 @@ use super::assignment_candidate::{ use super::assignment_path::{ assignment_move_for_entity_value, move_from_edits, AssignmentRequest, }; +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::phase::control::GENERATION_POLL_INTERVAL; use solverforge_core::fast_hash::{FastMap, FastSet}; pub(super) struct EntityValueCursor { @@ -20,6 +20,10 @@ pub(super) struct EntityValueCursor { pub(super) value_degrees: FastMap, pub(super) options: ScalarAssignmentMoveOptions, pub(super) kind: AssignmentMoveKind, + /* Required rows try every value directly (search depth 0) before any + value with augmenting rematches, so a row with a free value never pays + for a rematch search. False during the direct pass. */ + pub(super) augmenting: bool, } impl EntityValueCursor { @@ -46,6 +50,7 @@ impl EntityValueCursor { self.entity_pos += 1; self.values.clear(); self.value_pos = 0; + self.augmenting = false; continue; } if self.values.is_empty() { @@ -80,7 +85,7 @@ impl EntityValueCursor { group, solution, state, - AssignmentRequest::root(entity_index, value, self.options.max_depth), + AssignmentRequest::root(entity_index, value, self.request_depth()), self.options, intent, should_stop, @@ -93,12 +98,64 @@ impl EntityValueCursor { return Some(mov); } } + if self.kind == AssignmentMoveKind::Required + && !self.augmenting + && self.options.max_depth > 0 + { + self.augmenting = true; + self.value_pos = 0; + continue; + } self.entity_pos += 1; self.values.clear(); self.value_pos = 0; + self.augmenting = false; } None } + + fn request_depth(&self) -> usize { + if self.kind == AssignmentMoveKind::Required && !self.augmenting { + 0 + } else { + self.options.max_depth + } + } + + /* Carries the cursor past a finished placement: generation moves past + `placed` and restarts the value list of the row it stands on, whose + candidates were built before the placement was committed. */ + pub(super) fn resume_after_placement(&mut self, placed: usize) { + if self.entities.get(self.entity_pos) == Some(&placed) { + self.entity_pos += 1; + } + self.values.clear(); + self.value_pos = 0; + self.augmenting = false; + } + + /* Drops a newly assigned required row from the value degrees, so the + degrees keep counting only the rows that still need a value. */ + pub(super) fn retire_required_row( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + entity_index: usize, + ) { + 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) { + *degree -= 1; + if *degree == 0 { + self.value_degrees.remove(&value); + } + } + } + } } #[derive(Clone, Copy, PartialEq, Eq)] @@ -209,6 +266,7 @@ impl CapacityCursor { value_degrees: FastMap::default(), options: self.options, kind: AssignmentMoveKind::CapacityRepair, + augmenting: false, }); } } @@ -372,93 +430,3 @@ pub(super) fn assigned_entities_by_position( }); entities } - -pub(super) fn required_entities_by_scarcity( - group: &ScalarAssignmentBinding, - solution: &S, - state: &ScalarAssignmentState, - value_candidate_limit: Option, - should_stop: &mut ShouldStop, -) -> Option> -where - S: PlanningSolution, - ShouldStop: FnMut() -> bool, -{ - let mut entities = Vec::new(); - for entity_index in 0..group.entity_count(solution) { - if should_stop() { - return None; - } - 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(); - if should_stop() { - return None; - } - entities.push(( - candidate_count, - group.entity_order_key(solution, entity_index), - entity_index, - )); - } - entities.sort_unstable(); - if should_stop() { - return None; - } - Some( - entities - .into_iter() - .map(|(_, _, entity_index)| entity_index) - .collect(), - ) -} - -pub(super) fn required_value_degrees( - group: &ScalarAssignmentBinding, - solution: &S, - entities: &[usize], - value_candidate_limit: Option, - should_stop: &mut ShouldStop, -) -> Option> -where - S: PlanningSolution, - ShouldStop: FnMut() -> bool, -{ - let mut degrees = FastMap::default(); - let mut processed_edges = 0usize; - for entity_index in entities { - if should_stop() { - return None; - } - for value in group.candidate_values(solution, *entity_index, value_candidate_limit) { - *degrees.entry(value).or_insert(0) += 1; - processed_edges += 1; - if processed_edges.is_multiple_of(GENERATION_POLL_INTERVAL) && should_stop() { - return None; - } - } - } - if should_stop() { - return None; - } - Some(degrees) -} - -pub(super) fn sort_values_by_required_scarcity( - group: &ScalarAssignmentBinding, - solution: &S, - entity_index: usize, - degrees: &FastMap, - values: &mut [usize], -) { - values.sort_by_key(|value| { - ( - degrees.get(value).copied().unwrap_or(usize::MAX), - group.value_order_key(solution, entity_index, *value), - *value, - ) - }); -} diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_family.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_family.rs index 18393b32..9959fad7 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_family.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_family.rs @@ -6,10 +6,10 @@ use super::assignment_block::{ use super::assignment_candidate::{order_candidates, ScalarAssignmentMoveOptions}; use super::assignment_cycle::CycleWindowCursor; use super::assignment_entity::{ - required_entities_by_scarcity, required_value_degrees, AssignmentMoveKind, CapacityCursor, - EntityValueCursor, OptionalAdjustmentCursor, + AssignmentMoveKind, CapacityCursor, EntityValueCursor, OptionalAdjustmentCursor, }; use super::assignment_pair::PairWindowCursor; +use super::assignment_scarcity::{required_entities_by_scarcity, required_value_degrees}; use super::assignment_state::ScalarAssignmentState; use super::assignment_value_cycle::ValueWindowCycleCursor; use super::assignment_value_release::ValueRunReleaseCursor; @@ -98,9 +98,20 @@ impl AssignmentFamilyCursor { value_degrees, options, kind: AssignmentMoveKind::Required, + augmenting: false, })) } + /* Carries an entity-value cursor past a finished placement; any other + family reopens against the committed state. */ + pub(super) fn resume_after_placement(&mut self, placed: usize) { + match self { + Self::EntityValues(cursor) => cursor.resume_after_placement(placed), + Self::Empty => {} + _ => *self = Self::Empty, + } + } + pub(super) fn entity_values( mut entities: Vec, options: ScalarAssignmentMoveOptions, @@ -115,6 +126,7 @@ impl AssignmentFamilyCursor { value_degrees: FastMap::default(), options, kind, + augmenting: 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 8b9010d6..548e08a8 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,8 +164,7 @@ impl AugmentingPathSearch<'_, S> { if state.is_required(blocker) { continue; } - work.overlay - .set_value(state, self.group, self.solution, blocker, None); + work.overlay.set_value(state, blocker, None); work.edits.push(self.group.edit(blocker, None)); } // State changed after the displacements; re-derive both blockers @@ -196,8 +195,7 @@ impl AugmentingPathSearch<'_, S> { } if work.blockers.is_empty() { - work.overlay - .set_value(state, self.group, self.solution, entity_index, Some(value)); + work.overlay.set_value(state, entity_index, Some(value)); work.edits.push(self.group.edit(entity_index, Some(value))); return true; } @@ -259,19 +257,16 @@ impl AugmentingPathSearch<'_, S> { ), } { - work.overlay - .rollback(self.group, self.solution, overlay_checkpoint); + work.overlay.rollback(overlay_checkpoint); work.edits.truncate(edit_checkpoint); continue; } - work.overlay - .set_value(state, self.group, self.solution, entity_index, Some(value)); + work.overlay.set_value(state, entity_index, Some(value)); work.edits.push(self.group.edit(entity_index, Some(value))); work.visiting.remove(&entity_index); return true; } - work.overlay - .rollback(self.group, self.solution, overlay_checkpoint); + work.overlay.rollback(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 efdf4677..849fd6bf 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,67 +3,20 @@ 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>)>, - 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) - } + left_members: Vec, + right_members: Vec, } impl AssignmentPathOverlay { pub(super) fn clear(&mut self) { self.changed.clear(); self.journal.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); + self.left_members.clear(); + self.right_members.clear(); } pub(super) fn checkpoint(&self) -> usize { @@ -77,171 +30,39 @@ impl AssignmentPathOverlay { ) -> Option { self.changed .get(&entity) - .map_or_else(|| state.current_value(entity), PendingValue::value) + .copied() + .unwrap_or_else(|| state.current_value(entity)) } - 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.get(&entity).map(PendingValue::value); - self.replace(group, solution, entity, previous.flatten(), Some(value)); + let previous = self.changed.insert(entity, value); self.journal.push((entity, previous)); } - pub(super) fn rollback( - &mut self, - group: &ScalarAssignmentBinding, - solution: &S, - checkpoint: usize, - ) { + pub(super) fn rollback(&mut self, checkpoint: usize) { while self.journal.len() > checkpoint { let (entity, previous) = self.journal.pop().expect("journal length was checked"); - let current = self.changed.get(&entity).and_then(PendingValue::value); - self.replace(group, solution, entity, current, previous); - } - } - - /* 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, - ); + match previous { + Some(value) => { + self.changed.insert(entity, value); + } + None => { + self.changed.remove(&entity); + } + } } } - 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, + &mut self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -251,8 +72,7 @@ impl AssignmentPathOverlay { ) -> Option { blockers.clear(); if let Some(key) = group.capacity_key(solution, entity, value) { - let occupants = state.capacity_occupants(key); - for occupant in occupants { + for occupant in state.capacity_occupants(key) { if *occupant != entity && self.current_value(state, *occupant).is_some_and(|current| { group.capacity_key(solution, *occupant, current) == Some(key) @@ -261,10 +81,17 @@ impl AssignmentPathOverlay { blockers.push(*occupant); } } - blockers.extend( - self.capacity_chain(key) - .filter(|arrival| *arrival != entity && !occupants.contains(arrival)), - ); + 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); + } } let verdict = self.push_rule_blockers(state, group, solution, entity, value, blockers); @@ -274,7 +101,7 @@ impl AssignmentPathOverlay { } pub(super) fn assignment_allowed( - &self, + &mut self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -286,7 +113,7 @@ impl AssignmentPathOverlay { } fn push_rule_blockers( - &self, + &mut self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -307,8 +134,11 @@ impl AssignmentPathOverlay { .into_iter() .flatten() { + self.collect_members(state, group, solution, value, adjacent, true); blockers.extend( - self.members(state, value, adjacent) + self.left_members + .iter() + .copied() .filter(|blocker| *blocker != entity), ); } @@ -316,7 +146,7 @@ impl AssignmentPathOverlay { } fn rule_allows( - &self, + &mut self, state: &ScalarAssignmentState, group: &ScalarAssignmentBinding, solution: &S, @@ -330,7 +160,8 @@ impl AssignmentPathOverlay { return true; }; if let Some(previous) = sequence.checked_sub(1) { - if self.members(state, value, previous).any(|left| { + self.collect_members(state, group, solution, value, previous, true); + if self.left_members.iter().copied().any(|left| { left != entity && !group.assignment_edge_allowed(solution, left, value, entity, value) }) { @@ -338,7 +169,8 @@ impl AssignmentPathOverlay { } } if let Some(next) = sequence.checked_add(1) { - if self.members(state, value, next).any(|right| { + self.collect_members(state, group, solution, value, next, false); + if self.right_members.iter().copied().any(|right| { right != entity && !group.assignment_edge_allowed(solution, entity, value, right, value) }) { @@ -347,53 +179,41 @@ impl AssignmentPathOverlay { } true } -} - -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); + 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 } else { - *head = following; + &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); + } } - 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; + 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); } - 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 deleted file mode 100644 index 65aa39b9..00000000 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_required_batch.rs +++ /dev/null @@ -1,139 +0,0 @@ -use solverforge_core::domain::PlanningSolution; -use solverforge_core::fast_hash::FastSet; - -use super::assignment_candidate::{ - order_candidates, AssignmentMoveIntent, ScalarAssignmentMoveOptions, -}; -use super::assignment_entity::{ - required_entities_by_scarcity, required_value_degrees, sort_values_by_required_scarcity, -}; -use super::assignment_path::{ - move_from_edits, AssignmentPathWork, AssignmentRequest, AugmentingPathSearch, -}; -use super::assignment_state::ScalarAssignmentState; -use crate::builder::ScalarAssignmentBinding; -use crate::heuristic::r#move::CompoundScalarMove; - -pub(super) fn required_batch_move( - group: &ScalarAssignmentBinding, - solution: &S, - state: &mut ScalarAssignmentState, - options: ScalarAssignmentMoveOptions, - should_stop: &mut ShouldStop, -) -> Option> -where - S: PlanningSolution, - ShouldStop: FnMut() -> bool, -{ - let mut entities = required_entities_by_scarcity( - group, - solution, - state, - options.value_candidate_limit, - should_stop, - )?; - order_candidates(&mut entities, options); - if should_stop() { - return None; - } - let value_degrees = required_value_degrees( - group, - solution, - &entities, - options.value_candidate_limit, - should_stop, - )?; - let mut scalar_edits = Vec::new(); - 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 { - if should_stop() { - overlay.clear(); - state.restore_path_overlay(overlay); - return None; - } - if overlay.current_value(state, entity_index).is_some() { - continue; - } - let mut values = - group.candidate_values(solution, entity_index, options.value_candidate_limit); - sort_values_by_required_scarcity( - group, - solution, - entity_index, - &value_degrees, - &mut values, - ); - for value in values { - if should_stop() { - overlay.clear(); - state.restore_path_overlay(overlay); - return None; - } - let overlay_checkpoint = overlay.checkpoint(); - let edit_checkpoint = scalar_edits.len(); - visiting.clear(); - let mut work = AssignmentPathWork::new( - &mut overlay, - &mut visiting, - &mut scalar_edits, - &mut blockers, - ); - if !search.discover( - state, - // The batch below can retain only independent single-entity edits. - // Defer augmenting rematches to the following required cursor, - // where their multi-entity edits can actually be applied. - AssignmentRequest::root(entity_index, value, 0), - &mut work, - should_stop, - ) { - overlay.rollback(group, solution, overlay_checkpoint); - scalar_edits.truncate(edit_checkpoint); - if should_stop() { - overlay.clear(); - state.restore_path_overlay(overlay); - return None; - } - 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.len() != 1 { - 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(group, solution, overlay_checkpoint); - scalar_edits.truncate(edit_checkpoint); - continue; - } - break; - } - } - if should_stop() { - overlay.clear(); - state.restore_path_overlay(overlay); - return None; - } - // 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; - } - if !state.scalar_edits_feasible(group, solution, &scalar_edits) { - return None; - } - move_from_edits(group, solution, &scalar_edits, "scalar_assignment_required") -} 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 new file mode 100644 index 00000000..d2f4217e --- /dev/null +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/assignment_scarcity.rs @@ -0,0 +1,96 @@ +use solverforge_core::domain::PlanningSolution; +use solverforge_core::fast_hash::FastMap; + +use super::assignment_state::ScalarAssignmentState; +use crate::builder::ScalarAssignmentBinding; +use crate::phase::control::GENERATION_POLL_INTERVAL; + +pub(super) fn required_entities_by_scarcity( + group: &ScalarAssignmentBinding, + solution: &S, + state: &ScalarAssignmentState, + value_candidate_limit: Option, + should_stop: &mut ShouldStop, +) -> Option> +where + S: PlanningSolution, + ShouldStop: FnMut() -> bool, +{ + let mut entities = Vec::new(); + for entity_index in 0..group.entity_count(solution) { + if should_stop() { + return None; + } + 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(); + if should_stop() { + return None; + } + entities.push(( + candidate_count, + group.entity_order_key(solution, entity_index), + entity_index, + )); + } + entities.sort_unstable(); + if should_stop() { + return None; + } + Some( + entities + .into_iter() + .map(|(_, _, entity_index)| entity_index) + .collect(), + ) +} + +pub(super) fn required_value_degrees( + group: &ScalarAssignmentBinding, + solution: &S, + entities: &[usize], + value_candidate_limit: Option, + should_stop: &mut ShouldStop, +) -> Option> +where + S: PlanningSolution, + ShouldStop: FnMut() -> bool, +{ + let mut degrees = FastMap::default(); + let mut processed_edges = 0usize; + for entity_index in entities { + if should_stop() { + return None; + } + for value in group.candidate_values(solution, *entity_index, value_candidate_limit) { + *degrees.entry(value).or_insert(0) += 1; + processed_edges += 1; + if processed_edges.is_multiple_of(GENERATION_POLL_INTERVAL) && should_stop() { + return None; + } + } + } + if should_stop() { + return None; + } + Some(degrees) +} + +pub(super) fn sort_values_by_required_scarcity( + group: &ScalarAssignmentBinding, + solution: &S, + entity_index: usize, + degrees: &FastMap, + values: &mut [usize], +) { + values.sort_by_key(|value| { + ( + degrees.get(value).copied().unwrap_or(usize::MAX), + group.value_order_key(solution, entity_index, *value), + *value, + ) + }); +} 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 7946e786..6b477d4a 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 @@ -7,7 +7,6 @@ use super::assignment_cycle::CycleWindowCursor; use super::assignment_entity::{AssignmentMoveKind, CapacityCursor, OptionalAdjustmentCursor}; use super::assignment_family::{AssignmentFamilyCursor, AssignmentMoveFamily}; use super::assignment_pair::PairWindowCursor; -use super::assignment_required_batch::required_batch_move; use super::assignment_state::ScalarAssignmentState; use super::assignment_value_index::{assigned_value_sequence_index, AssignedValueSequenceIndex}; use crate::builder::ScalarAssignmentBinding; @@ -26,7 +25,6 @@ where // candidate build rolls the state back, so the index content is // identical for every open within one step. index_cache: Option, - batch_required: bool, family_slots: Vec, family_pos: usize, seen: FastSet, @@ -62,7 +60,6 @@ where AssignmentMoveFamily::Required, AssignmentMoveFamily::EjectionReinsert, true, - false, ) } @@ -81,7 +78,6 @@ where AssignmentMoveFamily::Required, AssignmentMoveFamily::EjectionReinsert, true, - false, ); cursor.state = state; cursor @@ -93,21 +89,6 @@ where self.state } - pub(crate) fn required_construction( - group: &ScalarAssignmentBinding, - solution: &S, - options: ScalarAssignmentMoveOptions, - ) -> Self { - Self::from_family_range( - group, - solution, - options, - AssignmentMoveFamily::Required, - AssignmentMoveFamily::Required, - false, - true, - ) - } pub(super) fn exclude_completed_optional_entities( &mut self, group: &ScalarAssignmentBinding, @@ -142,7 +123,6 @@ where AssignmentMoveFamily::Required, AssignmentMoveFamily::Required, false, - false, ) } @@ -158,7 +138,6 @@ where AssignmentMoveFamily::OptionalAssign, AssignmentMoveFamily::OptionalAssign, false, - false, ) } @@ -169,7 +148,6 @@ where family: AssignmentMoveFamily, stop_after: AssignmentMoveFamily, spread_budget: bool, - batch_required: bool, ) -> Self { let families = if spread_budget { AssignmentMoveFamily::range(family, stop_after) @@ -180,7 +158,6 @@ where state: ScalarAssignmentState::new(group, solution), marker: std::marker::PhantomData, options, - batch_required, family_slots: families .into_iter() .map(|family| AssignmentFamilySlot { @@ -196,6 +173,47 @@ where } } + /* Carries the cursor across a finished placement instead of rebuilding + it: `touched` (sorted, deduplicated) holds every row an edit of the + placement's candidates names, so it covers the committed move. Rows whose + value changed are refreshed in the assignment state, required rows that + gained a value leave the value degrees, and generation resumes after + `placed`. Returns whether any row changed. */ + pub(super) fn resume_after_placement( + &mut self, + group: &ScalarAssignmentBinding, + solution: &S, + touched: &[usize], + placed: usize, + ) -> 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 { + 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); + } + } + } + } + let any_changed = !changed.is_empty(); + self.state.refresh_rows(group, solution, changed); + for slot in &mut self.family_slots { + slot.cursor.resume_after_placement(placed); + } + self.index_cache = None; + self.seen.clear(); + self.yielded = 0; + any_changed + } + pub(crate) fn next_move_with_control( &mut self, group: &ScalarAssignmentBinding, @@ -212,21 +230,6 @@ where return None; } - if self.batch_required { - let candidate = - required_batch_move(group, solution, &mut self.state, self.options, should_stop); - if let Some(candidate) = candidate { - self.batch_required = false; - self.seen.insert(normalized_move_key(&candidate)); - self.yielded += 1; - return Some(candidate); - } - if should_stop() { - return None; - } - self.batch_required = false; - } - let mut exhausted_turns = 0; while exhausted_turns < self.family_slots.len() { if should_stop() { diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/mod.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/mod.rs index 3156887b..35ada0e0 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/mod.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/mod.rs @@ -6,7 +6,7 @@ mod assignment_family; mod assignment_pair; mod assignment_path; mod assignment_path_overlay; -mod assignment_required_batch; +mod assignment_scarcity; mod assignment_state; mod assignment_stream; mod assignment_value_coordinates; @@ -18,6 +18,7 @@ mod move_build; mod phase; mod placement; mod placer; +mod placer_resume; mod placer_stream; #[cfg(test)] 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 77f05648..433ef55c 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer.rs @@ -8,6 +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_stream::{ assignment_placement_move_limit, next_assignment_placement, next_candidate_placement, AssignmentPlacementGenerator, CandidatePlacementSeed, ScalarGroupCandidateCursor, @@ -114,6 +115,9 @@ where /// per-placement provider rescan this replaces ran a full candidate /// enumeration for every pull. candidate_seeds: Option>>, + /// The last assignment placement's generator, carried into the next + /// placement so its state and row order are not rebuilt per placement. + resumable: Option>, } impl EntityPlacerCursor> for ScalarGroupPlacerCursor<'_, S> @@ -146,15 +150,36 @@ where &mut should_stop, ) } - ScalarGroupBindingKind::Assignment(assignment) => next_assignment_placement( - self.placer - .assignment_placement_generator(score_director, assignment)?, - score_director.working_solution(), - &mut is_completed, - &mut should_stop, - ), + ScalarGroupBindingKind::Assignment(assignment) => { + let solution = score_director.working_solution(); + // A carried generator that finds nothing more has finished a + // pass over its rows; a fresh one re-reads the solution, so + // rows skipped earlier get another pass. + if let Some(resumable) = self.resumable.take() { + let placement = next_assignment_placement( + resumable.resume(solution), + solution, + &mut is_completed, + &mut should_stop, + ); + if placement.is_some() || should_stop() { + return placement; + } + } + next_assignment_placement( + self.placer + .assignment_placement_generator(score_director, assignment)?, + solution, + &mut is_completed, + &mut should_stop, + ) + } } } + + fn recycle(&mut self, placement: ScalarGroupPlacement) { + self.resumable = placement.into_candidates().into_resumable(); + } } impl EntityPlacer> for ScalarGroupPlacer @@ -171,6 +196,7 @@ where ScalarGroupPlacerCursor { placer: self, candidate_seeds: None, + resumable: None, } } } @@ -315,9 +341,7 @@ where options, ); let options = options.with_max_moves(max_moves); - let cursor = if self.required_only { - ScalarAssignmentMoveCursor::required_construction(assignment, solution, options) - } else if target_required { + let cursor = if target_required { ScalarAssignmentMoveCursor::required(assignment, solution, options) } else { ScalarAssignmentMoveCursor::optional_construction(assignment, solution, options) @@ -330,6 +354,7 @@ where pending: None, options, accepted: 0, + completion_rows: None, }) } } 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 new file mode 100644 index 00000000..2f623474 --- /dev/null +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/placer_resume.rs @@ -0,0 +1,127 @@ +use solverforge_core::domain::PlanningSolution; +use solverforge_core::fast_hash::FastSet; + +use super::placement::assignment_group_slot; +use super::placer_stream::{AssignmentPlacementGenerator, ScalarGroupCandidateCursor}; +use crate::heuristic::r#move::CompoundScalarMove; +use crate::heuristic::selector::EntityReference; +use crate::phase::construction::{ConstructionSlotId, Placement}; + +/* A finished assignment placement handed back to the placer cursor: the +generator, the row it placed and every row its candidates' edits named. */ +pub(crate) struct ResumableAssignment +where + S: PlanningSolution + 'static, +{ + generator: AssignmentPlacementGenerator, + placed: usize, + touched: Vec, +} + +impl ResumableAssignment +where + S: PlanningSolution + 'static, +{ + pub(super) fn new( + generator: AssignmentPlacementGenerator, + placed: usize, + touched: Vec, + ) -> Self { + Self { + generator, + placed, + touched, + } + } + + /* The generator for the next placement, carried over the committed + move instead of rebuilt from the whole solution. */ + pub(super) fn resume(self, solution: &S) -> AssignmentPlacementGenerator { + let Self { + mut generator, + placed, + mut touched, + } = self; + touched.sort_unstable(); + touched.dedup(); + let changed = generator.cursor.resume_after_placement( + &generator.assignment, + solution, + &touched, + placed, + ); + generator.pending = None; + generator.accepted = 0; + match &mut generator.completion_rows { + Some(rows) if !changed => rows.push(placed), + rows => *rows = Some(vec![placed]), + } + generator + } +} + +pub(super) fn completed_assignment_slots( + generator: &mut AssignmentPlacementGenerator, + solution: &S, + is_completed: &mut IsCompleted, +) -> FastSet +where + S: PlanningSolution + 'static, + IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> 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) + }) + .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(); + generator.completion_rows = Some(rows); + completed +} + +fn assignment_slot_completed( + generator: &AssignmentPlacementGenerator, + solution: &S, + entity_index: usize, + is_completed: &mut IsCompleted, +) -> bool +where + S: PlanningSolution + 'static, + IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> 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 + .assignment + .current_value(solution, entity_index) + .is_none() + { + placement = + placement.with_group_slot(assignment_group_slot(generator.group_index, entity_index)); + } + is_completed(&placement) +} 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 94a1000c..3fa8c826 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,6 +5,7 @@ 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 crate::builder::context::{ScalarAssignmentBinding, ScalarCandidate, ScalarGroupBinding}; use crate::heuristic::r#move::CompoundScalarMove; use crate::heuristic::selector::move_selector::{ @@ -39,6 +40,12 @@ where pub(super) pending: Option>, pub(super) options: ScalarAssignmentMoveOptions, pub(super) accepted: usize, + /* Rows whose construction slots can be completed at the current solution + revision: unknown (`None`) until the first placement scans every row, + then the rows that scan found plus the rows placed since. A committed + move advances the revision, which voids every earlier completion, so a + change narrows the list to the placed row. */ + pub(super) completion_rows: Option>, } #[allow(clippy::large_enum_variant)] @@ -59,6 +66,7 @@ where active_entity: usize, completed_slots: FastSet, first: Option<(CompoundScalarMove, ConstructionTarget)>, + touched: Vec, }, } @@ -75,7 +83,7 @@ impl ScalarGroupCandidateCursor where S: PlanningSolution + 'static, { - fn empty() -> Self { + pub(super) fn empty() -> Self { Self { store: CandidateStore::new(), targets: Vec::new(), @@ -100,6 +108,12 @@ where completed_slots: FastSet, first: (CompoundScalarMove, ConstructionTarget), ) -> Self { + let touched = first + .0 + .edits() + .iter() + .map(|edit| edit.entity_index) + .collect(); Self { store: CandidateStore::new(), targets: Vec::new(), @@ -108,10 +122,25 @@ where active_entity, completed_slots, first: Some(first), + touched, }, } } + /* Hands an assignment placement's generator back for the next + placement; other sources keep nothing. */ + pub(super) fn into_resumable(self) -> Option> { + match self.source { + ScalarGroupCandidateSource::Assignment { + generator, + active_entity, + touched, + .. + } => Some(ResumableAssignment::new(generator, active_entity, touched)), + _ => None, + } + } + pub(super) fn construction_target( &self, candidate_id: CandidateId, @@ -153,6 +182,7 @@ where active_entity, completed_slots, first, + touched, } => { let (mov, target) = if let Some(first) = first.take() { first @@ -167,6 +197,7 @@ where generator.pending = Some(mov); return None; } + touched.extend(mov.edits().iter().map(|edit| edit.entity_index)); (mov, target) }; generator.accepted += 1; @@ -235,7 +266,7 @@ where IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> bool, ShouldStop: FnMut() -> bool, { - let completed_slots = completed_assignment_slots(&generator, solution, &mut is_completed); + let completed_slots = completed_assignment_slots(&mut generator, solution, &mut is_completed); if generator.accepted < generator.options.max_moves && !should_stop() { generator.cursor.exclude_completed_optional_entities( &generator.assignment, @@ -333,42 +364,6 @@ where } } -fn completed_assignment_slots( - generator: &AssignmentPlacementGenerator, - solution: &S, - is_completed: &mut IsCompleted, -) -> FastSet -where - S: PlanningSolution + 'static, - IsCompleted: FnMut(&Placement, ScalarGroupCandidateCursor>) -> bool, -{ - (0..generator.assignment.entity_count(solution)) - .filter_map(|entity_index| { - 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 batch members remain - // available as blockers in a later required augmenting rematch. - if 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_some(slot_id) - }) - .collect() -} - pub(super) fn assignment_placement_move_limit( heuristic: ConstructionHeuristicType, construction_obligation: ConstructionObligation, 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 067cd323..94b667c7 100644 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests.rs @@ -4,6 +4,8 @@ use std::any::{Any, TypeId}; #[path = "tests/augmenting_overlay.rs"] mod augmenting_overlay; +#[path = "tests/construction_resume.rs"] +mod construction_resume; #[path = "tests/ejection_differential.rs"] mod ejection_differential; #[path = "tests/neighborhood_contracts.rs"] @@ -12,8 +14,6 @@ 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"] @@ -32,10 +32,9 @@ use solverforge_scoring::ScoreDirector; use super::assignment_candidate::{ order_candidates, AssignmentMoveIntent, ScalarAssignmentMoveOptions, }; -use super::assignment_entity::required_value_degrees; use super::assignment_path::{assignment_move_for_entity_value, AssignmentRequest}; +use super::assignment_scarcity::required_value_degrees; use super::assignment_state::ScalarAssignmentState; -use super::assignment_stream::ScalarAssignmentMoveCursor; use super::build_scalar_group_construction; use crate::builder::{ RuntimeModel, ScalarAssignmentBinding, ScalarGroupBinding, ScalarGroupBindingKind, @@ -198,53 +197,8 @@ fn assignment_binding_with_candidate_values( } } -static DIRECT_BATCH_CANDIDATE_READS: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -fn tracked_direct_batch_candidates(plan: &AssignmentPlan, entity: usize, _: usize) -> &[usize] { - DIRECT_BATCH_CANDIDATE_READS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - &plan.candidates[entity] -} - -#[test] -fn required_batch_defers_augmenting_rematches() { - DIRECT_BATCH_CANDIDATE_READS.store(0, std::sync::atomic::Ordering::SeqCst); - let descriptor = descriptor(); - let limits = ScalarGroupLimits { - max_augmenting_depth: Some(4), - max_rematch_size: Some(8), - ..ScalarGroupLimits::new() - }; - let assignment = assignment_binding_with_candidate_values( - &descriptor, - limits, - tracked_direct_batch_candidates, - ); - let solution = AssignmentPlan { - score: None, - assignments: vec![None, None, None], - candidates: vec![vec![0, 2], vec![1, 2], vec![0, 1]], - }; - let mut cursor = ScalarAssignmentMoveCursor::required_construction( - &assignment, - &solution, - ScalarAssignmentMoveOptions::for_construction(limits), - ); - - let direct_batch = cursor - .next_move_with_control(&assignment, &solution, &mut || false) - .expect("direct required assignments must form a batch"); - - assert_eq!(direct_batch.edits().len(), 2); - assert_eq!( - DIRECT_BATCH_CANDIDATE_READS.load(std::sync::atomic::Ordering::SeqCst), - 21, - "the direct batch must not traverse augmenting rematch candidates" - ); -} - #[test] -fn required_construction_can_rematch_rows_assigned_by_its_batch_move() { +fn required_construction_rematches_rows_it_assigned() { let descriptor = descriptor(); let group = assignment_group( &descriptor, diff --git a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs new file mode 100644 index 00000000..a4f44299 --- /dev/null +++ b/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/construction_resume.rs @@ -0,0 +1,82 @@ +/* Required construction carried across placements. + +The placement cursor keeps its assignment state and row order from one +placement to the next, so a construction reads each row's domain a bounded +number of times instead of once per placement, and a required row takes a +free value before any value that needs an augmenting rematch. */ + +use std::cell::Cell; + +use super::*; + +thread_local! { + static DOMAIN_READS: Cell = const { Cell::new(0) }; +} + +fn counted_candidates(plan: &AssignmentPlan, entity: usize, _: usize) -> &[usize] { + DOMAIN_READS.with(|reads| reads.set(reads.get() + 1)); + &plan.candidates[entity] +} + +fn first_fit() -> ConstructionHeuristicConfig { + ConstructionHeuristicConfig { + construction_heuristic_type: ConstructionHeuristicType::FirstFit, + construction_obligation: ConstructionObligation::AssignWhenCandidateExists, + ..ConstructionHeuristicConfig::default() + } +} + +fn construct(group: ScalarGroupBinding, input: AssignmentPlan) -> AssignmentPlan { + let descriptor = descriptor(); + let bindings = collect_bindings(&descriptor) + .into_iter() + .map(ResolvedVariableBinding::new) + .collect(); + let director = ScoreDirector::simple(input, descriptor, |plan, _| plan.assignments.len()); + let mut scope = SolverScope::new(director); + let mut phase = build_scalar_group_construction(Some(&first_fit()), 0, group, bindings, true); + phase.solve(&mut scope); + scope.working_solution().clone() +} + +#[test] +fn required_construction_reads_each_domain_a_bounded_number_of_times() { + let reads_for = |rows: usize| { + let group = assignment_group_with_candidate_values( + &descriptor(), + ScalarGroupLimits::new(), + counted_candidates, + ); + let input = AssignmentPlan { + score: None, + assignments: vec![None; rows], + candidates: (0..rows).map(|entity| vec![entity]).collect(), + }; + DOMAIN_READS.with(|reads| reads.set(0)); + let solved = construct(group, input); + assert!(solved.assignments.iter().all(Option::is_some)); + DOMAIN_READS.with(Cell::get) + }; + let small = reads_for(256); + let large = reads_for(1024); + assert!( + large <= small * 5, + "domain reads grew from {small} at 256 rows to {large} at 1024 rows" + ); +} + +#[test] +fn required_rows_take_a_free_value_before_a_rematch() { + let group = assignment_group(&descriptor(), ScalarGroupLimits::new()); + let solved = construct( + group, + AssignmentPlan { + score: None, + // Row 1 lists the occupied value first; moving row 0 to value 2 + // would free it, but value 1 is free already. + assignments: vec![Some(0), None], + candidates: vec![vec![0, 2], vec![0, 1]], + }, + ); + assert_eq!(solved.assignments, vec![Some(0), Some(1)]); +} 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 c4439166..19ba06b5 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 @@ -36,90 +36,6 @@ fn augmenting_assignment_observes_control_during_recursive_search() { assert_eq!(state.current_value(2), None); } -#[test] -fn interrupted_required_batch_can_resume_without_partial_state() { - let descriptor = descriptor(); - let limits = ScalarGroupLimits { - max_augmenting_depth: Some(4), - max_rematch_size: Some(8), - ..ScalarGroupLimits::new() - }; - let assignment = assignment_binding(&descriptor, limits); - let entity_total = 100; - let solution = AssignmentPlan { - score: None, - assignments: vec![None; entity_total], - candidates: (0..entity_total).map(|value| vec![value]).collect(), - }; - let options = ScalarAssignmentMoveOptions::for_construction(limits); - let mut reference = - ScalarAssignmentMoveCursor::required_construction(&assignment, &solution, options); - let mut reference_polls = 0; - let complete = reference - .next_move_with_control(&assignment, &solution, &mut || { - reference_polls += 1; - false - }) - .expect("uninterrupted required batch must be generated"); - assert_eq!(complete.edits().len(), entity_total); - - let mut cursor = - ScalarAssignmentMoveCursor::required_construction(&assignment, &solution, options); - let mut polls = 0; - - let interrupted = cursor.next_move_with_control(&assignment, &solution, &mut || { - polls += 1; - polls >= reference_polls - }); - assert!(interrupted.is_none()); - - let resumed = cursor - .next_move_with_control(&assignment, &solution, &mut || false) - .expect("required batch must restart after interrupted generation"); - assert_eq!(resumed.edits().len(), entity_total); -} - -static PREPROCESSING_CANDIDATE_READS: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); - -fn tracked_preprocessing_candidates(plan: &AssignmentPlan, entity: usize, _: usize) -> &[usize] { - let previous = PREPROCESSING_CANDIDATE_READS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - assert_eq!( - previous, 0, - "degree preprocessing read candidates after control requested interruption" - ); - &plan.candidates[entity] -} - -#[test] -fn required_batch_polls_control_between_scarcity_and_degree_preprocessing() { - PREPROCESSING_CANDIDATE_READS.store(0, std::sync::atomic::Ordering::SeqCst); - let descriptor = descriptor(); - let limits = ScalarGroupLimits::new(); - let assignment = assignment_binding_with_candidate_values( - &descriptor, - limits, - tracked_preprocessing_candidates, - ); - let solution = AssignmentPlan { - score: None, - assignments: vec![None], - candidates: vec![vec![0]], - }; - let options = ScalarAssignmentMoveOptions::for_construction(limits); - let mut cursor = - ScalarAssignmentMoveCursor::required_construction(&assignment, &solution, options); - let interrupted = cursor.next_move_with_control(&assignment, &solution, &mut || { - PREPROCESSING_CANDIDATE_READS.load(std::sync::atomic::Ordering::SeqCst) >= 1 - }); - - assert!(interrupted.is_none()); - assert_eq!( - PREPROCESSING_CANDIDATE_READS.load(std::sync::atomic::Ordering::SeqCst), - 1 - ); -} - #[test] fn required_value_degrees_bounds_control_polling_for_dense_rows() { let descriptor = descriptor(); 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 cb07da11..71515317 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 @@ -150,6 +150,7 @@ fn reassignment_preserves_required_blocker_rematching() { value_degrees: FastMap::default(), options: options(), kind: AssignmentMoveKind::Reassignment, + augmenting: false, }; let candidate = cursor .next(&binding, &solution, &mut state, &mut || false) 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 deleted file mode 100644 index df9ba0c3..00000000 --- a/crates/solverforge-solver/src/phase/construction/grouped_scalar/tests/path_overlay_index.rs +++ /dev/null @@ -1,298 +0,0 @@ -/* 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/docs/configuration.md b/docs/configuration.md index dedf29f8..6cc608fe 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -139,9 +139,8 @@ fixed fleet. After list construction, a slot with route hooks and a non-empty route runs `ListKOpt` (`route_hooks_declared_and_route_non_empty`). -The dense required batch collects independent assignments directly. Bounded -augmenting rematches stay with the following required cursor rather than being -explored inside a batch that cannot retain multi-entity edits. Keeping an +Required assignment rows are placed one move at a time by the required cursor, +which tries a direct assignment and then bounded augmenting rematches. Keeping an optional assignment unassigned completes that decision without ending the optional pass. Completed optional roots are skipped before candidate-domain reads or move generation, so the candidate budget stays available for later