diff --git a/AGENTS.md b/AGENTS.md index 36d8e793..3ba801fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -293,8 +293,8 @@ runs: - The compiled list leaf `RuntimeListNeighborhoodCursor` (list change, swap, nearby change and swap, sublist change and swap, and k-opt) over the shared `list_kernel` emitters. -- The scalar neighborhood leaf `RuntimeScalarNeighborhoodCursor` (change and - ruin/recreate). +- The scalar neighborhood leaf `RuntimeScalarNeighborhoodCursor` (change, + swap and ruin/recreate). - The descriptor-placement scalar construction placer (`RuntimeScalarConstructionPlacer`) and the compiled runtime phase runner that solves first-fit construction. diff --git a/crates/solverforge-solver/benches/selector_cursor_gate.rs b/crates/solverforge-solver/benches/selector_cursor_gate.rs index e3f37ffe..5ebacc6c 100644 --- a/crates/solverforge-solver/benches/selector_cursor_gate.rs +++ b/crates/solverforge-solver/benches/selector_cursor_gate.rs @@ -21,7 +21,8 @@ use solverforge_config::{ ConstructionHeuristicType, KOptMoveSelectorConfig, ListChangeMoveConfig, ListSwapMoveConfig, LocalSearchConfig, MoveSelectorConfig, NearbyListChangeMoveConfig, NearbyListSwapMoveConfig, PhaseConfig, RuinRecreateMoveSelectorConfig, SelectionOrder, SolverConfig, - SublistChangeMoveConfig, SublistSwapMoveConfig, UnionMoveSelectorConfig, VariableTargetConfig, + SublistChangeMoveConfig, SublistSwapMoveConfig, SwapMoveConfig, UnionMoveSelectorConfig, + VariableTargetConfig, }; use solverforge_core::domain::{ EntityCollectionExtractor, EntityDescriptor, PlanningSolution, SolutionDescriptor, @@ -178,6 +179,7 @@ fn main() { run_case!(case, matched, "k_opt", k_opt); run_case!(case, matched, "ruin", ruin); run_case!(case, matched, "scalar_change", scalar_change); + run_case!(case, matched, "scalar_swap", scalar_swap); run_case!(case, matched, "construction_full", construction_full); run_case!( case, diff --git a/crates/solverforge-solver/benches/selector_cursor_gate/scalar_cases.rs b/crates/solverforge-solver/benches/selector_cursor_gate/scalar_cases.rs index a1822ba9..4ad60747 100644 --- a/crates/solverforge-solver/benches/selector_cursor_gate/scalar_cases.rs +++ b/crates/solverforge-solver/benches/selector_cursor_gate/scalar_cases.rs @@ -21,6 +21,25 @@ fn scalar_change() { ); } +/* Every entity's value lies inside a 4,096-value range, so every pair of +distinct values is a legal exchange. The range dwarfs the entity count, which +is the shape where opening the cursor must not scale with the value range. */ +fn scalar_swap() { + neighborhood_case( + "scalar_swap", + 18_336, + scalar_director(routed_plan(192, 1), 1), + compile_neighborhood( + scalar_context(vec![first_slot(0..4_096)]), + MoveSelectorConfig::SwapMoveSelector(SwapMoveConfig { + selection_order: CANONICAL, + target: target("first"), + ..SwapMoveConfig::default() + }), + ), + ); +} + /* The value ranges lie outside the plan's current values, so every right leg stays doable under its left leg's preview. */ fn cartesian() { diff --git a/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/cursor/swap.rs b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/cursor/swap.rs index 5f39e3e4..fc68e2e2 100644 --- a/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/cursor/swap.rs +++ b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/cursor/swap.rs @@ -16,9 +16,13 @@ const ENTITY_STRIDE_MIX: u64 = 0xD1B5_4A32_D192_ED03; /// Complete scalar exchange enumeration for one frozen slot. /// -/// Native slots eagerly snapshot their values and legal rows, matching the -/// historic selector's source timing. Dynamic slots retain their existing -/// direct legality calls while traversing the same candidate ordering. +/// Native slots snapshot every entity's current value at open and test value +/// legality against the slot's value source without materializing it: a +/// counted or ranged source is a bounds check against the range read at open, +/// and an entity-slice source is looked up in the borrowed slice. Opening the +/// cursor is therefore linear in the entity count, independent of the value +/// range. Dynamic slots retain their existing direct legality calls while +/// traversing the same candidate ordering. pub(super) struct SwapCursor { slot: RuntimeScalarSlot, snapshot: SwapSnapshot, @@ -31,12 +35,39 @@ pub(super) struct SwapCursor { enum SwapSnapshot { Static { current_values: Vec>, - legal_values: Vec>, - empty_value_source: bool, + legality: StaticSwapLegality, }, Dynamic, } +/// Value legality of a native slot, resolved once at cursor open. +#[derive(Clone, Copy)] +enum StaticSwapLegality { + /// An empty value source: any assigned value may be exchanged. + AnyAssigned, + /// A counted or ranged source: values `from..to`, read at open. + Range { from: usize, to: usize }, + /// A per-entity slice source, looked up in the borrowed slice. + EntitySlice, +} + +impl StaticSwapLegality { + fn of(value_source: &ValueSource, solution: &S) -> Self { + match *value_source { + ValueSource::Empty => Self::AnyAssigned, + ValueSource::CountableRange { from, to } => Self::Range { from, to }, + ValueSource::SolutionCount { + count_fn, + provider_index, + } => Self::Range { + from: 0, + to: count_fn(solution, provider_index), + }, + ValueSource::EntitySlice { .. } => Self::EntitySlice, + } + } +} + impl SwapCursor where S: PlanningSolution, @@ -52,13 +83,9 @@ where let current_values = (0..entity_count) .map(|entity_index| slot.current_value(solution, entity_index)) .collect(); - let legal_values = (0..entity_count) - .map(|entity_index| static_slot.values_for_entity(solution, entity_index)) - .collect(); SwapSnapshot::Static { current_values, - legal_values, - empty_value_source: matches!(static_slot.value_source, ValueSource::Empty), + legality: StaticSwapLegality::of(&static_slot.value_source, solution), } } RuntimeScalarSlot::Dynamic(_) => SwapSnapshot::Dynamic, @@ -145,20 +172,17 @@ where value: Option, ) -> bool { match &self.snapshot { - SwapSnapshot::Static { - legal_values, - empty_value_source, - .. - } => { - if *empty_value_source { - value.is_some() - } else { - match value { - Some(value) => legal_values[entity_index].contains(&value), - None => self.slot.allows_unassigned(), - } + SwapSnapshot::Static { legality, .. } => match (*legality, value) { + (StaticSwapLegality::AnyAssigned, value) => value.is_some(), + (StaticSwapLegality::Range { from, to }, Some(value)) => { + from <= value && value < to } - } + (StaticSwapLegality::Range { .. }, None) => self.slot.allows_unassigned(), + (StaticSwapLegality::EntitySlice, value) => { + self.slot + .swap_destination_is_legal(solution, entity_index, value) + } + }, SwapSnapshot::Dynamic => { self.slot .swap_destination_is_legal(solution, entity_index, value) diff --git a/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests.rs b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests.rs index d4570af0..6241ef0a 100644 --- a/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests.rs +++ b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests.rs @@ -17,6 +17,7 @@ use solverforge_scoring::ScoreDirector; use crate::heuristic::selector::MoveSelector; mod coverage; +mod swap_legality; // Per-thread probes: the test harness runs tests concurrently, and every test // here drives the same nearby-source callbacks on its own thread. diff --git a/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests/swap_legality.rs b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests/swap_legality.rs new file mode 100644 index 00000000..be723cbc --- /dev/null +++ b/crates/solverforge-solver/src/heuristic/selector/scalar_neighborhood/tests/swap_legality.rs @@ -0,0 +1,210 @@ +//! Native scalar swap legality against every value source, without +//! materializing the value range at cursor open. + +use std::cell::Cell; + +use super::*; +use crate::builder::{RuntimeScalarSlot, ScalarVariableSlot, ValueSource}; +use crate::heuristic::selector::move_selector::{MoveCursor, MoveStreamContext}; +use crate::heuristic::selector::scalar_neighborhood::spec::{ + RuntimeScalarRecipe, ScalarNeighborhoodSpec, +}; +use crate::heuristic::selector::scalar_neighborhood::ScalarNeighborhoodLeaf; + +thread_local! { + static COUNT_CALLS: Cell = const { Cell::new(0) }; +} + +fn row_count(plan: &Plan) -> usize { + plan.values.len() +} + +fn row_get(plan: &Plan, entity_index: usize, _variable_index: usize) -> Option { + plan.values[entity_index] +} + +fn row_set(plan: &mut Plan, entity_index: usize, _variable_index: usize, value: Option) { + plan.values[entity_index] = value; +} + +fn candidate_count(plan: &Plan, _provider_index: usize) -> usize { + COUNT_CALLS.with(|calls| calls.set(calls.get() + 1)); + plan.candidates.len() +} + +fn huge_count(_plan: &Plan, _provider_index: usize) -> usize { + COUNT_CALLS.with(|calls| calls.set(calls.get() + 1)); + 1 << 40 +} + +/// Each entity accepts a different suffix of the candidate list. +fn candidate_suffix(plan: &Plan, entity_index: usize, _variable_index: usize) -> &[usize] { + &plan.candidates[entity_index.min(plan.candidates.len())..] +} + +fn static_slot( + value_source: ValueSource, + allows_unassigned: bool, +) -> RuntimeScalarSlot { + RuntimeScalarSlot::Static(ScalarVariableSlot::new( + 0, + 0, + "Row", + row_count, + "value", + row_get, + row_set, + value_source, + allows_unassigned, + )) +} + +fn swap_pairs(slot: RuntimeScalarSlot, plan: Plan) -> Vec<(usize, usize)> { + let director = director(plan); + let leaf = ScalarNeighborhoodLeaf::from_spec(ScalarNeighborhoodSpec::Swap, slot, Some(23)) + .expect("static slot supplies the swap capability"); + let mut state = leaf.new_stream_state(); + let mut cursor = + leaf.open_cursor_with_stream_state(&mut state, &director, MoveStreamContext::default()); + let mut pairs = Vec::new(); + while let Some(mov) = cursor.next_owned_candidate(director.working_solution()) { + match mov.into_recipe() { + RuntimeScalarRecipe::Swap { + left_entity_index, + right_entity_index, + .. + } => pairs.push((left_entity_index, right_entity_index)), + _ => panic!("the swap leaf emits only swap recipes"), + } + } + pairs +} + +/// The legality rule the eager per-entity snapshot applied: membership in the +/// materialized value list, `None` per the slot, any assigned value for an +/// empty source. +fn legal_by_materialized_values( + slot: &RuntimeScalarSlot, + plan: &Plan, + entity_index: usize, + value: Option, +) -> bool { + let RuntimeScalarSlot::Static(slot) = slot else { + unreachable!("these tests drive native slots"); + }; + if matches!(slot.value_source, ValueSource::Empty) { + return value.is_some(); + } + match value { + Some(value) => slot.values_for_entity(plan, entity_index).contains(&value), + None => slot.allows_unassigned, + } +} + +fn expected_pairs(slot: &RuntimeScalarSlot, plan: &Plan) -> Vec<(usize, usize)> { + let mut pairs = Vec::new(); + for left in 0..plan.values.len() { + for right in (left + 1)..plan.values.len() { + let (left_value, right_value) = (plan.values[left], plan.values[right]); + if left_value != right_value + && legal_by_materialized_values(slot, plan, left, right_value) + && legal_by_materialized_values(slot, plan, right, left_value) + { + pairs.push((left, right)); + } + } + } + pairs +} + +fn plan() -> Plan { + Plan { + values: vec![ + Some(0), + Some(3), + None, + Some(1), + Some(7), + Some(2), + Some(1), + None, + ], + candidates: vec![0, 1, 2, 3], + score: None, + } +} + +#[test] +fn swap_legality_matches_the_materialized_value_rule_for_every_source() { + let sources = [ + ValueSource::Empty, + ValueSource::CountableRange { from: 1, to: 4 }, + ValueSource::SolutionCount { + count_fn: candidate_count, + provider_index: 0, + }, + ValueSource::EntitySlice { + values_for_entity: candidate_suffix, + }, + ]; + for source in sources { + for allows_unassigned in [false, true] { + let slot = static_slot(source, allows_unassigned); + let expected = expected_pairs(&slot, &plan()); + let mut actual = swap_pairs(slot, plan()); + let emitted = actual.len(); + actual.sort_unstable(); + actual.dedup(); + assert_eq!(actual.len(), emitted, "{source:?}: no pair repeats"); + assert_eq!( + actual, expected, + "{source:?}, allows_unassigned={allows_unassigned}" + ); + } + } +} + +#[test] +fn counted_source_is_read_once_at_cursor_open() { + COUNT_CALLS.with(|calls| calls.set(0)); + let slot = static_slot( + ValueSource::SolutionCount { + count_fn: candidate_count, + provider_index: 0, + }, + false, + ); + let director = director(plan()); + let leaf = ScalarNeighborhoodLeaf::from_spec(ScalarNeighborhoodSpec::Swap, slot, Some(23)) + .expect("static slot supplies the swap capability"); + let mut state = leaf.new_stream_state(); + let mut cursor = + leaf.open_cursor_with_stream_state(&mut state, &director, MoveStreamContext::default()); + assert_eq!(COUNT_CALLS.with(Cell::get), 1, "the count is read at open"); + while cursor + .next_owned_candidate(director.working_solution()) + .is_some() + {} + assert_eq!( + COUNT_CALLS.with(Cell::get), + 1, + "enumeration tests against the count read at open" + ); +} + +#[test] +fn opening_never_materializes_the_value_range() { + // A 2^40-value range cannot be collected per entity; the cursor must + // bound-check against it instead. + COUNT_CALLS.with(|calls| calls.set(0)); + let slot = static_slot( + ValueSource::SolutionCount { + count_fn: huge_count, + provider_index: 0, + }, + false, + ); + let pairs = swap_pairs(slot, plan()); + assert_eq!(COUNT_CALLS.with(Cell::get), 1); + assert!(!pairs.is_empty()); +} diff --git a/scripts/bench-zero-regression.sh b/scripts/bench-zero-regression.sh index 277e3262..ab55d99e 100755 --- a/scripts/bench-zero-regression.sh +++ b/scripts/bench-zero-regression.sh @@ -85,7 +85,7 @@ RESULTS=${RESULTS:-"/tmp/solverforge-zero-regression-$(date +%Y%m%d-%H%M%S)"} # scoring_weights_one scoring_weights_mixed" measures incremental score-director # churn through uni, join, shared grouped, and balance constraints; see # crates/solverforge-solver/benches/selector_cursor_gate/scoring_cases.rs. -DEFAULT_CASES=(list_change list_swap nearby_change nearby_swap sublist_change sublist_swap union cartesian k_opt ruin scalar_change construction_full construction_first_fit) +DEFAULT_CASES=(list_change list_swap nearby_change nearby_swap sublist_change sublist_swap union cartesian k_opt ruin scalar_change scalar_swap construction_full construction_first_fit) if [[ -n ${BENCH_CASES:-} ]]; then read -r -a CASES <<<"$BENCH_CASES" else