Skip to content
Closed
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
2 changes: 1 addition & 1 deletion crates/solverforge-bridge/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ where
IDM: CrossEntityDistanceMeter<S> + Clone + Debug + Send + Sync + 'static,
{
Ok(DynamicSearchDeclaration {
context: SearchContext::new(descriptor, model, config.random_seed)?,
context: SearchContext::new(descriptor, model, config.resolved_random_seed())?,
})
}

Expand Down
21 changes: 16 additions & 5 deletions crates/solverforge-config/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Top-level solver configuration. Derives: `Debug, Clone, Default, Deserialize, Se
| Field | Type | Default | Note |
|-------|------|---------|------|
| `environment_mode` | `EnvironmentMode` | `NonReproducible` | `#[serde(default)]` |
| `random_seed` | `Option<u64>` | `None` | |
| `random_seed` | `Option<u64>` | `None` | Read through `resolved_random_seed()` |
| `move_thread_count` | `MoveThreadCount` | `Auto` | `#[serde(default)]` |
| `termination` | `Option<TerminationConfig>` | `None` | |
| `score_director` | `Option<DirectorConfig>` | `None` | Omitted: the `constraints` provider, snapshot analysis enabled |
Expand All @@ -73,6 +73,7 @@ Top-level solver configuration. Derives: `Debug, Clone, Default, Deserialize, Se
| `new` | `fn() -> Self` | Alias for `Default::default()` |
| `constraint_provider` | `fn(&self) -> Option<&str>` | `score_director.constraint_provider`; `None` selects `constraints` |
| `constraint_match_enabled` | `fn(&self) -> bool` | `score_director.constraint_match_enabled`; `true` when omitted |
| `resolved_random_seed` | `fn(&self) -> Option<u64>` | `random_seed`, or `REPRODUCIBLE_RANDOM_SEED` when omitted outside `NonReproducible`; `None` seeds from the operating system. Every seed consumer reads this |
| `load` | `fn(path: impl AsRef<Path>) -> Result<Self, ConfigError>` | Delegates to `from_toml_file` |
| `from_toml_file` | `fn(path: impl AsRef<Path>) -> Result<Self, ConfigError>` | Reads file, parses TOML |
| `from_toml_str` | `fn(s: &str) -> Result<Self, ConfigError>` | Parses TOML string |
Expand Down Expand Up @@ -722,10 +723,20 @@ Derives: `Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize`. T

| Variant | Note |
|---------|------|
| `NonReproducible` | **Default.** Minimal overhead |
| `Reproducible` | Deterministic behavior |
| `FastAssert` | Basic assertions |
| `FullAssert` | Comprehensive assertions |
| `NonReproducible` | **Default.** No checks; without `random_seed` each run seeds itself from the operating system |
| `Reproducible` | No checks; without `random_seed` the solve uses `REPRODUCIBLE_RANDOM_SEED`, so step- or move-bounded runs repeat exactly |
| `FastAssert` | As `Reproducible`, plus every committed step and best-solution update is checked against a fresh score (panics on drift) |
| `FullAssert` | As `FastAssert`, plus every score-director calculation, including each evaluated move on the main director and on evaluator replicas |

| Method | Signature | Note |
|--------|-----------|------|
| `asserts_steps` | `const fn(self) -> bool` | `FastAssert` and `FullAssert` |
| `asserts_every_score_calculation` | `const fn(self) -> bool` | `FullAssert` |

### `REPRODUCIBLE_RANDOM_SEED`

`pub const REPRODUCIBLE_RANDOM_SEED: u64 = 0` — the seed of a solve without
`random_seed` in every mode except `NonReproducible`.

### `MoveThreadCount`

Expand Down
1 change: 1 addition & 0 deletions crates/solverforge-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub use phase::{
};
pub use solver_config::{
CandidateTraceConfig, EnvironmentMode, MoveThreadCount, SolverConfig, SolverConfigOverride,
REPRODUCIBLE_RANDOM_SEED,
};
pub use termination::TerminationConfig;

Expand Down
51 changes: 44 additions & 7 deletions crates/solverforge-config/src/solver_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ pub struct SolverConfig {
pub environment_mode: EnvironmentMode,

/// Seed for the solver's random choices. Omitted: every run seeds itself
/// from the operating system, so runs differ.
/// from the operating system under `non_reproducible`, and uses
/// [`REPRODUCIBLE_RANDOM_SEED`] under every other environment mode. Read
/// it through [`SolverConfig::resolved_random_seed`].
#[serde(default)]
pub random_seed: Option<u64>,

Expand Down Expand Up @@ -73,6 +75,17 @@ impl SolverConfig {
.is_none_or(|director| director.constraint_match_enabled)
}

/// The seed the solve uses: `random_seed`, or [`REPRODUCIBLE_RANDOM_SEED`]
/// when it is omitted under any mode but `non_reproducible`. `None` means
/// a seed from the operating system.
pub fn resolved_random_seed(&self) -> Option<u64> {
match (self.random_seed, self.environment_mode) {
(Some(seed), _) => Some(seed),
(None, EnvironmentMode::NonReproducible) => None,
(None, _) => Some(REPRODUCIBLE_RANDOM_SEED),
}
}

/// Loads configuration from a TOML file.
///
/// # Errors
Expand Down Expand Up @@ -191,22 +204,46 @@ impl CandidateTraceConfig {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EnvironmentMode {
/// No extra runtime checks. Default.
/// No runtime checks. Without `random_seed`, every run seeds itself from
/// the operating system, so runs differ. Default.
#[default]
NonReproducible,

/// Currently runs exactly like `non_reproducible`; repeatable runs come
/// from setting `random_seed`.
/// No runtime checks. Without `random_seed`, the solve uses
/// [`REPRODUCIBLE_RANDOM_SEED`], so runs with the same input,
/// configuration and step or move-count limits produce the same result.
/// Time limits still end runs at different points.
Reproducible,

/// Currently runs exactly like `non_reproducible`.
/// Like `reproducible`, and at every committed step and best-solution
/// update asserts that the incremental score equals a fresh full
/// calculation, panicking on drift.
FastAssert,

/// On score calculation and best-solution updates, asserts that the
/// incremental score equals a fresh full calculation, panicking on drift.
/// Like `fast_assert`, and every score calculation of the score director,
/// including every evaluated move on the main director and on evaluator
/// replicas, is checked against a fresh full calculation.
FullAssert,
}

/// The seed a solve without `random_seed` uses in every mode except
/// `non_reproducible`.
pub const REPRODUCIBLE_RANDOM_SEED: u64 = 0;

impl EnvironmentMode {
/// Whether committed steps and best-solution updates are checked against a
/// fresh score: `fast_assert` and `full_assert`.
pub const fn asserts_steps(self) -> bool {
matches!(self, Self::FastAssert | Self::FullAssert)
}

/// Whether every score calculation is checked against a fresh score:
/// `full_assert`.
pub const fn asserts_every_score_calculation(self) -> bool {
matches!(self, Self::FullAssert)
}
}

/// Move thread count configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ fn generate_list_search_declaration_fn(input: ListSearchDeclarationInput<'_>) ->
let context = ::solverforge::__internal::SearchContext::new(
descriptor,
model,
config.random_seed,
config.resolved_random_seed(),
)?;
::core::result::Result::Ok(#search_fn(context))
}
Expand Down Expand Up @@ -188,7 +188,7 @@ fn generate_list_search_declaration_fn(input: ListSearchDeclarationInput<'_>) ->
let context = ::solverforge::__internal::SearchContext::new(
descriptor,
model,
config.random_seed,
config.resolved_random_seed(),
)?;
::core::result::Result::Ok(context.defaults())
}
Expand Down Expand Up @@ -244,7 +244,7 @@ fn generate_scalar_search_declaration_fn(
let context = ::solverforge::__internal::SearchContext::new(
descriptor,
model,
config.random_seed,
config.resolved_random_seed(),
)?;
::core::result::Result::Ok(#search_fn(context))
}
Expand Down Expand Up @@ -290,7 +290,7 @@ fn generate_scalar_search_declaration_fn(
let context = ::solverforge::__internal::SearchContext::new(
descriptor,
model,
config.random_seed,
config.resolved_random_seed(),
)?;
::core::result::Result::Ok(context.defaults())
}
Expand Down
1 change: 1 addition & 0 deletions crates/solverforge-scoring/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ pub use stream::{
| `working_solution_mut` | `fn working_solution_mut(&mut self) -> &mut S` | Mutable solution reference |
| `calculate_score` | `fn calculate_score(&mut self) -> S::Score` | Full score calculation |
| `fresh_score` | `fn fresh_score(&self) -> Option<S::Score>` | Optional scratch score without mutating committed director state; default `None` |
| `set_score_assertion` | `fn set_score_assertion(&mut self, enabled: bool)` | While enabled, every `calculate_score` panics when it differs from `fresh_score`; `ScoreDirector` implements it and its replicas inherit it; the default does nothing (no fresh score to compare) |
| `solution_descriptor` | `fn solution_descriptor(&self) -> &SolutionDescriptor` | Runtime metadata |
| `clone_working_solution` | `fn clone_working_solution(&self) -> S` | Deep copy |
| `before_variable_changed` | `fn before_variable_changed(&mut self, descriptor_index: usize, entity_index: usize)` | Pre-change notification |
Expand Down
3 changes: 2 additions & 1 deletion crates/solverforge-scoring/public-api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ trait constraint::relational::AdaptWeight: pub trait AdaptWeight<S: 'static, O:
constraint::relational::AdaptWeight: fn is_hard(&self, weight: &W) -> bool
trait constraint::relational::RowWeight: pub trait RowWeight<S: 'static, O: Operator<S>, Sc>: Send + Sync { // Required method fn score(&self, solution: &S, row: &O::View<'_>) -> Sc; }
constraint::relational::RowWeight: fn score(&self, solution: &S, row: &O::View<'_>) -> Sc
trait director::Director: pub trait Director<S: PlanningSolution>: Send { Show 17 methods // Required methods fn working_solution(&self) -> &S; fn working_solution_mut(&mut self) -> &mut S; fn calculate_score(&mut self) -> S::Score; fn solution_descriptor(&self) -> &SolutionDescriptor; fn clone_working_solution(&self) -> S; fn before_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn after_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn entity_count(&self, descriptor_index: usize) -> Option<usize>; fn total_entity_count(&self) -> Option<usize>; fn constraint_metadata(&self) -> Vec<ConstraintMetadata<'_>>; // Provided methods fn fresh_score(&self) -> Option<S::Score> { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option<bool> { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState<S::Score> { ... } fn restore_score_state(&mut self, state: DirectorScoreState<S::Score>) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option<Self> where Self: Sized { ... } }
trait director::Director: pub trait Director<S: PlanningSolution>: Send { Show 18 methods // Required methods fn working_solution(&self) -> &S; fn working_solution_mut(&mut self) -> &mut S; fn calculate_score(&mut self) -> S::Score; fn solution_descriptor(&self) -> &SolutionDescriptor; fn clone_working_solution(&self) -> S; fn before_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn after_variable_changed( &mut self, descriptor_index: usize, entity_index: usize, ); fn entity_count(&self, descriptor_index: usize) -> Option<usize>; fn total_entity_count(&self) -> Option<usize>; fn constraint_metadata(&self) -> Vec<ConstraintMetadata<'_>>; // Provided methods fn fresh_score(&self) -> Option<S::Score> { ... } fn set_score_assertion(&mut self, enabled: bool) { ... } fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option<bool> { ... } fn is_incremental(&self) -> bool { ... } fn snapshot_score_state(&self) -> DirectorScoreState<S::Score> { ... } fn restore_score_state(&mut self, state: DirectorScoreState<S::Score>) { ... } fn reset(&mut self) { ... } fn fork_replica(&self) -> Option<Self> where Self: Sized { ... } }
director::Director: fn working_solution(&self) -> &S
director::Director: fn working_solution_mut(&mut self) -> &mut S
director::Director: fn calculate_score(&mut self) -> S::Score
Expand All @@ -489,6 +489,7 @@ trait director::Director: pub trait Director<S: PlanningSolution>: Send { Show 1
director::Director: fn total_entity_count(&self) -> Option<usize>
director::Director: fn constraint_metadata(&self) -> Vec<ConstraintMetadata<'_>>
director::Director: fn fresh_score(&self) -> Option<S::Score>
director::Director: fn set_score_assertion(&mut self, enabled: bool)
director::Director: fn constraint_is_hard(&self, constraint_ref: &ConstraintRef) -> Option<bool>
director::Director: fn is_incremental(&self) -> bool
director::Director: fn snapshot_score_state(&self) -> DirectorScoreState<S::Score>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ where
Some(self.fresh_score_impl())
}

fn set_score_assertion(&mut self, enabled: bool) {
self.score_assertion = enabled;
}

fn solution_descriptor(&self) -> &SolutionDescriptor {
self.solution_descriptor.solution_descriptor()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ where
constraints,
cached_score: S::Score::zero(),
initialized: false,
score_assertion: false,
list_shadow_rows: ListShadowRows::default(),
weight_mode,
solution_descriptor,
Expand All @@ -143,6 +144,7 @@ where
constraints: self.constraints,
cached_score: self.cached_score,
initialized: false,
score_assertion: self.score_assertion,
list_shadow_rows: self.list_shadow_rows,
weight_mode,
solution_descriptor: self.solution_descriptor,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ where
pub(super) constraints: C,
pub(super) cached_score: S::Score,
pub(super) initialized: bool,
/// Whether every score calculation is checked against a fresh one.
pub(super) score_assertion: bool,
pub(super) list_shadow_rows: ListShadowRows,
/// The weight mode and, for `WeightedMode`, its bound multipliers.
pub(super) weight_mode: M,
Expand Down Expand Up @@ -134,6 +136,7 @@ where
descriptor,
self.entity_counter,
);
replica.score_assertion = self.score_assertion;
replica.calculate_score_impl();
Some(replica)
}
Expand All @@ -154,9 +157,24 @@ where
self.initialized = true;
}
self.working_solution.set_score(Some(self.cached_score));
if self.score_assertion {
self.assert_cached_score_is_fresh();
}
self.cached_score
}

#[cold]
#[inline(never)]
fn assert_cached_score_is_fresh(&self) {
let fresh = self.fresh_score_impl();
assert!(
self.cached_score == fresh,
"score director drift: incremental score {:?} != fresh score {:?}",
self.cached_score,
fresh
);
}

pub(crate) fn fresh_score_impl(&self) -> S::Score {
let mut solution = self.working_solution.clone();
solution.update_all_shadows();
Expand Down
8 changes: 8 additions & 0 deletions crates/solverforge-scoring/src/director/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ pub trait Director<S: PlanningSolution>: Send {
None
}

/// Turns score assertion on or off: while on, every [`Self::calculate_score`]
/// panics when the score differs from [`Self::fresh_score`]. A director
/// without a fresh calculation (`fresh_score` returns `None`) has nothing
/// to compare against, so the default does nothing.
fn set_score_assertion(&mut self, enabled: bool) {
let _ = enabled;
}

/// Returns the solution descriptor for this solution type.
fn solution_descriptor(&self) -> &SolutionDescriptor;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ fn dynamic_successors_only_metadata_executes_for_list_ruin_without_duration() {
..SolverConfig::default()
};

let context = SearchContext::new(descriptor(), model, config.random_seed)
let context = SearchContext::new(descriptor(), model, config.resolved_random_seed())
.expect("search context should bind");
compile_runtime_graph(
&config,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,10 @@ impl Solvable for ZeroVariableLifecycleSolution {
DefaultCrossEntityDistanceMeter,
DefaultCrossEntityDistanceMeter,
>::new(Vec::new());
Ok(SearchContext::new(descriptor, model, config.random_seed)?.defaults())
Ok(
SearchContext::new(descriptor, model, config.resolved_random_seed())?
.defaults(),
)
},
);
assert!(
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-solver/src/run_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ fn zero_variable_run_builds_the_normal_graph_and_search_declaration() {
DefaultCrossEntityDistanceMeter,
DefaultCrossEntityDistanceMeter,
>::new(Vec::new());
Ok(SearchContext::new(descriptor, model, config.random_seed)?.defaults())
Ok(SearchContext::new(descriptor, model, config.resolved_random_seed())?.defaults())
},
);

Expand Down
6 changes: 3 additions & 3 deletions crates/solverforge-solver/src/runtime/compiler/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ where
validate_best_score_limits::<S::Score>(config)?;
validate_selector_values(config)?;
let (context, extensions) = input.into_parts();
if context.seed() != config.random_seed {
if context.seed() != config.resolved_random_seed() {
return Err(RuntimeCompileError {
path: "runtime_extension_context.random_seed".to_string(),
kind: RuntimeCompileErrorKind::ContextSeedMismatch {
config_seed: config.random_seed,
config_seed: config.resolved_random_seed(),
context_seed: context.seed(),
},
});
Expand All @@ -55,7 +55,7 @@ where
context.descriptor(),
context.model(),
needs_omitted_local_search,
config.random_seed,
config.resolved_random_seed(),
)?;
let phases = if config.phases.is_empty() {
// Defaults are explicitly retained as a graph node. They are
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ fn default_plan(model: Model) -> DefaultLocalSearchPlan {
}

fn default_plan_with_config(model: Model, config: SolverConfig) -> DefaultLocalSearchPlan {
let context = SearchContext::new(descriptor(), model, config.random_seed)
let context = SearchContext::new(descriptor(), model, config.resolved_random_seed())
.expect("search context should bind");
compile_runtime_graph(
&config,
Expand Down Expand Up @@ -429,8 +429,12 @@ fn omitted_explicit_acceptor_forager_phase_refs_the_compiled_default_declaration
})],
..SolverConfig::default()
};
let context = SearchContext::new(descriptor(), dynamic_scalar_model(), config.random_seed)
.expect("search context should bind");
let context = SearchContext::new(
descriptor(),
dynamic_scalar_model(),
config.resolved_random_seed(),
)
.expect("search context should bind");
let graph = compile_runtime_graph(
&config,
RuntimeGraphInput::new(context, NoDynamicExtensions),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ fn omitted_selector_provenance_keeps_the_explicit_local_search_policy() {
phases: vec![PhaseConfig::LocalSearch(local_search)],
..SolverConfig::default()
};
let context = SearchContext::new(descriptor(), dynamic_scalar_model(), config.random_seed)
.expect("search context should bind");
let context = SearchContext::new(
descriptor(),
dynamic_scalar_model(),
config.resolved_random_seed(),
)
.expect("search context should bind");
let graph = compile_runtime_graph(
&config,
RuntimeGraphInput::new(context, NoDynamicExtensions),
Expand Down
Loading
Loading