Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion crates/solverforge-solver/benches/selector_cursor_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<S> {
slot: RuntimeScalarSlot<S>,
snapshot: SwapSnapshot,
Expand All @@ -31,12 +35,39 @@ pub(super) struct SwapCursor<S> {
enum SwapSnapshot {
Static {
current_values: Vec<Option<usize>>,
legal_values: Vec<Vec<usize>>,
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<S>(value_source: &ValueSource<S>, 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<S> SwapCursor<S>
where
S: PlanningSolution,
Expand All @@ -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,
Expand Down Expand Up @@ -145,20 +172,17 @@ where
value: Option<usize>,
) -> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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<usize> = 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<usize> {
plan.values[entity_index]
}

fn row_set(plan: &mut Plan, entity_index: usize, _variable_index: usize, value: Option<usize>) {
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<Plan>,
allows_unassigned: bool,
) -> RuntimeScalarSlot<Plan> {
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: 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: &Plan,
entity_index: usize,
value: Option<usize>,
) -> 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: &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());
}
2 changes: 1 addition & 1 deletion scripts/bench-zero-regression.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading